xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 9e269eafebfca6c876be76a78e4bda621a921e45)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011, 2025 Chelsio Communications.
5  * Written by: Navdeep Parhar <np@FreeBSD.org>
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 #include "opt_ddb.h"
31 #include "opt_inet.h"
32 #include "opt_inet6.h"
33 #include "opt_kern_tls.h"
34 #include "opt_ratelimit.h"
35 #include "opt_rss.h"
36 
37 #include <sys/param.h>
38 #include <sys/conf.h>
39 #include <sys/priv.h>
40 #include <sys/kernel.h>
41 #include <sys/bus.h>
42 #include <sys/eventhandler.h>
43 #include <sys/module.h>
44 #include <sys/malloc.h>
45 #include <sys/queue.h>
46 #include <sys/taskqueue.h>
47 #include <dev/pci/pcireg.h>
48 #include <dev/pci/pcivar.h>
49 #include <sys/firmware.h>
50 #include <sys/sbuf.h>
51 #include <sys/smp.h>
52 #include <sys/socket.h>
53 #include <sys/sockio.h>
54 #include <sys/sysctl.h>
55 #include <net/ethernet.h>
56 #include <net/if.h>
57 #include <net/if_types.h>
58 #include <net/if_dl.h>
59 #include <net/if_vlan_var.h>
60 #ifdef RSS
61 #include <net/rss_config.h>
62 #endif
63 #include <netinet/in.h>
64 #include <netinet/ip.h>
65 #ifdef KERN_TLS
66 #include <netinet/tcp_seq.h>
67 #endif
68 #if defined(__i386__) || defined(__amd64__)
69 #include <machine/md_var.h>
70 #include <machine/cputypes.h>
71 #include <vm/vm.h>
72 #include <vm/pmap.h>
73 #endif
74 #ifdef DDB
75 #include <ddb/ddb.h>
76 #include <ddb/db_lex.h>
77 #endif
78 
79 #include "common/common.h"
80 #include "common/t4_msg.h"
81 #include "common/t4_regs.h"
82 #include "common/t4_regs_values.h"
83 #include "cudbg/cudbg.h"
84 #include "t4_clip.h"
85 #include "t4_ioctl.h"
86 #include "t4_l2t.h"
87 #include "t4_mp_ring.h"
88 #include "t4_if.h"
89 #include "t4_smt.h"
90 
91 /* T4 bus driver interface */
92 static int t4_probe(device_t);
93 static int t4_attach(device_t);
94 static int t4_detach(device_t);
95 static int t4_child_location(device_t, device_t, struct sbuf *);
96 static int t4_ready(device_t);
97 static int t4_read_port_device(device_t, int, device_t *);
98 static int t4_suspend(device_t);
99 static int t4_resume(device_t);
100 static int t4_reset_prepare(device_t, device_t);
101 static int t4_reset_post(device_t, device_t);
102 static device_method_t t4_methods[] = {
103 	DEVMETHOD(device_probe,		t4_probe),
104 	DEVMETHOD(device_attach,	t4_attach),
105 	DEVMETHOD(device_detach,	t4_detach),
106 	DEVMETHOD(device_suspend,	t4_suspend),
107 	DEVMETHOD(device_resume,	t4_resume),
108 
109 	DEVMETHOD(bus_child_location,	t4_child_location),
110 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
111 	DEVMETHOD(bus_reset_post,	t4_reset_post),
112 
113 	DEVMETHOD(t4_is_main_ready,	t4_ready),
114 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
115 
116 	DEVMETHOD_END
117 };
118 static driver_t t4_driver = {
119 	"t4nex",
120 	t4_methods,
121 	sizeof(struct adapter)
122 };
123 
124 
125 /* T4 port (cxgbe) interface */
126 static int cxgbe_probe(device_t);
127 static int cxgbe_attach(device_t);
128 static int cxgbe_detach(device_t);
129 device_method_t cxgbe_methods[] = {
130 	DEVMETHOD(device_probe,		cxgbe_probe),
131 	DEVMETHOD(device_attach,	cxgbe_attach),
132 	DEVMETHOD(device_detach,	cxgbe_detach),
133 	{ 0, 0 }
134 };
135 static driver_t cxgbe_driver = {
136 	"cxgbe",
137 	cxgbe_methods,
138 	sizeof(struct port_info)
139 };
140 
141 /* T4 VI (vcxgbe) interface */
142 static int vcxgbe_probe(device_t);
143 static int vcxgbe_attach(device_t);
144 static int vcxgbe_detach(device_t);
145 static device_method_t vcxgbe_methods[] = {
146 	DEVMETHOD(device_probe,		vcxgbe_probe),
147 	DEVMETHOD(device_attach,	vcxgbe_attach),
148 	DEVMETHOD(device_detach,	vcxgbe_detach),
149 	{ 0, 0 }
150 };
151 static driver_t vcxgbe_driver = {
152 	"vcxgbe",
153 	vcxgbe_methods,
154 	sizeof(struct vi_info)
155 };
156 
157 static d_ioctl_t t4_ioctl;
158 
159 static struct cdevsw t4_cdevsw = {
160        .d_version = D_VERSION,
161        .d_ioctl = t4_ioctl,
162        .d_name = "t4nex",
163 };
164 
165 /* T5 bus driver interface */
166 static int t5_probe(device_t);
167 static device_method_t t5_methods[] = {
168 	DEVMETHOD(device_probe,		t5_probe),
169 	DEVMETHOD(device_attach,	t4_attach),
170 	DEVMETHOD(device_detach,	t4_detach),
171 	DEVMETHOD(device_suspend,	t4_suspend),
172 	DEVMETHOD(device_resume,	t4_resume),
173 
174 	DEVMETHOD(bus_child_location,	t4_child_location),
175 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
176 	DEVMETHOD(bus_reset_post,	t4_reset_post),
177 
178 	DEVMETHOD(t4_is_main_ready,	t4_ready),
179 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
180 
181 	DEVMETHOD_END
182 };
183 static driver_t t5_driver = {
184 	"t5nex",
185 	t5_methods,
186 	sizeof(struct adapter)
187 };
188 
189 
190 /* T5 port (cxl) interface */
191 static driver_t cxl_driver = {
192 	"cxl",
193 	cxgbe_methods,
194 	sizeof(struct port_info)
195 };
196 
197 /* T5 VI (vcxl) interface */
198 static driver_t vcxl_driver = {
199 	"vcxl",
200 	vcxgbe_methods,
201 	sizeof(struct vi_info)
202 };
203 
204 /* T6 bus driver interface */
205 static int t6_probe(device_t);
206 static device_method_t t6_methods[] = {
207 	DEVMETHOD(device_probe,		t6_probe),
208 	DEVMETHOD(device_attach,	t4_attach),
209 	DEVMETHOD(device_detach,	t4_detach),
210 	DEVMETHOD(device_suspend,	t4_suspend),
211 	DEVMETHOD(device_resume,	t4_resume),
212 
213 	DEVMETHOD(bus_child_location,	t4_child_location),
214 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
215 	DEVMETHOD(bus_reset_post,	t4_reset_post),
216 
217 	DEVMETHOD(t4_is_main_ready,	t4_ready),
218 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
219 
220 	DEVMETHOD_END
221 };
222 static driver_t t6_driver = {
223 	"t6nex",
224 	t6_methods,
225 	sizeof(struct adapter)
226 };
227 
228 
229 /* T6 port (cc) interface */
230 static driver_t cc_driver = {
231 	"cc",
232 	cxgbe_methods,
233 	sizeof(struct port_info)
234 };
235 
236 /* T6 VI (vcc) interface */
237 static driver_t vcc_driver = {
238 	"vcc",
239 	vcxgbe_methods,
240 	sizeof(struct vi_info)
241 };
242 
243 /* T7+ bus driver interface */
244 static int ch_probe(device_t);
245 static device_method_t ch_methods[] = {
246 	DEVMETHOD(device_probe,		ch_probe),
247 	DEVMETHOD(device_attach,	t4_attach),
248 	DEVMETHOD(device_detach,	t4_detach),
249 	DEVMETHOD(device_suspend,	t4_suspend),
250 	DEVMETHOD(device_resume,	t4_resume),
251 
252 	DEVMETHOD(bus_child_location,	t4_child_location),
253 	DEVMETHOD(bus_reset_prepare, 	t4_reset_prepare),
254 	DEVMETHOD(bus_reset_post, 	t4_reset_post),
255 
256 	DEVMETHOD(t4_is_main_ready,	t4_ready),
257 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
258 
259 	DEVMETHOD_END
260 };
261 static driver_t ch_driver = {
262 	"chnex",
263 	ch_methods,
264 	sizeof(struct adapter)
265 };
266 
267 
268 /* T7+ port (che) interface */
269 static driver_t che_driver = {
270 	"che",
271 	cxgbe_methods,
272 	sizeof(struct port_info)
273 };
274 
275 /* T7+ VI (vche) interface */
276 static driver_t vche_driver = {
277 	"vche",
278 	vcxgbe_methods,
279 	sizeof(struct vi_info)
280 };
281 
282 /* ifnet interface */
283 static void cxgbe_init(void *);
284 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
285 static int cxgbe_transmit(if_t, struct mbuf *);
286 static void cxgbe_qflush(if_t);
287 #if defined(KERN_TLS) || defined(RATELIMIT)
288 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
289     struct m_snd_tag **);
290 #endif
291 
292 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
293 
294 /*
295  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
296  * then ADAPTER_LOCK, then t4_uld_list_lock.
297  */
298 static struct sx t4_list_lock;
299 SLIST_HEAD(, adapter) t4_list;
300 #ifdef TCP_OFFLOAD
301 static struct sx t4_uld_list_lock;
302 struct uld_info *t4_uld_list[ULD_MAX + 1];
303 #endif
304 
305 /*
306  * Tunables.  See tweak_tunables() too.
307  *
308  * Each tunable is set to a default value here if it's known at compile-time.
309  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
310  * provide a reasonable default (upto n) when the driver is loaded.
311  *
312  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
313  * T5 are under hw.cxl.
314  */
315 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
316     "cxgbe(4) parameters");
317 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
318     "cxgbe(4) T5+ parameters");
319 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
320     "cxgbe(4) TOE parameters");
321 
322 /*
323  * Number of queues for tx and rx, NIC and offload.
324  */
325 #define NTXQ 16
326 int t4_ntxq = -NTXQ;
327 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
328     "Number of TX queues per port");
329 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
330 
331 #define NRXQ 8
332 int t4_nrxq = -NRXQ;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
334     "Number of RX queues per port");
335 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
336 
337 #define NTXQ_VI 1
338 static int t4_ntxq_vi = -NTXQ_VI;
339 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
340     "Number of TX queues per VI");
341 
342 #define NRXQ_VI 1
343 static int t4_nrxq_vi = -NRXQ_VI;
344 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
345     "Number of RX queues per VI");
346 
347 static int t4_rsrv_noflowq = 0;
348 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
349     0, "Reserve TX queue 0 of each VI for non-flowid packets");
350 
351 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
352 #define NOFLDTXQ 8
353 static int t4_nofldtxq = -NOFLDTXQ;
354 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
355     "Number of offload TX queues per port");
356 
357 #define NOFLDTXQ_VI 1
358 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
359 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
360     "Number of offload TX queues per VI");
361 #endif
362 
363 #if defined(TCP_OFFLOAD)
364 #define NOFLDRXQ 2
365 static int t4_nofldrxq = -NOFLDRXQ;
366 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
367     "Number of offload RX queues per port");
368 
369 #define NOFLDRXQ_VI 1
370 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
371 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
372     "Number of offload RX queues per VI");
373 
374 #define TMR_IDX_OFLD 1
375 static int t4_tmr_idx_ofld = TMR_IDX_OFLD;
376 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
377     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
378 
379 #define PKTC_IDX_OFLD (-1)
380 static int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
381 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
382     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
383 
384 /* 0 means chip/fw default, non-zero number is value in microseconds */
385 static u_long t4_toe_keepalive_idle = 0;
386 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
387     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
388 
389 /* 0 means chip/fw default, non-zero number is value in microseconds */
390 static u_long t4_toe_keepalive_interval = 0;
391 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
392     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
393 
394 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
395 static int t4_toe_keepalive_count = 0;
396 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
397     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
398 
399 /* 0 means chip/fw default, non-zero number is value in microseconds */
400 static u_long t4_toe_rexmt_min = 0;
401 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
403 
404 /* 0 means chip/fw default, non-zero number is value in microseconds */
405 static u_long t4_toe_rexmt_max = 0;
406 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
407     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
408 
409 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
410 static int t4_toe_rexmt_count = 0;
411 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
413 
414 /* -1 means chip/fw default, other values are raw backoff values to use */
415 static int t4_toe_rexmt_backoff[16] = {
416 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
417 };
418 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
419     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
420     "cxgbe(4) TOE retransmit backoff values");
421 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
422     &t4_toe_rexmt_backoff[0], 0, "");
423 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
424     &t4_toe_rexmt_backoff[1], 0, "");
425 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
426     &t4_toe_rexmt_backoff[2], 0, "");
427 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
428     &t4_toe_rexmt_backoff[3], 0, "");
429 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
430     &t4_toe_rexmt_backoff[4], 0, "");
431 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
432     &t4_toe_rexmt_backoff[5], 0, "");
433 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
434     &t4_toe_rexmt_backoff[6], 0, "");
435 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
436     &t4_toe_rexmt_backoff[7], 0, "");
437 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
438     &t4_toe_rexmt_backoff[8], 0, "");
439 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
440     &t4_toe_rexmt_backoff[9], 0, "");
441 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
442     &t4_toe_rexmt_backoff[10], 0, "");
443 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
444     &t4_toe_rexmt_backoff[11], 0, "");
445 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
446     &t4_toe_rexmt_backoff[12], 0, "");
447 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
448     &t4_toe_rexmt_backoff[13], 0, "");
449 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
450     &t4_toe_rexmt_backoff[14], 0, "");
451 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
452     &t4_toe_rexmt_backoff[15], 0, "");
453 
454 int t4_ddp_rcvbuf_len = 256 * 1024;
455 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
456     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
457 
458 unsigned int t4_ddp_rcvbuf_cache = 4;
459 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
460     &t4_ddp_rcvbuf_cache, 0,
461     "maximum number of free DDP RX buffers to cache per connection");
462 #endif
463 
464 #ifdef DEV_NETMAP
465 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
466 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
467 static int t4_native_netmap = NN_EXTRA_VI;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
469     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
470 
471 #define NNMTXQ 8
472 static int t4_nnmtxq = -NNMTXQ;
473 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
474     "Number of netmap TX queues");
475 
476 #define NNMRXQ 8
477 static int t4_nnmrxq = -NNMRXQ;
478 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
479     "Number of netmap RX queues");
480 
481 #define NNMTXQ_VI 2
482 static int t4_nnmtxq_vi = -NNMTXQ_VI;
483 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
484     "Number of netmap TX queues per VI");
485 
486 #define NNMRXQ_VI 2
487 static int t4_nnmrxq_vi = -NNMRXQ_VI;
488 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
489     "Number of netmap RX queues per VI");
490 #endif
491 
492 /*
493  * Holdoff parameters for ports.
494  */
495 #define TMR_IDX 1
496 int t4_tmr_idx = TMR_IDX;
497 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
498     0, "Holdoff timer index");
499 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
500 
501 #define PKTC_IDX (-1)
502 int t4_pktc_idx = PKTC_IDX;
503 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
504     0, "Holdoff packet counter index");
505 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
506 
507 /*
508  * Size (# of entries) of each tx and rx queue.
509  */
510 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
511 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
512     "Number of descriptors in each TX queue");
513 
514 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
515 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
516     "Number of descriptors in each RX queue");
517 
518 /*
519  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
520  */
521 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
522 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
523     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
524 
525 /*
526  * Configuration file.  All the _CF names here are special.
527  */
528 #define DEFAULT_CF	"default"
529 #define BUILTIN_CF	"built-in"
530 #define FLASH_CF	"flash"
531 #define UWIRE_CF	"uwire"
532 #define FPGA_CF		"fpga"
533 static char t4_cfg_file[32] = DEFAULT_CF;
534 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
535     sizeof(t4_cfg_file), "Firmware configuration file");
536 
537 /*
538  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
539  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
540  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
541  *            mark or when signalled to do so, 0 to never emit PAUSE.
542  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
543  *                 negotiated settings will override rx_pause/tx_pause.
544  *                 Otherwise rx_pause/tx_pause are applied forcibly.
545  */
546 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
547 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
548     &t4_pause_settings, 0,
549     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
550 
551 /*
552  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
553  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
554  *  0 to disable FEC.
555  */
556 static int t4_fec = -1;
557 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
558     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
559 
560 static const char *
561 t4_fec_bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2\6auto\7module";
562 
563 /*
564  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
565  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
566  * driver runs as if this is set to 0.
567  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
568  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
569  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
570  *    the firmware anyway (may result in l1cfg errors with old firmwares).
571  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
572  *    means set all FEC bits that are valid for the speed.
573  */
574 static int t4_force_fec = -1;
575 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
576     "Controls the use of FORCE_FEC bit in L1 configuration.");
577 
578 /*
579  * Link autonegotiation.
580  * -1 to run with the firmware default.
581  *  0 to disable.
582  *  1 to enable.
583  */
584 static int t4_autoneg = -1;
585 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
586     "Link autonegotiation");
587 
588 /*
589  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
590  * encouraged respectively).  '-n' is the same as 'n' except the firmware
591  * version used in the checks is read from the firmware bundled with the driver.
592  */
593 static int t4_fw_install = 1;
594 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
595     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
596 
597 /*
598  * ASIC features that will be used.  Disable the ones you don't want so that the
599  * chip resources aren't wasted on features that will not be used.
600  */
601 static int t4_nbmcaps_allowed = 0;
602 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
603     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
604 
605 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
606 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
607     &t4_linkcaps_allowed, 0, "Default link capabilities");
608 
609 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
610     FW_CAPS_CONFIG_SWITCH_EGRESS;
611 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
612     &t4_switchcaps_allowed, 0, "Default switch capabilities");
613 
614 static int t4_nvmecaps_allowed = 0;
615 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nvmecaps_allowed, CTLFLAG_RDTUN,
616     &t4_nvmecaps_allowed, 0, "Default NVMe capabilities");
617 
618 #ifdef RATELIMIT
619 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
620 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
621 #else
622 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
623 	FW_CAPS_CONFIG_NIC_HASHFILTER;
624 #endif
625 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
626     &t4_niccaps_allowed, 0, "Default NIC capabilities");
627 
628 static int t4_toecaps_allowed = -1;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
630     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
631 
632 static int t4_rdmacaps_allowed = -1;
633 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
634     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
635 
636 static int t4_cryptocaps_allowed = -1;
637 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
638     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
639 
640 static int t4_iscsicaps_allowed = -1;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
642     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
643 
644 static int t4_fcoecaps_allowed = 0;
645 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
646     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
647 
648 static int t5_write_combine = 0;
649 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
650     0, "Use WC instead of UC for BAR2");
651 
652 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
653 static int t4_doorbells_allowed = 0xf;
654 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
655 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
656 
657 static int t4_num_vis = 1;
658 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
659     "Number of VIs per port");
660 
661 /*
662  * PCIe Relaxed Ordering.
663  * -1: driver should figure out a good value.
664  * 0: disable RO.
665  * 1: enable RO.
666  * 2: leave RO alone.
667  */
668 static int pcie_relaxed_ordering = -1;
669 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
670     &pcie_relaxed_ordering, 0,
671     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
672 
673 static int t4_panic_on_fatal_err = 0;
674 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
675     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
676 
677 static int t4_reset_on_fatal_err = 0;
678 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
679     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
680 
681 static int t4_reset_method = 1;
682 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_method, CTLFLAG_RWTUN, &t4_reset_method,
683     0, "reset method: 0 = PL_RST, 1 = PCIe secondary bus reset, 2 = PCIe link bounce");
684 
685 static int t4_clock_gate_on_suspend = 0;
686 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
687     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
688 
689 static int t4_tx_vm_wr = 0;
690 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
691     "Use VM work requests to transmit packets.");
692 
693 /*
694  * Set to non-zero to enable the attack filter.  A packet that matches any of
695  * these conditions will get dropped on ingress:
696  * 1) IP && source address == destination address.
697  * 2) TCP/IP && source address is not a unicast address.
698  * 3) TCP/IP && destination address is not a unicast address.
699  * 4) IP && source address is loopback (127.x.y.z).
700  * 5) IP && destination address is loopback (127.x.y.z).
701  * 6) IPv6 && source address == destination address.
702  * 7) IPv6 && source address is not a unicast address.
703  * 8) IPv6 && source address is loopback (::1/128).
704  * 9) IPv6 && destination address is loopback (::1/128).
705  * 10) IPv6 && source address is unspecified (::/128).
706  * 11) IPv6 && destination address is unspecified (::/128).
707  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
708  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
709  */
710 static int t4_attack_filter = 0;
711 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
712     &t4_attack_filter, 0, "Drop suspicious traffic");
713 
714 static int t4_drop_ip_fragments = 0;
715 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
716     &t4_drop_ip_fragments, 0, "Drop IP fragments");
717 
718 static int t4_drop_pkts_with_l2_errors = 1;
719 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
720     &t4_drop_pkts_with_l2_errors, 0,
721     "Drop all frames with Layer 2 length or checksum errors");
722 
723 static int t4_drop_pkts_with_l3_errors = 0;
724 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
725     &t4_drop_pkts_with_l3_errors, 0,
726     "Drop all frames with IP version, length, or checksum errors");
727 
728 static int t4_drop_pkts_with_l4_errors = 0;
729 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
730     &t4_drop_pkts_with_l4_errors, 0,
731     "Drop all frames with Layer 4 length, checksum, or other errors");
732 
733 #ifdef TCP_OFFLOAD
734 /*
735  * TOE tunables.
736  */
737 static int t4_cop_managed_offloading = 0;
738 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
739     &t4_cop_managed_offloading, 0,
740     "COP (Connection Offload Policy) controls all TOE offload");
741 TUNABLE_INT("hw.cxgbe.cop_managed_offloading", &t4_cop_managed_offloading);
742 #endif
743 
744 #ifdef KERN_TLS
745 /*
746  * This enables KERN_TLS for all adapters if set.
747  */
748 static int t4_kern_tls = 0;
749 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
750     "Enable KERN_TLS mode for T6 adapters");
751 
752 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
753     "cxgbe(4) KERN_TLS parameters");
754 
755 static int t4_tls_inline_keys = 0;
756 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
757     &t4_tls_inline_keys, 0,
758     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
759     "in card memory.");
760 
761 static int t4_tls_combo_wrs = 0;
762 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
763     0, "Attempt to combine TCB field updates with TLS record work requests.");
764 
765 static int t4_tls_short_records = 1;
766 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, short_records, CTLFLAG_RDTUN,
767     &t4_tls_short_records, 0, "Use cipher-only mode for short records.");
768 
769 static int t4_tls_partial_ghash = 1;
770 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, partial_ghash, CTLFLAG_RDTUN,
771     &t4_tls_partial_ghash, 0, "Use partial GHASH for AES-GCM records.");
772 #endif
773 
774 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
775 static int vi_mac_funcs[] = {
776 	FW_VI_FUNC_ETH,
777 	FW_VI_FUNC_OFLD,
778 	FW_VI_FUNC_IWARP,
779 	FW_VI_FUNC_OPENISCSI,
780 	FW_VI_FUNC_OPENFCOE,
781 	FW_VI_FUNC_FOISCSI,
782 	FW_VI_FUNC_FOFCOE,
783 };
784 
785 struct intrs_and_queues {
786 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
787 	uint16_t num_vis;	/* number of VIs for each port */
788 	uint16_t nirq;		/* Total # of vectors */
789 	uint16_t ntxq;		/* # of NIC txq's for each port */
790 	uint16_t nrxq;		/* # of NIC rxq's for each port */
791 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
792 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
793 	uint16_t nnmtxq;	/* # of netmap txq's */
794 	uint16_t nnmrxq;	/* # of netmap rxq's */
795 
796 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
797 	uint16_t ntxq_vi;	/* # of NIC txq's */
798 	uint16_t nrxq_vi;	/* # of NIC rxq's */
799 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
800 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
801 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
802 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
803 };
804 
805 static void setup_memwin(struct adapter *);
806 static void position_memwin(struct adapter *, int, uint32_t);
807 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
808 static int fwmtype_to_hwmtype(int);
809 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
810     uint32_t *);
811 static int fixup_devlog_params(struct adapter *);
812 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
813 static int contact_firmware(struct adapter *);
814 static int partition_resources(struct adapter *);
815 static int get_params__pre_init(struct adapter *);
816 static int set_params__pre_init(struct adapter *);
817 static int get_params__post_init(struct adapter *);
818 static int set_params__post_init(struct adapter *);
819 static void t4_set_desc(struct adapter *);
820 static bool fixed_ifmedia(struct port_info *);
821 static void build_medialist(struct port_info *);
822 static void init_link_config(struct port_info *);
823 static int fixup_link_config(struct port_info *);
824 static int apply_link_config(struct port_info *);
825 static int cxgbe_init_synchronized(struct vi_info *);
826 static int cxgbe_uninit_synchronized(struct vi_info *);
827 static int adapter_full_init(struct adapter *);
828 static void adapter_full_uninit(struct adapter *);
829 static int vi_full_init(struct vi_info *);
830 static void vi_full_uninit(struct vi_info *);
831 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
832 static void quiesce_txq(struct sge_txq *);
833 static void quiesce_wrq(struct sge_wrq *);
834 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
835 static void quiesce_vi(struct vi_info *);
836 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
837     driver_intr_t *, void *, char *);
838 static int t4_free_irq(struct adapter *, struct irq *);
839 static void t4_init_atid_table(struct adapter *);
840 static void t4_free_atid_table(struct adapter *);
841 static void stop_atid_allocator(struct adapter *);
842 static void restart_atid_allocator(struct adapter *);
843 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
844 static void vi_refresh_stats(struct vi_info *);
845 static void cxgbe_refresh_stats(struct vi_info *);
846 static void cxgbe_tick(void *);
847 static void vi_tick(void *);
848 static void cxgbe_sysctls(struct port_info *);
849 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
850 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
851 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
852 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
853 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
854 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
855 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
856 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
857 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
858 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
859 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
860 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
861 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
862 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
863 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
864 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
865 static int sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS);
866 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
867 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
868 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
869 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
870 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
871 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
872 static int sysctl_cim_ibq(SYSCTL_HANDLER_ARGS);
873 static int sysctl_cim_obq(SYSCTL_HANDLER_ARGS);
874 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
875 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
876 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
877 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
878 static int sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS);
879 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
880 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
881 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
882 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
883 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
884 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
885 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
886 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
887 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
888 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
889 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
890 static int sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS);
891 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
892 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
893 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
894 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
895 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
896 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
897 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
898 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
899 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
900 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
901 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
902 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
903 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
904 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
905 #ifdef TCP_OFFLOAD
906 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
907 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
908 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
909 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
910 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
911 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
912 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
913 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
914 #endif
915 static int get_sge_context(struct adapter *, int, uint32_t, int, uint32_t *);
916 static int load_fw(struct adapter *, struct t4_data *);
917 static int load_cfg(struct adapter *, struct t4_data *);
918 static int load_boot(struct adapter *, struct t4_bootrom *);
919 static int load_bootcfg(struct adapter *, struct t4_data *);
920 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
921 static void free_offload_policy(struct t4_offload_policy *);
922 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
923 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
924 static int read_i2c(struct adapter *, struct t4_i2c_data *);
925 static int clear_stats(struct adapter *, u_int);
926 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
927 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
928 static inline int stop_adapter(struct adapter *);
929 static inline void set_adapter_hwstatus(struct adapter *, const bool);
930 static int stop_lld(struct adapter *);
931 static inline int restart_adapter(struct adapter *);
932 static int restart_lld(struct adapter *);
933 #ifdef TCP_OFFLOAD
934 static int deactivate_all_uld(struct adapter *);
935 static void stop_all_uld(struct adapter *);
936 static void restart_all_uld(struct adapter *);
937 #endif
938 #ifdef KERN_TLS
939 static int ktls_capability(struct adapter *, bool);
940 #endif
941 static int mod_event(module_t, int, void *);
942 static int notify_siblings(device_t, int);
943 static uint64_t vi_get_counter(if_t, ift_counter);
944 static uint64_t cxgbe_get_counter(if_t, ift_counter);
945 static void enable_vxlan_rx(struct adapter *);
946 static void reset_adapter_task(void *, int);
947 static void fatal_error_task(void *, int);
948 static void dump_devlog(struct adapter *);
949 static void dump_cim_regs(struct adapter *);
950 static void dump_cimla(struct adapter *);
951 
952 struct {
953 	uint16_t device;
954 	char *desc;
955 } t4_pciids[] = {
956 	{0xa000, "Chelsio Terminator 4 FPGA"},
957 	{0x4400, "Chelsio T440-dbg"},
958 	{0x4401, "Chelsio T420-CR"},
959 	{0x4402, "Chelsio T422-CR"},
960 	{0x4403, "Chelsio T440-CR"},
961 	{0x4404, "Chelsio T420-BCH"},
962 	{0x4405, "Chelsio T440-BCH"},
963 	{0x4406, "Chelsio T440-CH"},
964 	{0x4407, "Chelsio T420-SO"},
965 	{0x4408, "Chelsio T420-CX"},
966 	{0x4409, "Chelsio T420-BT"},
967 	{0x440a, "Chelsio T404-BT"},
968 	{0x440e, "Chelsio T440-LP-CR"},
969 }, t5_pciids[] = {
970 	{0xb000, "Chelsio Terminator 5 FPGA"},
971 	{0x5400, "Chelsio T580-dbg"},
972 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
973 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
974 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
975 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
976 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
977 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
978 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
979 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
980 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
981 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
982 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
983 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
984 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
985 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
986 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
987 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
988 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
989 
990 	/* Custom */
991 	{0x5483, "Custom T540-CR"},
992 	{0x5484, "Custom T540-BT"},
993 }, t6_pciids[] = {
994 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
995 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
996 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
997 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
998 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
999 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
1000 	{0x6405, "Chelsio T6225-SO-OCP3"},	/* 2 x 10/25G, nomem */
1001 	{0x6406, "Chelsio T6225-OCP3"},		/* 2 x 10/25G */
1002 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
1003 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
1004 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
1005 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
1006 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
1007 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
1008 	{0x6414, "Chelsio T62100-SO-OCP3"},	/* 2 x 40/50/100G, nomem */
1009 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
1010 
1011 	/* Custom */
1012 	{0x6480, "Custom T6225-CR"},
1013 	{0x6481, "Custom T62100-CR"},
1014 	{0x6482, "Custom T6225-CR"},
1015 	{0x6483, "Custom T62100-CR"},
1016 	{0x6484, "Custom T64100-CR"},
1017 	{0x6485, "Custom T6240-SO"},
1018 	{0x6486, "Custom T6225-SO-CR"},
1019 	{0x6487, "Custom T6225-CR"},
1020 }, t7_pciids[] = {
1021 	{0xd000, "Chelsio Terminator 7 FPGA"},	/* T7 PE12K FPGA */
1022 	{0x7400, "Chelsio T72200-DBG"},		/* 2 x 200G, debug */
1023 	{0x7401, "Chelsio T7250"},		/* 2 x 10/25/50G, 1 mem */
1024 	{0x7402, "Chelsio S7250"},		/* 2 x 10/25/50G, nomem */
1025 	{0x7403, "Chelsio T7450"},		/* 4 x 10/25/50G, 1 mem */
1026 	{0x7404, "Chelsio S7450"},		/* 4 x 10/25/50G, nomem */
1027 	{0x7405, "Chelsio T72200"},		/* 2 x 40/100/200G, 1 mem */
1028 	{0x7406, "Chelsio S72200"},		/* 2 x 40/100/200G, nomem */
1029 	{0x7407, "Chelsio T72200-FH"},		/* 2 x 40/100/200G, 2 mem */
1030 	{0x7408, "Chelsio S71400"},		/* 1 x 400G, nomem */
1031 	{0x7409, "Chelsio S7210-BT"},		/* 2 x 10GBASE-T, nomem */
1032 	{0x740a, "Chelsio T7450-RC"},		/* 4 x 10/25/50G, 1 mem, RC */
1033 	{0x740b, "Chelsio T72200-RC"},		/* 2 x 40/100/200G, 1 mem, RC */
1034 	{0x740c, "Chelsio T72200-FH-RC"},	/* 2 x 40/100/200G, 2 mem, RC */
1035 	{0x740d, "Chelsio S72200-OCP3"},	/* 2 x 40/100/200G OCP3 */
1036 	{0x740e, "Chelsio S7450-OCP3"},		/* 4 x 1/20/25/50G OCP3 */
1037 	{0x740f, "Chelsio S7410-BT-OCP3"},	/* 4 x 10GBASE-T OCP3 */
1038 	{0x7410, "Chelsio S7210-BT-A"},		/* 2 x 10GBASE-T */
1039 	{0x7411, "Chelsio T7_MAYRA_7"},		/* Motherboard */
1040 
1041 	/* Custom */
1042 	{0x7480, "Custom T7"},
1043 };
1044 
1045 #ifdef TCP_OFFLOAD
1046 /*
1047  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
1048  * be exactly the same for both rxq and ofld_rxq.
1049  */
1050 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
1051 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
1052 #endif
1053 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
1054 
1055 static int
1056 t4_probe(device_t dev)
1057 {
1058 	int i;
1059 	uint16_t v = pci_get_vendor(dev);
1060 	uint16_t d = pci_get_device(dev);
1061 	uint8_t f = pci_get_function(dev);
1062 
1063 	if (v != PCI_VENDOR_ID_CHELSIO)
1064 		return (ENXIO);
1065 
1066 	/* Attach only to PF0 of the FPGA */
1067 	if (d == 0xa000 && f != 0)
1068 		return (ENXIO);
1069 
1070 	for (i = 0; i < nitems(t4_pciids); i++) {
1071 		if (d == t4_pciids[i].device) {
1072 			device_set_desc(dev, t4_pciids[i].desc);
1073 			return (BUS_PROBE_DEFAULT);
1074 		}
1075 	}
1076 
1077 	return (ENXIO);
1078 }
1079 
1080 static int
1081 t5_probe(device_t dev)
1082 {
1083 	int i;
1084 	uint16_t v = pci_get_vendor(dev);
1085 	uint16_t d = pci_get_device(dev);
1086 	uint8_t f = pci_get_function(dev);
1087 
1088 	if (v != PCI_VENDOR_ID_CHELSIO)
1089 		return (ENXIO);
1090 
1091 	/* Attach only to PF0 of the FPGA */
1092 	if (d == 0xb000 && f != 0)
1093 		return (ENXIO);
1094 
1095 	for (i = 0; i < nitems(t5_pciids); i++) {
1096 		if (d == t5_pciids[i].device) {
1097 			device_set_desc(dev, t5_pciids[i].desc);
1098 			return (BUS_PROBE_DEFAULT);
1099 		}
1100 	}
1101 
1102 	return (ENXIO);
1103 }
1104 
1105 static int
1106 t6_probe(device_t dev)
1107 {
1108 	int i;
1109 	uint16_t v = pci_get_vendor(dev);
1110 	uint16_t d = pci_get_device(dev);
1111 
1112 	if (v != PCI_VENDOR_ID_CHELSIO)
1113 		return (ENXIO);
1114 
1115 	for (i = 0; i < nitems(t6_pciids); i++) {
1116 		if (d == t6_pciids[i].device) {
1117 			device_set_desc(dev, t6_pciids[i].desc);
1118 			return (BUS_PROBE_DEFAULT);
1119 		}
1120 	}
1121 
1122 	return (ENXIO);
1123 }
1124 
1125 static int
1126 ch_probe(device_t dev)
1127 {
1128 	int i;
1129 	uint16_t v = pci_get_vendor(dev);
1130 	uint16_t d = pci_get_device(dev);
1131 	uint8_t f = pci_get_function(dev);
1132 
1133 	if (v != PCI_VENDOR_ID_CHELSIO)
1134 		return (ENXIO);
1135 
1136 	/* Attach only to PF0 of the FPGA */
1137 	if (d == 0xd000 && f != 0)
1138 		return (ENXIO);
1139 
1140 	for (i = 0; i < nitems(t7_pciids); i++) {
1141 		if (d == t7_pciids[i].device) {
1142 			device_set_desc(dev, t7_pciids[i].desc);
1143 			return (BUS_PROBE_DEFAULT);
1144 		}
1145 	}
1146 
1147 	return (ENXIO);
1148 }
1149 
1150 static void
1151 t5_attribute_workaround(device_t dev)
1152 {
1153 	device_t root_port;
1154 	uint32_t v;
1155 
1156 	/*
1157 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1158 	 * Ordering attributes when replying to a TLP from a Root
1159 	 * Port.  As a workaround, find the parent Root Port and
1160 	 * disable No Snoop and Relaxed Ordering.  Note that this
1161 	 * affects all devices under this root port.
1162 	 */
1163 	root_port = pci_find_pcie_root_port(dev);
1164 	if (root_port == NULL) {
1165 		device_printf(dev, "Unable to find parent root port\n");
1166 		return;
1167 	}
1168 
1169 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1170 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1171 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1172 	    0)
1173 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1174 		    device_get_nameunit(root_port));
1175 }
1176 
1177 static const struct devnames devnames[] = {
1178 	{
1179 		.nexus_name = "t4nex",
1180 		.ifnet_name = "cxgbe",
1181 		.vi_ifnet_name = "vcxgbe",
1182 		.pf03_drv_name = "t4iov",
1183 		.vf_nexus_name = "t4vf",
1184 		.vf_ifnet_name = "cxgbev"
1185 	}, {
1186 		.nexus_name = "t5nex",
1187 		.ifnet_name = "cxl",
1188 		.vi_ifnet_name = "vcxl",
1189 		.pf03_drv_name = "t5iov",
1190 		.vf_nexus_name = "t5vf",
1191 		.vf_ifnet_name = "cxlv"
1192 	}, {
1193 		.nexus_name = "t6nex",
1194 		.ifnet_name = "cc",
1195 		.vi_ifnet_name = "vcc",
1196 		.pf03_drv_name = "t6iov",
1197 		.vf_nexus_name = "t6vf",
1198 		.vf_ifnet_name = "ccv"
1199 	}, {
1200 		.nexus_name = "chnex",
1201 		.ifnet_name = "che",
1202 		.vi_ifnet_name = "vche",
1203 		.pf03_drv_name = "chiov",
1204 		.vf_nexus_name = "chvf",
1205 		.vf_ifnet_name = "chev"
1206 	}
1207 };
1208 
1209 void
1210 t4_init_devnames(struct adapter *sc)
1211 {
1212 	int id;
1213 
1214 	id = chip_id(sc);
1215 	if (id < CHELSIO_T4) {
1216 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1217 		sc->names = NULL;
1218 	} else if (id - CHELSIO_T4 < nitems(devnames))
1219 		sc->names = &devnames[id - CHELSIO_T4];
1220 	else
1221 		sc->names = &devnames[nitems(devnames) - 1];
1222 }
1223 
1224 static int
1225 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1226 {
1227 	const char *parent, *name;
1228 	long value;
1229 	int line, unit;
1230 
1231 	line = 0;
1232 	parent = device_get_nameunit(sc->dev);
1233 	name = sc->names->ifnet_name;
1234 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1235 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1236 		    value == pi->port_id)
1237 			return (unit);
1238 	}
1239 	return (-1);
1240 }
1241 
1242 static void
1243 t4_calibration(void *arg)
1244 {
1245 	struct adapter *sc;
1246 	struct clock_sync *cur, *nex;
1247 	uint64_t hw;
1248 	sbintime_t sbt;
1249 	int next_up;
1250 
1251 	sc = (struct adapter *)arg;
1252 
1253 	KASSERT(hw_all_ok(sc), ("!hw_all_ok at t4_calibration"));
1254 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1255 	sbt = sbinuptime();
1256 
1257 	cur = &sc->cal_info[sc->cal_current];
1258 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1259 	nex = &sc->cal_info[next_up];
1260 	if (__predict_false(sc->cal_count == 0)) {
1261 		/* First time in, just get the values in */
1262 		cur->hw_cur = hw;
1263 		cur->sbt_cur = sbt;
1264 		sc->cal_count++;
1265 		goto done;
1266 	}
1267 
1268 	if (cur->hw_cur == hw) {
1269 		/* The clock is not advancing? */
1270 		sc->cal_count = 0;
1271 		atomic_store_rel_int(&cur->gen, 0);
1272 		goto done;
1273 	}
1274 
1275 	seqc_write_begin(&nex->gen);
1276 	nex->hw_prev = cur->hw_cur;
1277 	nex->sbt_prev = cur->sbt_cur;
1278 	nex->hw_cur = hw;
1279 	nex->sbt_cur = sbt;
1280 	seqc_write_end(&nex->gen);
1281 	sc->cal_current = next_up;
1282 done:
1283 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1284 	    sc, C_DIRECT_EXEC);
1285 }
1286 
1287 static void
1288 t4_calibration_start(struct adapter *sc)
1289 {
1290 	/*
1291 	 * Here if we have not done a calibration
1292 	 * then do so otherwise start the appropriate
1293 	 * timer.
1294 	 */
1295 	int i;
1296 
1297 	for (i = 0; i < CNT_CAL_INFO; i++) {
1298 		sc->cal_info[i].gen = 0;
1299 	}
1300 	sc->cal_current = 0;
1301 	sc->cal_count = 0;
1302 	sc->cal_gen = 0;
1303 	t4_calibration(sc);
1304 }
1305 
1306 static int
1307 t4_attach(device_t dev)
1308 {
1309 	struct adapter *sc;
1310 	int rc = 0, i, j, rqidx, tqidx, nports;
1311 	struct make_dev_args mda;
1312 	struct intrs_and_queues iaq;
1313 	struct sge *s;
1314 	uint32_t *buf;
1315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1316 	int ofld_tqidx;
1317 #endif
1318 #ifdef TCP_OFFLOAD
1319 	int ofld_rqidx;
1320 #endif
1321 #ifdef DEV_NETMAP
1322 	int nm_rqidx, nm_tqidx;
1323 #endif
1324 	int num_vis;
1325 
1326 	sc = device_get_softc(dev);
1327 	sc->dev = dev;
1328 	sysctl_ctx_init(&sc->ctx);
1329 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1330 
1331 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1332 		t5_attribute_workaround(dev);
1333 	pci_enable_busmaster(dev);
1334 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1335 		uint32_t v;
1336 
1337 		pci_set_max_read_req(dev, 4096);
1338 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1339 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1340 		if (pcie_relaxed_ordering == 0 &&
1341 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1342 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1343 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1344 		} else if (pcie_relaxed_ordering == 1 &&
1345 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1346 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1347 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1348 		}
1349 	}
1350 
1351 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1352 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1353 	sc->traceq = -1;
1354 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1355 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1356 	    device_get_nameunit(dev));
1357 
1358 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1359 	    device_get_nameunit(dev));
1360 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1361 	t4_add_adapter(sc);
1362 
1363 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1364 	TAILQ_INIT(&sc->sfl);
1365 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1366 
1367 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1368 
1369 	sc->policy = NULL;
1370 	rw_init(&sc->policy_lock, "connection offload policy");
1371 
1372 	callout_init(&sc->ktls_tick, 1);
1373 
1374 	callout_init(&sc->cal_callout, 1);
1375 
1376 	refcount_init(&sc->vxlan_refcount, 0);
1377 
1378 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1379 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1380 
1381 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1382 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1383 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1384 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1385 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1386 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1387 
1388 	rc = t4_map_bars_0_and_4(sc);
1389 	if (rc != 0)
1390 		goto done; /* error message displayed already */
1391 
1392 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1393 	memset(sc->port_map, 0xff, sizeof(sc->port_map));
1394 
1395 	/* Prepare the adapter for operation. */
1396 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1397 	rc = -t4_prep_adapter(sc, buf);
1398 	free(buf, M_CXGBE);
1399 	if (rc != 0) {
1400 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1401 		goto done;
1402 	}
1403 
1404 	/*
1405 	 * This is the real PF# to which we're attaching.  Works from within PCI
1406 	 * passthrough environments too, where pci_get_function() could return a
1407 	 * different PF# depending on the passthrough configuration.  We need to
1408 	 * use the real PF# in all our communication with the firmware.
1409 	 */
1410 	j = t4_read_reg(sc, A_PL_WHOAMI);
1411 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1412 	sc->mbox = sc->pf;
1413 
1414 	t4_init_devnames(sc);
1415 	if (sc->names == NULL) {
1416 		rc = ENOTSUP;
1417 		goto done; /* error message displayed already */
1418 	}
1419 
1420 	/*
1421 	 * Do this really early, with the memory windows set up even before the
1422 	 * character device.  The userland tool's register i/o and mem read
1423 	 * will work even in "recovery mode".
1424 	 */
1425 	setup_memwin(sc);
1426 	if (t4_init_devlog_ncores_params(sc, 0) == 0)
1427 		fixup_devlog_params(sc);
1428 	make_dev_args_init(&mda);
1429 	mda.mda_devsw = &t4_cdevsw;
1430 	mda.mda_uid = UID_ROOT;
1431 	mda.mda_gid = GID_WHEEL;
1432 	mda.mda_mode = 0600;
1433 	mda.mda_si_drv1 = sc;
1434 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1435 	if (rc != 0)
1436 		device_printf(dev, "failed to create nexus char device: %d.\n",
1437 		    rc);
1438 
1439 	/* Go no further if recovery mode has been requested. */
1440 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1441 		device_printf(dev, "recovery mode.\n");
1442 		goto done;
1443 	}
1444 
1445 #if defined(__i386__)
1446 	if ((cpu_feature & CPUID_CX8) == 0) {
1447 		device_printf(dev, "64 bit atomics not available.\n");
1448 		rc = ENOTSUP;
1449 		goto done;
1450 	}
1451 #endif
1452 
1453 	/* Contact the firmware and try to become the master driver. */
1454 	rc = contact_firmware(sc);
1455 	if (rc != 0)
1456 		goto done; /* error message displayed already */
1457 	MPASS(sc->flags & FW_OK);
1458 
1459 	rc = get_params__pre_init(sc);
1460 	if (rc != 0)
1461 		goto done; /* error message displayed already */
1462 
1463 	if (sc->flags & MASTER_PF) {
1464 		rc = partition_resources(sc);
1465 		if (rc != 0)
1466 			goto done; /* error message displayed already */
1467 	}
1468 
1469 	rc = get_params__post_init(sc);
1470 	if (rc != 0)
1471 		goto done; /* error message displayed already */
1472 
1473 	rc = set_params__post_init(sc);
1474 	if (rc != 0)
1475 		goto done; /* error message displayed already */
1476 
1477 	rc = t4_map_bar_2(sc);
1478 	if (rc != 0)
1479 		goto done; /* error message displayed already */
1480 
1481 	rc = t4_adj_doorbells(sc);
1482 	if (rc != 0)
1483 		goto done; /* error message displayed already */
1484 
1485 	rc = t4_create_dma_tag(sc);
1486 	if (rc != 0)
1487 		goto done; /* error message displayed already */
1488 
1489 	/*
1490 	 * First pass over all the ports - allocate VIs and initialize some
1491 	 * basic parameters like mac address, port type, etc.
1492 	 */
1493 	for_each_port(sc, i) {
1494 		struct port_info *pi;
1495 
1496 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1497 		sc->port[i] = pi;
1498 
1499 		/* These must be set before t4_port_init */
1500 		pi->adapter = sc;
1501 		pi->port_id = i;
1502 		/*
1503 		 * XXX: vi[0] is special so we can't delay this allocation until
1504 		 * pi->nvi's final value is known.
1505 		 */
1506 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1507 		    M_ZERO | M_WAITOK);
1508 
1509 		/*
1510 		 * Allocate the "main" VI and initialize parameters
1511 		 * like mac addr.
1512 		 */
1513 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1514 		if (rc != 0) {
1515 			device_printf(dev, "unable to initialize port %d: %d\n",
1516 			    i, rc);
1517 			free(pi->vi, M_CXGBE);
1518 			free(pi, M_CXGBE);
1519 			sc->port[i] = NULL;
1520 			goto done;
1521 		}
1522 
1523 		if (is_bt(pi->port_type))
1524 			setbit(&sc->bt_map, pi->hw_port);
1525 		else
1526 			MPASS(!isset(&sc->bt_map, pi->hw_port));
1527 
1528 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1529 		    device_get_nameunit(dev), i);
1530 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1531 		for (j = 0; j < sc->params.tp.lb_nchan; j++)
1532 			sc->chan_map[pi->tx_chan + j] = i;
1533 		sc->port_map[pi->hw_port] = i;
1534 
1535 		/*
1536 		 * The MPS counter for FCS errors doesn't work correctly on the
1537 		 * T6 so we use the MAC counter here.  Which MAC is in use
1538 		 * depends on the link settings which will be known when the
1539 		 * link comes up.
1540 		 */
1541 		if (is_t6(sc))
1542 			pi->fcs_reg = -1;
1543 		else
1544 			pi->fcs_reg = A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L;
1545 		pi->fcs_base = 0;
1546 
1547 		/* All VIs on this port share this media. */
1548 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1549 		    cxgbe_media_status);
1550 
1551 		PORT_LOCK(pi);
1552 		init_link_config(pi);
1553 		fixup_link_config(pi);
1554 		build_medialist(pi);
1555 		if (fixed_ifmedia(pi))
1556 			pi->flags |= FIXED_IFMEDIA;
1557 		PORT_UNLOCK(pi);
1558 
1559 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1560 		    t4_ifnet_unit(sc, pi));
1561 		if (pi->dev == NULL) {
1562 			device_printf(dev,
1563 			    "failed to add device for port %d.\n", i);
1564 			rc = ENXIO;
1565 			goto done;
1566 		}
1567 		pi->vi[0].dev = pi->dev;
1568 		device_set_softc(pi->dev, pi);
1569 	}
1570 
1571 	/*
1572 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1573 	 */
1574 	nports = sc->params.nports;
1575 	rc = cfg_itype_and_nqueues(sc, &iaq);
1576 	if (rc != 0)
1577 		goto done; /* error message displayed already */
1578 
1579 	num_vis = iaq.num_vis;
1580 	sc->intr_type = iaq.intr_type;
1581 	sc->intr_count = iaq.nirq;
1582 
1583 	s = &sc->sge;
1584 	s->nctrlq = max(sc->params.nports, sc->params.ncores);
1585 	s->nrxq = nports * iaq.nrxq;
1586 	s->ntxq = nports * iaq.ntxq;
1587 	if (num_vis > 1) {
1588 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1589 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1590 	}
1591 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1592 	s->neq += nports;		/* ctrl queues: 1 per port */
1593 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1594 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1595 	if (is_offload(sc) || is_ethoffload(sc)) {
1596 		s->nofldtxq = nports * iaq.nofldtxq;
1597 		if (num_vis > 1)
1598 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1599 		s->neq += s->nofldtxq;
1600 
1601 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1602 		    M_CXGBE, M_ZERO | M_WAITOK);
1603 	}
1604 #endif
1605 #ifdef TCP_OFFLOAD
1606 	if (is_offload(sc)) {
1607 		s->nofldrxq = nports * iaq.nofldrxq;
1608 		if (num_vis > 1)
1609 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1610 		s->neq += s->nofldrxq;	/* free list */
1611 		s->niq += s->nofldrxq;
1612 
1613 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1614 		    M_CXGBE, M_ZERO | M_WAITOK);
1615 	}
1616 #endif
1617 #ifdef DEV_NETMAP
1618 	s->nnmrxq = 0;
1619 	s->nnmtxq = 0;
1620 	if (t4_native_netmap & NN_MAIN_VI) {
1621 		s->nnmrxq += nports * iaq.nnmrxq;
1622 		s->nnmtxq += nports * iaq.nnmtxq;
1623 	}
1624 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1625 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1626 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1627 	}
1628 	s->neq += s->nnmtxq + s->nnmrxq;
1629 	s->niq += s->nnmrxq;
1630 
1631 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1632 	    M_CXGBE, M_ZERO | M_WAITOK);
1633 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1634 	    M_CXGBE, M_ZERO | M_WAITOK);
1635 #endif
1636 	MPASS(s->niq <= s->iqmap_sz);
1637 	MPASS(s->neq <= s->eqmap_sz);
1638 
1639 	s->ctrlq = malloc(s->nctrlq * sizeof(struct sge_wrq), M_CXGBE,
1640 	    M_ZERO | M_WAITOK);
1641 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1642 	    M_ZERO | M_WAITOK);
1643 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1644 	    M_ZERO | M_WAITOK);
1645 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1646 	    M_ZERO | M_WAITOK);
1647 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1648 	    M_ZERO | M_WAITOK);
1649 
1650 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1651 	    M_ZERO | M_WAITOK);
1652 
1653 	t4_init_l2t(sc, M_WAITOK);
1654 	t4_init_smt(sc, M_WAITOK);
1655 	t4_init_tx_sched(sc);
1656 	t4_init_atid_table(sc);
1657 #ifdef RATELIMIT
1658 	t4_init_etid_table(sc);
1659 #endif
1660 #ifdef INET6
1661 	t4_init_clip_table(sc);
1662 #endif
1663 	if (sc->vres.key.size != 0)
1664 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1665 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1666 	t4_init_tpt(sc);
1667 
1668 	/*
1669 	 * Second pass over the ports.  This time we know the number of rx and
1670 	 * tx queues that each port should get.
1671 	 */
1672 	rqidx = tqidx = 0;
1673 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1674 	ofld_tqidx = 0;
1675 #endif
1676 #ifdef TCP_OFFLOAD
1677 	ofld_rqidx = 0;
1678 #endif
1679 #ifdef DEV_NETMAP
1680 	nm_rqidx = nm_tqidx = 0;
1681 #endif
1682 	for_each_port(sc, i) {
1683 		struct port_info *pi = sc->port[i];
1684 		struct vi_info *vi;
1685 
1686 		if (pi == NULL)
1687 			continue;
1688 
1689 		pi->nvi = num_vis;
1690 		for_each_vi(pi, j, vi) {
1691 			vi->pi = pi;
1692 			vi->adapter = sc;
1693 			vi->first_intr = -1;
1694 			vi->qsize_rxq = t4_qsize_rxq;
1695 			vi->qsize_txq = t4_qsize_txq;
1696 
1697 			vi->first_rxq = rqidx;
1698 			vi->first_txq = tqidx;
1699 			vi->tmr_idx = t4_tmr_idx;
1700 			vi->pktc_idx = t4_pktc_idx;
1701 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1702 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1703 
1704 			rqidx += vi->nrxq;
1705 			tqidx += vi->ntxq;
1706 
1707 			if (j == 0 && vi->ntxq > 1)
1708 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1709 			else
1710 				vi->rsrv_noflowq = 0;
1711 
1712 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1713 			vi->first_ofld_txq = ofld_tqidx;
1714 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1715 			ofld_tqidx += vi->nofldtxq;
1716 #endif
1717 #ifdef TCP_OFFLOAD
1718 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1719 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1720 			vi->first_ofld_rxq = ofld_rqidx;
1721 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1722 
1723 			ofld_rqidx += vi->nofldrxq;
1724 #endif
1725 #ifdef DEV_NETMAP
1726 			vi->first_nm_rxq = nm_rqidx;
1727 			vi->first_nm_txq = nm_tqidx;
1728 			if (j == 0) {
1729 				vi->nnmrxq = iaq.nnmrxq;
1730 				vi->nnmtxq = iaq.nnmtxq;
1731 			} else {
1732 				vi->nnmrxq = iaq.nnmrxq_vi;
1733 				vi->nnmtxq = iaq.nnmtxq_vi;
1734 			}
1735 			nm_rqidx += vi->nnmrxq;
1736 			nm_tqidx += vi->nnmtxq;
1737 #endif
1738 		}
1739 	}
1740 
1741 	rc = t4_setup_intr_handlers(sc);
1742 	if (rc != 0) {
1743 		device_printf(dev,
1744 		    "failed to setup interrupt handlers: %d\n", rc);
1745 		goto done;
1746 	}
1747 
1748 	bus_identify_children(dev);
1749 
1750 	/*
1751 	 * Ensure thread-safe mailbox access (in debug builds).
1752 	 *
1753 	 * So far this was the only thread accessing the mailbox but various
1754 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1755 	 * will access the mailbox from different threads.
1756 	 */
1757 	sc->flags |= CHK_MBOX_ACCESS;
1758 
1759 	bus_attach_children(dev);
1760 	t4_calibration_start(sc);
1761 
1762 	device_printf(dev,
1763 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1764 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1765 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1766 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1767 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1768 
1769 	t4_set_desc(sc);
1770 
1771 	notify_siblings(dev, 0);
1772 
1773 done:
1774 	if (rc != 0 && sc->cdev) {
1775 		/* cdev was created and so cxgbetool works; recover that way. */
1776 		device_printf(dev,
1777 		    "error during attach, adapter is now in recovery mode.\n");
1778 		rc = 0;
1779 	}
1780 
1781 	if (rc != 0)
1782 		t4_detach_common(dev);
1783 	else
1784 		t4_sysctls(sc);
1785 
1786 	return (rc);
1787 }
1788 
1789 static int
1790 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1791 {
1792 	struct adapter *sc;
1793 	struct port_info *pi;
1794 	int i;
1795 
1796 	sc = device_get_softc(bus);
1797 	for_each_port(sc, i) {
1798 		pi = sc->port[i];
1799 		if (pi != NULL && pi->dev == dev) {
1800 			sbuf_printf(sb, "port=%d", pi->port_id);
1801 			break;
1802 		}
1803 	}
1804 	return (0);
1805 }
1806 
1807 static int
1808 t4_ready(device_t dev)
1809 {
1810 	struct adapter *sc;
1811 
1812 	sc = device_get_softc(dev);
1813 	if (sc->flags & FW_OK)
1814 		return (0);
1815 	return (ENXIO);
1816 }
1817 
1818 static int
1819 t4_read_port_device(device_t dev, int port, device_t *child)
1820 {
1821 	struct adapter *sc;
1822 	struct port_info *pi;
1823 
1824 	sc = device_get_softc(dev);
1825 	if (port < 0 || port >= MAX_NPORTS)
1826 		return (EINVAL);
1827 	pi = sc->port[port];
1828 	if (pi == NULL || pi->dev == NULL)
1829 		return (ENXIO);
1830 	*child = pi->dev;
1831 	return (0);
1832 }
1833 
1834 static int
1835 notify_siblings(device_t dev, int detaching)
1836 {
1837 	device_t sibling;
1838 	int error, i;
1839 
1840 	error = 0;
1841 	for (i = 0; i < PCI_FUNCMAX; i++) {
1842 		if (i == pci_get_function(dev))
1843 			continue;
1844 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1845 		    pci_get_slot(dev), i);
1846 		if (sibling == NULL || !device_is_attached(sibling))
1847 			continue;
1848 		if (detaching)
1849 			error = T4_DETACH_CHILD(sibling);
1850 		else
1851 			(void)T4_ATTACH_CHILD(sibling);
1852 		if (error)
1853 			break;
1854 	}
1855 	return (error);
1856 }
1857 
1858 /*
1859  * Idempotent
1860  */
1861 static int
1862 t4_detach(device_t dev)
1863 {
1864 	int rc;
1865 
1866 	rc = notify_siblings(dev, 1);
1867 	if (rc) {
1868 		device_printf(dev,
1869 		    "failed to detach sibling devices: %d\n", rc);
1870 		return (rc);
1871 	}
1872 
1873 	return (t4_detach_common(dev));
1874 }
1875 
1876 int
1877 t4_detach_common(device_t dev)
1878 {
1879 	struct adapter *sc;
1880 	struct port_info *pi;
1881 	int i, rc;
1882 
1883 	sc = device_get_softc(dev);
1884 
1885 #ifdef TCP_OFFLOAD
1886 	rc = deactivate_all_uld(sc);
1887 	if (rc) {
1888 		device_printf(dev,
1889 		    "failed to detach upper layer drivers: %d\n", rc);
1890 		return (rc);
1891 	}
1892 #endif
1893 
1894 	if (sc->cdev) {
1895 		destroy_dev(sc->cdev);
1896 		sc->cdev = NULL;
1897 	}
1898 
1899 	sx_xlock(&t4_list_lock);
1900 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1901 	sx_xunlock(&t4_list_lock);
1902 
1903 	sc->flags &= ~CHK_MBOX_ACCESS;
1904 	if (sc->flags & FULL_INIT_DONE) {
1905 		if (!(sc->flags & IS_VF))
1906 			t4_intr_disable(sc);
1907 	}
1908 
1909 	if (device_is_attached(dev)) {
1910 		rc = bus_detach_children(dev);
1911 		if (rc) {
1912 			device_printf(dev,
1913 			    "failed to detach child devices: %d\n", rc);
1914 			return (rc);
1915 		}
1916 	}
1917 
1918 	for (i = 0; i < sc->intr_count; i++)
1919 		t4_free_irq(sc, &sc->irq[i]);
1920 
1921 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1922 		t4_free_tx_sched(sc);
1923 
1924 	for (i = 0; i < MAX_NPORTS; i++) {
1925 		pi = sc->port[i];
1926 		if (pi) {
1927 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1928 
1929 			mtx_destroy(&pi->pi_lock);
1930 			free(pi->vi, M_CXGBE);
1931 			free(pi, M_CXGBE);
1932 		}
1933 	}
1934 	callout_stop(&sc->cal_callout);
1935 	callout_drain(&sc->cal_callout);
1936 	device_delete_children(dev);
1937 	sysctl_ctx_free(&sc->ctx);
1938 	adapter_full_uninit(sc);
1939 
1940 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1941 		t4_fw_bye(sc, sc->mbox);
1942 
1943 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1944 		pci_release_msi(dev);
1945 
1946 	if (sc->regs_res)
1947 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1948 		    sc->regs_res);
1949 
1950 	if (sc->udbs_res)
1951 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1952 		    sc->udbs_res);
1953 
1954 	if (sc->msix_res)
1955 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1956 		    sc->msix_res);
1957 
1958 	if (sc->l2t)
1959 		t4_free_l2t(sc);
1960 	if (sc->smt)
1961 		t4_free_smt(sc->smt);
1962 	t4_free_atid_table(sc);
1963 #ifdef RATELIMIT
1964 	t4_free_etid_table(sc);
1965 #endif
1966 	if (sc->key_map)
1967 		vmem_destroy(sc->key_map);
1968 	t4_free_tpt(sc);
1969 #ifdef INET6
1970 	t4_destroy_clip_table(sc);
1971 #endif
1972 
1973 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1974 	free(sc->sge.ofld_txq, M_CXGBE);
1975 #endif
1976 #ifdef TCP_OFFLOAD
1977 	free(sc->sge.ofld_rxq, M_CXGBE);
1978 #endif
1979 #ifdef DEV_NETMAP
1980 	free(sc->sge.nm_rxq, M_CXGBE);
1981 	free(sc->sge.nm_txq, M_CXGBE);
1982 #endif
1983 	free(sc->irq, M_CXGBE);
1984 	free(sc->sge.rxq, M_CXGBE);
1985 	free(sc->sge.txq, M_CXGBE);
1986 	free(sc->sge.ctrlq, M_CXGBE);
1987 	free(sc->sge.iqmap, M_CXGBE);
1988 	free(sc->sge.eqmap, M_CXGBE);
1989 	free(sc->tids.ftid_tab, M_CXGBE);
1990 	free(sc->tids.hpftid_tab, M_CXGBE);
1991 	free_hftid_hash(&sc->tids);
1992 	free(sc->tids.tid_tab, M_CXGBE);
1993 	t4_destroy_dma_tag(sc);
1994 
1995 	callout_drain(&sc->ktls_tick);
1996 	callout_drain(&sc->sfl_callout);
1997 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1998 		mtx_destroy(&sc->tids.ftid_lock);
1999 		cv_destroy(&sc->tids.ftid_cv);
2000 	}
2001 	if (mtx_initialized(&sc->tids.atid_lock))
2002 		mtx_destroy(&sc->tids.atid_lock);
2003 	if (mtx_initialized(&sc->ifp_lock))
2004 		mtx_destroy(&sc->ifp_lock);
2005 
2006 	if (rw_initialized(&sc->policy_lock)) {
2007 		rw_destroy(&sc->policy_lock);
2008 #ifdef TCP_OFFLOAD
2009 		if (sc->policy != NULL)
2010 			free_offload_policy(sc->policy);
2011 #endif
2012 	}
2013 
2014 	for (i = 0; i < NUM_MEMWIN; i++) {
2015 		struct memwin *mw = &sc->memwin[i];
2016 
2017 		if (rw_initialized(&mw->mw_lock))
2018 			rw_destroy(&mw->mw_lock);
2019 	}
2020 
2021 	mtx_destroy(&sc->sfl_lock);
2022 	mtx_destroy(&sc->reg_lock);
2023 	mtx_destroy(&sc->sc_lock);
2024 
2025 	bzero(sc, sizeof(*sc));
2026 
2027 	return (0);
2028 }
2029 
2030 static inline int
2031 stop_adapter(struct adapter *sc)
2032 {
2033 	struct port_info *pi;
2034 	int i;
2035 
2036 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2037 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2038 			 __func__, curthread, sc->flags, sc->error_flags);
2039 		return (EALREADY);
2040 	}
2041 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2042 		 sc->flags, sc->error_flags);
2043 	t4_shutdown_adapter(sc);
2044 	for_each_port(sc, i) {
2045 		pi = sc->port[i];
2046 		if (pi == NULL)
2047 			continue;
2048 		PORT_LOCK(pi);
2049 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
2050 			/*
2051 			 * t4_shutdown_adapter has already shut down all the
2052 			 * PHYs but it also disables interrupts and DMA so there
2053 			 * won't be a link interrupt.  Update the state manually
2054 			 * if the link was up previously and inform the kernel.
2055 			 */
2056 			pi->link_cfg.link_ok = false;
2057 			t4_os_link_changed(pi);
2058 		}
2059 		PORT_UNLOCK(pi);
2060 	}
2061 
2062 	return (0);
2063 }
2064 
2065 static inline int
2066 restart_adapter(struct adapter *sc)
2067 {
2068 	uint32_t val;
2069 
2070 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2071 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2072 			 __func__, curthread, sc->flags, sc->error_flags);
2073 		return (EALREADY);
2074 	}
2075 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2076 		 sc->flags, sc->error_flags);
2077 
2078 	MPASS(hw_off_limits(sc));
2079 	MPASS((sc->flags & FW_OK) == 0);
2080 	MPASS((sc->flags & MASTER_PF) == 0);
2081 	MPASS(sc->reset_thread == NULL);
2082 
2083 	/*
2084 	 * The adapter is supposed to be back on PCIE with its config space and
2085 	 * BARs restored to their state before reset.  Register access via
2086 	 * t4_read_reg BAR0 should just work.
2087 	 */
2088 	sc->reset_thread = curthread;
2089 	val = t4_read_reg(sc, A_PL_WHOAMI);
2090 	if (val == 0xffffffff || val == 0xeeeeeeee) {
2091 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
2092 		sc->reset_thread = NULL;
2093 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
2094 		return (ENXIO);
2095 	}
2096 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
2097 	atomic_add_int(&sc->incarnation, 1);
2098 	atomic_add_int(&sc->num_resets, 1);
2099 
2100 	return (0);
2101 }
2102 
2103 static inline void
2104 set_adapter_hwstatus(struct adapter *sc, const bool usable)
2105 {
2106 	if (usable) {
2107 		/* Must be marked reusable by the designated thread. */
2108 		ASSERT_SYNCHRONIZED_OP(sc);
2109 		MPASS(sc->reset_thread == curthread);
2110 		mtx_lock(&sc->reg_lock);
2111 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2112 		mtx_unlock(&sc->reg_lock);
2113 	} else {
2114 		/* Mark the adapter totally off limits. */
2115 		begin_synchronized_op(sc, NULL, SLEEP_OK, "t4hwsts");
2116 		mtx_lock(&sc->reg_lock);
2117 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2118 		mtx_unlock(&sc->reg_lock);
2119 		sc->flags &= ~(FW_OK | MASTER_PF);
2120 		sc->reset_thread = NULL;
2121 		end_synchronized_op(sc, 0);
2122 	}
2123 }
2124 
2125 static int
2126 stop_lld(struct adapter *sc)
2127 {
2128 	struct port_info *pi;
2129 	struct vi_info *vi;
2130 	if_t ifp;
2131 	struct sge_rxq *rxq;
2132 	struct sge_txq *txq;
2133 	struct sge_wrq *wrq;
2134 #ifdef TCP_OFFLOAD
2135 	struct sge_ofld_rxq *ofld_rxq;
2136 #endif
2137 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2138 	struct sge_ofld_txq *ofld_txq;
2139 #endif
2140 	int rc, i, j, k;
2141 
2142 	/*
2143 	 * XXX: Can there be a synch_op in progress that will hang because
2144 	 * hardware has been stopped?  We'll hang too and the solution will be
2145 	 * to use a version of begin_synch_op that wakes up existing synch_op
2146 	 * with errors.  Maybe stop_adapter should do this wakeup?
2147 	 *
2148 	 * I don't think any synch_op could get stranded waiting for DMA or
2149 	 * interrupt so I think we're okay here.  Remove this comment block
2150 	 * after testing.
2151 	 */
2152 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2153 	if (rc != 0)
2154 		return (ENXIO);
2155 
2156 	/* Quiesce all activity. */
2157 	for_each_port(sc, i) {
2158 		pi = sc->port[i];
2159 		if (pi == NULL)
2160 			continue;
2161 		pi->vxlan_tcam_entry = false;
2162 		for_each_vi(pi, j, vi) {
2163 			vi->xact_addr_filt = -1;
2164 			mtx_lock(&vi->tick_mtx);
2165 			vi->flags |= VI_SKIP_STATS;
2166 			mtx_unlock(&vi->tick_mtx);
2167 			if (!(vi->flags & VI_INIT_DONE))
2168 				continue;
2169 
2170 			ifp = vi->ifp;
2171 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2172 				mtx_lock(&vi->tick_mtx);
2173 				callout_stop(&vi->tick);
2174 				mtx_unlock(&vi->tick_mtx);
2175 				callout_drain(&vi->tick);
2176 			}
2177 
2178 			/*
2179 			 * Note that the HW is not available.
2180 			 */
2181 			for_each_txq(vi, k, txq) {
2182 				TXQ_LOCK(txq);
2183 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2184 				TXQ_UNLOCK(txq);
2185 			}
2186 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2187 			for_each_ofld_txq(vi, k, ofld_txq) {
2188 				TXQ_LOCK(&ofld_txq->wrq);
2189 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2190 				TXQ_UNLOCK(&ofld_txq->wrq);
2191 			}
2192 #endif
2193 			for_each_rxq(vi, k, rxq) {
2194 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2195 			}
2196 #if defined(TCP_OFFLOAD)
2197 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2198 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2199 			}
2200 #endif
2201 
2202 			quiesce_vi(vi);
2203 		}
2204 
2205 		if (sc->flags & FULL_INIT_DONE) {
2206 			/* Control queue */
2207 			wrq = &sc->sge.ctrlq[i];
2208 			TXQ_LOCK(wrq);
2209 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2210 			TXQ_UNLOCK(wrq);
2211 			quiesce_wrq(wrq);
2212 		}
2213 
2214 		if (pi->flags & HAS_TRACEQ) {
2215 			pi->flags &= ~HAS_TRACEQ;
2216 			sc->traceq = -1;
2217 			sc->tracer_valid = 0;
2218 			sc->tracer_enabled = 0;
2219 		}
2220 	}
2221 	if (sc->flags & FULL_INIT_DONE) {
2222 		/* Firmware event queue */
2223 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2224 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2225 	}
2226 
2227 	/* Stop calibration */
2228 	callout_stop(&sc->cal_callout);
2229 	callout_drain(&sc->cal_callout);
2230 
2231 	if (t4_clock_gate_on_suspend) {
2232 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2233 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2234 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2235 	}
2236 
2237 	end_synchronized_op(sc, 0);
2238 
2239 	stop_atid_allocator(sc);
2240 	t4_stop_l2t(sc);
2241 
2242 	return (rc);
2243 }
2244 
2245 int
2246 suspend_adapter(struct adapter *sc)
2247 {
2248 	stop_adapter(sc);
2249 	stop_lld(sc);
2250 #ifdef TCP_OFFLOAD
2251 	stop_all_uld(sc);
2252 #endif
2253 	set_adapter_hwstatus(sc, false);
2254 
2255 	return (0);
2256 }
2257 
2258 static int
2259 t4_suspend(device_t dev)
2260 {
2261 	struct adapter *sc = device_get_softc(dev);
2262 	int rc;
2263 
2264 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2265 	rc = suspend_adapter(sc);
2266 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2267 
2268 	return (rc);
2269 }
2270 
2271 struct adapter_pre_reset_state {
2272 	u_int flags;
2273 	uint16_t nbmcaps;
2274 	uint16_t linkcaps;
2275 	uint16_t switchcaps;
2276 	uint16_t nvmecaps;
2277 	uint16_t niccaps;
2278 	uint16_t toecaps;
2279 	uint16_t rdmacaps;
2280 	uint16_t cryptocaps;
2281 	uint16_t iscsicaps;
2282 	uint16_t fcoecaps;
2283 
2284 	u_int cfcsum;
2285 	char cfg_file[32];
2286 
2287 	struct adapter_params params;
2288 	struct t4_virt_res vres;
2289 	struct tid_info tids;
2290 	struct sge sge;
2291 
2292 	int rawf_base;
2293 	int nrawf;
2294 
2295 };
2296 
2297 static void
2298 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2299 {
2300 
2301 	ASSERT_SYNCHRONIZED_OP(sc);
2302 
2303 	o->flags = sc->flags;
2304 
2305 	o->nbmcaps =  sc->nbmcaps;
2306 	o->linkcaps = sc->linkcaps;
2307 	o->switchcaps = sc->switchcaps;
2308 	o->nvmecaps = sc->nvmecaps;
2309 	o->niccaps = sc->niccaps;
2310 	o->toecaps = sc->toecaps;
2311 	o->rdmacaps = sc->rdmacaps;
2312 	o->cryptocaps = sc->cryptocaps;
2313 	o->iscsicaps = sc->iscsicaps;
2314 	o->fcoecaps = sc->fcoecaps;
2315 
2316 	o->cfcsum = sc->cfcsum;
2317 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2318 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2319 
2320 	o->params = sc->params;
2321 	o->vres = sc->vres;
2322 	o->tids = sc->tids;
2323 	o->sge = sc->sge;
2324 
2325 	o->rawf_base = sc->rawf_base;
2326 	o->nrawf = sc->nrawf;
2327 }
2328 
2329 static int
2330 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2331 {
2332 	int rc = 0;
2333 
2334 	ASSERT_SYNCHRONIZED_OP(sc);
2335 
2336 	/* Capabilities */
2337 #define COMPARE_CAPS(c) do { \
2338 	if (o->c##caps != sc->c##caps) { \
2339 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2340 		    sc->c##caps); \
2341 		rc = EINVAL; \
2342 	} \
2343 } while (0)
2344 	COMPARE_CAPS(nbm);
2345 	COMPARE_CAPS(link);
2346 	COMPARE_CAPS(switch);
2347 	COMPARE_CAPS(nvme);
2348 	COMPARE_CAPS(nic);
2349 	COMPARE_CAPS(toe);
2350 	COMPARE_CAPS(rdma);
2351 	COMPARE_CAPS(crypto);
2352 	COMPARE_CAPS(iscsi);
2353 	COMPARE_CAPS(fcoe);
2354 #undef COMPARE_CAPS
2355 
2356 	/* Firmware config file */
2357 	if (o->cfcsum != sc->cfcsum) {
2358 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2359 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2360 		rc = EINVAL;
2361 	}
2362 
2363 #define COMPARE_PARAM(p, name) do { \
2364 	if (o->p != sc->p) { \
2365 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2366 		rc = EINVAL; \
2367 	} \
2368 } while (0)
2369 	COMPARE_PARAM(sge.iq_start, iq_start);
2370 	COMPARE_PARAM(sge.eq_start, eq_start);
2371 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2372 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2373 	COMPARE_PARAM(tids.nftids, nftids);
2374 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2375 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2376 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2377 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2378 	COMPARE_PARAM(tids.tid_base, tid_base);
2379 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2380 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2381 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2382 	COMPARE_PARAM(rawf_base, rawf_base);
2383 	COMPARE_PARAM(nrawf, nrawf);
2384 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2385 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2386 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2387 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2388 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2389 	COMPARE_PARAM(tids.ntids, ntids);
2390 	COMPARE_PARAM(tids.etid_base, etid_base);
2391 	COMPARE_PARAM(tids.etid_end, etid_end);
2392 	COMPARE_PARAM(tids.netids, netids);
2393 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2394 	COMPARE_PARAM(params.ethoffload, ethoffload);
2395 	COMPARE_PARAM(tids.natids, natids);
2396 	COMPARE_PARAM(tids.stid_base, stid_base);
2397 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2398 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2399 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2400 	COMPARE_PARAM(vres.stag.start, stag_start);
2401 	COMPARE_PARAM(vres.stag.size, stag_size);
2402 	COMPARE_PARAM(vres.rq.start, rq_start);
2403 	COMPARE_PARAM(vres.rq.size, rq_size);
2404 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2405 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2406 	COMPARE_PARAM(vres.qp.start, qp_start);
2407 	COMPARE_PARAM(vres.qp.size, qp_size);
2408 	COMPARE_PARAM(vres.cq.start, cq_start);
2409 	COMPARE_PARAM(vres.cq.size, cq_size);
2410 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2411 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2412 	COMPARE_PARAM(vres.srq.start, srq_start);
2413 	COMPARE_PARAM(vres.srq.size, srq_size);
2414 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2415 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2416 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2417 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2418 	COMPARE_PARAM(vres.key.start, key_start);
2419 	COMPARE_PARAM(vres.key.size, key_size);
2420 #undef COMPARE_PARAM
2421 
2422 	return (rc);
2423 }
2424 
2425 static int
2426 restart_lld(struct adapter *sc)
2427 {
2428 	struct adapter_pre_reset_state *old_state = NULL;
2429 	struct port_info *pi;
2430 	struct vi_info *vi;
2431 	if_t ifp;
2432 	struct sge_txq *txq;
2433 	int rc, i, j, k;
2434 
2435 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2436 	if (rc != 0)
2437 		return (ENXIO);
2438 
2439 	/* Restore memory window. */
2440 	setup_memwin(sc);
2441 
2442 	/* Go no further if recovery mode has been requested. */
2443 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2444 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2445 		rc = 0;
2446 		set_adapter_hwstatus(sc, true);
2447 		goto done;
2448 	}
2449 
2450 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2451 	save_caps_and_params(sc, old_state);
2452 
2453 	/* Reestablish contact with firmware and become the primary PF. */
2454 	rc = contact_firmware(sc);
2455 	if (rc != 0)
2456 		goto done; /* error message displayed already */
2457 	MPASS(sc->flags & FW_OK);
2458 
2459 	if (sc->flags & MASTER_PF) {
2460 		rc = partition_resources(sc);
2461 		if (rc != 0)
2462 			goto done; /* error message displayed already */
2463 	}
2464 
2465 	rc = get_params__post_init(sc);
2466 	if (rc != 0)
2467 		goto done; /* error message displayed already */
2468 
2469 	rc = set_params__post_init(sc);
2470 	if (rc != 0)
2471 		goto done; /* error message displayed already */
2472 
2473 	rc = compare_caps_and_params(sc, old_state);
2474 	if (rc != 0)
2475 		goto done; /* error message displayed already */
2476 
2477 	for_each_port(sc, i) {
2478 		pi = sc->port[i];
2479 		MPASS(pi != NULL);
2480 		MPASS(pi->vi != NULL);
2481 		MPASS(pi->vi[0].dev == pi->dev);
2482 
2483 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2484 		if (rc != 0) {
2485 			CH_ERR(sc,
2486 			    "failed to re-initialize port %d: %d\n", i, rc);
2487 			goto done;
2488 		}
2489 		MPASS(sc->chan_map[pi->tx_chan] == i);
2490 
2491 		PORT_LOCK(pi);
2492 		fixup_link_config(pi);
2493 		build_medialist(pi);
2494 		PORT_UNLOCK(pi);
2495 		for_each_vi(pi, j, vi) {
2496 			if (IS_MAIN_VI(vi))
2497 				continue;
2498 			rc = alloc_extra_vi(sc, pi, vi);
2499 			if (rc != 0) {
2500 				CH_ERR(vi,
2501 				    "failed to re-allocate extra VI: %d\n", rc);
2502 				goto done;
2503 			}
2504 		}
2505 	}
2506 
2507 	/*
2508 	 * Interrupts and queues are about to be enabled and other threads will
2509 	 * want to access the hardware too.  It is safe to do so.  Note that
2510 	 * this thread is still in the middle of a synchronized_op.
2511 	 */
2512 	set_adapter_hwstatus(sc, true);
2513 
2514 	if (sc->flags & FULL_INIT_DONE) {
2515 		rc = adapter_full_init(sc);
2516 		if (rc != 0) {
2517 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2518 			goto done;
2519 		}
2520 
2521 		if (sc->vxlan_refcount > 0)
2522 			enable_vxlan_rx(sc);
2523 
2524 		for_each_port(sc, i) {
2525 			pi = sc->port[i];
2526 			for_each_vi(pi, j, vi) {
2527 				mtx_lock(&vi->tick_mtx);
2528 				vi->flags &= ~VI_SKIP_STATS;
2529 				mtx_unlock(&vi->tick_mtx);
2530 				if (!(vi->flags & VI_INIT_DONE))
2531 					continue;
2532 				rc = vi_full_init(vi);
2533 				if (rc != 0) {
2534 					CH_ERR(vi, "failed to re-initialize "
2535 					    "interface: %d\n", rc);
2536 					goto done;
2537 				}
2538 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2539 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2540 					t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
2541 					pi->flags |= HAS_TRACEQ;
2542 				}
2543 
2544 				ifp = vi->ifp;
2545 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2546 					continue;
2547 				/*
2548 				 * Note that we do not setup multicast addresses
2549 				 * in the first pass.  This ensures that the
2550 				 * unicast DMACs for all VIs on all ports get an
2551 				 * MPS TCAM entry.
2552 				 */
2553 				rc = update_mac_settings(ifp, XGMAC_ALL &
2554 				    ~XGMAC_MCADDRS);
2555 				if (rc != 0) {
2556 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2557 					goto done;
2558 				}
2559 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2560 				    true);
2561 				if (rc != 0) {
2562 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2563 					goto done;
2564 				}
2565 				for_each_txq(vi, k, txq) {
2566 					TXQ_LOCK(txq);
2567 					txq->eq.flags |= EQ_ENABLED;
2568 					TXQ_UNLOCK(txq);
2569 				}
2570 				mtx_lock(&vi->tick_mtx);
2571 				callout_schedule(&vi->tick, hz);
2572 				mtx_unlock(&vi->tick_mtx);
2573 			}
2574 			PORT_LOCK(pi);
2575 			if (pi->up_vis > 0) {
2576 				t4_update_port_info(pi);
2577 				fixup_link_config(pi);
2578 				build_medialist(pi);
2579 				apply_link_config(pi);
2580 				if (pi->link_cfg.link_ok)
2581 					t4_os_link_changed(pi);
2582 			}
2583 			PORT_UNLOCK(pi);
2584 		}
2585 
2586 		/* Now reprogram the L2 multicast addresses. */
2587 		for_each_port(sc, i) {
2588 			pi = sc->port[i];
2589 			for_each_vi(pi, j, vi) {
2590 				if (!(vi->flags & VI_INIT_DONE))
2591 					continue;
2592 				ifp = vi->ifp;
2593 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2594 					continue;
2595 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2596 				if (rc != 0) {
2597 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2598 					rc = 0;	/* carry on */
2599 				}
2600 			}
2601 		}
2602 	}
2603 
2604 	/* Reset all calibration */
2605 	t4_calibration_start(sc);
2606 done:
2607 	end_synchronized_op(sc, 0);
2608 	free(old_state, M_CXGBE);
2609 
2610 	restart_atid_allocator(sc);
2611 	t4_restart_l2t(sc);
2612 
2613 	return (rc);
2614 }
2615 
2616 int
2617 resume_adapter(struct adapter *sc)
2618 {
2619 	restart_adapter(sc);
2620 	restart_lld(sc);
2621 #ifdef TCP_OFFLOAD
2622 	restart_all_uld(sc);
2623 #endif
2624 	return (0);
2625 }
2626 
2627 static int
2628 t4_resume(device_t dev)
2629 {
2630 	struct adapter *sc = device_get_softc(dev);
2631 	int rc;
2632 
2633 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2634 	rc = resume_adapter(sc);
2635 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2636 
2637 	return (rc);
2638 }
2639 
2640 static int
2641 t4_reset_prepare(device_t dev, device_t child)
2642 {
2643 	struct adapter *sc = device_get_softc(dev);
2644 
2645 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2646 	return (0);
2647 }
2648 
2649 static int
2650 t4_reset_post(device_t dev, device_t child)
2651 {
2652 	struct adapter *sc = device_get_softc(dev);
2653 
2654 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2655 	return (0);
2656 }
2657 
2658 static int
2659 reset_adapter_with_pl_rst(struct adapter *sc)
2660 {
2661 	/* This is a t4_write_reg without the hw_off_limits check. */
2662 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2663 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2664 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2665 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2666 	return (0);
2667 }
2668 
2669 static int
2670 reset_adapter_with_pcie_sbr(struct adapter *sc)
2671 {
2672 	device_t pdev = device_get_parent(sc->dev);
2673 	device_t gpdev = device_get_parent(pdev);
2674 	device_t *children;
2675 	int rc, i, lcap, lsta, nchildren;
2676 	uint32_t v;
2677 
2678 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2679 	if (rc != 0) {
2680 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2681 		    device_get_nameunit(gpdev), rc);
2682 		return (ENOTSUP);
2683 	}
2684 	lcap = v + PCIER_LINK_CAP;
2685 	lsta = v + PCIER_LINK_STA;
2686 
2687 	nchildren = 0;
2688 	device_get_children(pdev, &children, &nchildren);
2689 	for (i = 0; i < nchildren; i++)
2690 		pci_save_state(children[i]);
2691 	v = pci_read_config(gpdev, PCIR_BRIDGECTL_1, 2);
2692 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v | PCIB_BCR_SECBUS_RESET, 2);
2693 	pause("pcie_sbr1", hz / 10);	/* 100ms */
2694 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v, 2);
2695 	pause("pcie_sbr2", hz);		/* Wait 1s before restore_state. */
2696 	v = pci_read_config(gpdev, lsta, 2);
2697 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2698 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2699 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2700 		rc = ETIMEDOUT;
2701 	else
2702 		rc = 0;
2703 	if (rc != 0)
2704 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2705 		    __func__, v);
2706 	else {
2707 		for (i = 0; i < nchildren; i++)
2708 			pci_restore_state(children[i]);
2709 	}
2710 	free(children, M_TEMP);
2711 
2712 	return (rc);
2713 }
2714 
2715 static int
2716 reset_adapter_with_pcie_link_bounce(struct adapter *sc)
2717 {
2718 	device_t pdev = device_get_parent(sc->dev);
2719 	device_t gpdev = device_get_parent(pdev);
2720 	device_t *children;
2721 	int rc, i, lcap, lctl, lsta, nchildren;
2722 	uint32_t v;
2723 
2724 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2725 	if (rc != 0) {
2726 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2727 		    device_get_nameunit(gpdev), rc);
2728 		return (ENOTSUP);
2729 	}
2730 	lcap = v + PCIER_LINK_CAP;
2731 	lctl = v + PCIER_LINK_CTL;
2732 	lsta = v + PCIER_LINK_STA;
2733 
2734 	nchildren = 0;
2735 	device_get_children(pdev, &children, &nchildren);
2736 	for (i = 0; i < nchildren; i++)
2737 		pci_save_state(children[i]);
2738 	v = pci_read_config(gpdev, lctl, 2);
2739 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_LINK_DIS, 2);
2740 	pause("pcie_lnk1", 100 * hz / 1000);	/* 100ms */
2741 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_RETRAIN_LINK, 2);
2742 	pause("pcie_lnk2", hz);		/* Wait 1s before restore_state. */
2743 	v = pci_read_config(gpdev, lsta, 2);
2744 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2745 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2746 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2747 		rc = ETIMEDOUT;
2748 	else
2749 		rc = 0;
2750 	if (rc != 0)
2751 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2752 		    __func__, v);
2753 	else {
2754 		for (i = 0; i < nchildren; i++)
2755 			pci_restore_state(children[i]);
2756 	}
2757 	free(children, M_TEMP);
2758 
2759 	return (rc);
2760 }
2761 
2762 static inline int
2763 reset_adapter(struct adapter *sc)
2764 {
2765 	int rc;
2766 	const int reset_method = vm_guest == VM_GUEST_NO ? t4_reset_method : 0;
2767 
2768 	rc = suspend_adapter(sc);
2769 	if (rc != 0)
2770 		return (rc);
2771 
2772 	switch (reset_method) {
2773 	case 1:
2774 		rc = reset_adapter_with_pcie_sbr(sc);
2775 		break;
2776 	case 2:
2777 		rc = reset_adapter_with_pcie_link_bounce(sc);
2778 		break;
2779 	case 0:
2780 	default:
2781 		rc = reset_adapter_with_pl_rst(sc);
2782 		break;
2783 	}
2784 	if (rc == 0)
2785 		rc = resume_adapter(sc);
2786 	return (rc);
2787 }
2788 
2789 static void
2790 reset_adapter_task(void *arg, int pending)
2791 {
2792 	struct adapter *sc = arg;
2793 	const int flags = sc->flags;
2794 	const int eflags = sc->error_flags;
2795 	int rc;
2796 
2797 	if (pending > 1)
2798 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2799 	rc = reset_adapter(sc);
2800 	if (rc != 0) {
2801 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2802 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2803 		       rc, flags, sc->flags, eflags, sc->error_flags);
2804 	}
2805 }
2806 
2807 static int
2808 cxgbe_probe(device_t dev)
2809 {
2810 	struct port_info *pi = device_get_softc(dev);
2811 
2812 	device_set_descf(dev, "port %d", pi->port_id);
2813 
2814 	return (BUS_PROBE_DEFAULT);
2815 }
2816 
2817 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2818     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2819     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2820     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2821 #define T4_CAP_ENABLE (T4_CAP)
2822 
2823 static void
2824 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2825 {
2826 	if_t ifp;
2827 	struct sbuf *sb;
2828 	struct sysctl_ctx_list *ctx = &vi->ctx;
2829 	struct sysctl_oid_list *children;
2830 	struct pfil_head_args pa;
2831 	struct adapter *sc = vi->adapter;
2832 
2833 	sysctl_ctx_init(ctx);
2834 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2835 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2836 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2837 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2838 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2839 #ifdef DEV_NETMAP
2840 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2841 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2842 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2843 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2844 #endif
2845 #ifdef TCP_OFFLOAD
2846 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2847 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2848 #endif
2849 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2850 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2851 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2852 #endif
2853 
2854 	vi->xact_addr_filt = -1;
2855 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2856 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2857 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2858 		vi->flags |= TX_USES_VM_WR;
2859 
2860 	/* Allocate an ifnet and set it up */
2861 	ifp = if_alloc_dev(IFT_ETHER, dev);
2862 	vi->ifp = ifp;
2863 	if_setsoftc(ifp, vi);
2864 
2865 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2866 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2867 
2868 	if_setinitfn(ifp, cxgbe_init);
2869 	if_setioctlfn(ifp, cxgbe_ioctl);
2870 	if_settransmitfn(ifp, cxgbe_transmit);
2871 	if_setqflushfn(ifp, cxgbe_qflush);
2872 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2873 		if_setgetcounterfn(ifp, vi_get_counter);
2874 	else
2875 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2876 #if defined(KERN_TLS) || defined(RATELIMIT)
2877 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2878 #endif
2879 #ifdef RATELIMIT
2880 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2881 #endif
2882 
2883 	if_setcapabilities(ifp, T4_CAP);
2884 	if_setcapenable(ifp, T4_CAP_ENABLE);
2885 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2886 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2887 	if (chip_id(sc) >= CHELSIO_T6) {
2888 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2889 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2890 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2891 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2892 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2893 	}
2894 
2895 #ifdef TCP_OFFLOAD
2896 	if (vi->nofldrxq != 0)
2897 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2898 #endif
2899 #ifdef RATELIMIT
2900 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2901 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2902 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2903 	}
2904 #endif
2905 
2906 	if_sethwtsomax(ifp, IP_MAXPACKET);
2907 	if (vi->flags & TX_USES_VM_WR)
2908 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2909 	else
2910 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2911 #ifdef RATELIMIT
2912 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2913 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2914 #endif
2915 	if_sethwtsomaxsegsize(ifp, 65536);
2916 #ifdef KERN_TLS
2917 	if (is_ktls(sc)) {
2918 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2919 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2920 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2921 	}
2922 #endif
2923 
2924 	ether_ifattach(ifp, vi->hw_addr);
2925 #ifdef DEV_NETMAP
2926 	if (vi->nnmrxq != 0)
2927 		cxgbe_nm_attach(vi);
2928 #endif
2929 	sb = sbuf_new_auto();
2930 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2931 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2932 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2933 	case IFCAP_TOE:
2934 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2935 		break;
2936 	case IFCAP_TOE | IFCAP_TXRTLMT:
2937 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2938 		break;
2939 	case IFCAP_TXRTLMT:
2940 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2941 		break;
2942 	}
2943 #endif
2944 #ifdef TCP_OFFLOAD
2945 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2946 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2947 #endif
2948 #ifdef DEV_NETMAP
2949 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2950 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2951 		    vi->nnmtxq, vi->nnmrxq);
2952 #endif
2953 	sbuf_finish(sb);
2954 	device_printf(dev, "%s\n", sbuf_data(sb));
2955 	sbuf_delete(sb);
2956 
2957 	vi_sysctls(vi);
2958 
2959 	pa.pa_version = PFIL_VERSION;
2960 	pa.pa_flags = PFIL_IN;
2961 	pa.pa_type = PFIL_TYPE_ETHERNET;
2962 	pa.pa_headname = if_name(ifp);
2963 	vi->pfil = pfil_head_register(&pa);
2964 }
2965 
2966 static int
2967 cxgbe_attach(device_t dev)
2968 {
2969 	struct port_info *pi = device_get_softc(dev);
2970 	struct adapter *sc = pi->adapter;
2971 	struct vi_info *vi;
2972 	int i;
2973 
2974 	sysctl_ctx_init(&pi->ctx);
2975 
2976 	cxgbe_vi_attach(dev, &pi->vi[0]);
2977 
2978 	for_each_vi(pi, i, vi) {
2979 		if (i == 0)
2980 			continue;
2981 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2982 		if (vi->dev == NULL) {
2983 			device_printf(dev, "failed to add VI %d\n", i);
2984 			continue;
2985 		}
2986 		device_set_softc(vi->dev, vi);
2987 	}
2988 
2989 	cxgbe_sysctls(pi);
2990 
2991 	bus_attach_children(dev);
2992 
2993 	return (0);
2994 }
2995 
2996 static void
2997 cxgbe_vi_detach(struct vi_info *vi)
2998 {
2999 	if_t ifp = vi->ifp;
3000 
3001 	if (vi->pfil != NULL) {
3002 		pfil_head_unregister(vi->pfil);
3003 		vi->pfil = NULL;
3004 	}
3005 
3006 	ether_ifdetach(ifp);
3007 
3008 	/* Let detach proceed even if these fail. */
3009 #ifdef DEV_NETMAP
3010 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
3011 		cxgbe_nm_detach(vi);
3012 #endif
3013 	cxgbe_uninit_synchronized(vi);
3014 	callout_drain(&vi->tick);
3015 	mtx_destroy(&vi->tick_mtx);
3016 	sysctl_ctx_free(&vi->ctx);
3017 	vi_full_uninit(vi);
3018 
3019 	if_free(vi->ifp);
3020 	vi->ifp = NULL;
3021 }
3022 
3023 static int
3024 cxgbe_detach(device_t dev)
3025 {
3026 	struct port_info *pi = device_get_softc(dev);
3027 	struct adapter *sc = pi->adapter;
3028 	int rc;
3029 
3030 	/* Detach the extra VIs first. */
3031 	rc = bus_generic_detach(dev);
3032 	if (rc)
3033 		return (rc);
3034 
3035 	sysctl_ctx_free(&pi->ctx);
3036 	begin_vi_detach(sc, &pi->vi[0]);
3037 	if (pi->flags & HAS_TRACEQ) {
3038 		sc->traceq = -1;	/* cloner should not create ifnet */
3039 		t4_tracer_port_detach(sc);
3040 	}
3041 	cxgbe_vi_detach(&pi->vi[0]);
3042 	ifmedia_removeall(&pi->media);
3043 	end_vi_detach(sc, &pi->vi[0]);
3044 
3045 	return (0);
3046 }
3047 
3048 static void
3049 cxgbe_init(void *arg)
3050 {
3051 	struct vi_info *vi = arg;
3052 	struct adapter *sc = vi->adapter;
3053 
3054 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
3055 		return;
3056 	cxgbe_init_synchronized(vi);
3057 	end_synchronized_op(sc, 0);
3058 }
3059 
3060 static int
3061 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
3062 {
3063 	int rc = 0, mtu, flags;
3064 	struct vi_info *vi = if_getsoftc(ifp);
3065 	struct port_info *pi = vi->pi;
3066 	struct adapter *sc = pi->adapter;
3067 	struct ifreq *ifr = (struct ifreq *)data;
3068 	uint32_t mask;
3069 
3070 	switch (cmd) {
3071 	case SIOCSIFMTU:
3072 		mtu = ifr->ifr_mtu;
3073 		if (mtu < ETHERMIN || mtu > MAX_MTU)
3074 			return (EINVAL);
3075 
3076 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
3077 		if (rc)
3078 			return (rc);
3079 		if_setmtu(ifp, mtu);
3080 		if (vi->flags & VI_INIT_DONE) {
3081 			t4_update_fl_bufsize(ifp);
3082 			if (hw_all_ok(sc) &&
3083 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3084 				rc = update_mac_settings(ifp, XGMAC_MTU);
3085 		}
3086 		end_synchronized_op(sc, 0);
3087 		break;
3088 
3089 	case SIOCSIFFLAGS:
3090 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
3091 		if (rc)
3092 			return (rc);
3093 
3094 		if (!hw_all_ok(sc)) {
3095 			rc = ENXIO;
3096 			goto fail;
3097 		}
3098 
3099 		if (if_getflags(ifp) & IFF_UP) {
3100 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3101 				flags = vi->if_flags;
3102 				if ((if_getflags(ifp) ^ flags) &
3103 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3104 					rc = update_mac_settings(ifp,
3105 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
3106 				}
3107 			} else {
3108 				rc = cxgbe_init_synchronized(vi);
3109 			}
3110 			vi->if_flags = if_getflags(ifp);
3111 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3112 			rc = cxgbe_uninit_synchronized(vi);
3113 		}
3114 		end_synchronized_op(sc, 0);
3115 		break;
3116 
3117 	case SIOCADDMULTI:
3118 	case SIOCDELMULTI:
3119 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
3120 		if (rc)
3121 			return (rc);
3122 		if (hw_all_ok(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3123 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
3124 		end_synchronized_op(sc, 0);
3125 		break;
3126 
3127 	case SIOCSIFCAP:
3128 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
3129 		if (rc)
3130 			return (rc);
3131 
3132 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3133 		if (mask & IFCAP_TXCSUM) {
3134 			if_togglecapenable(ifp, IFCAP_TXCSUM);
3135 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
3136 
3137 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
3138 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3139 				mask &= ~IFCAP_TSO4;
3140 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
3141 				if_printf(ifp,
3142 				    "tso4 disabled due to -txcsum.\n");
3143 			}
3144 		}
3145 		if (mask & IFCAP_TXCSUM_IPV6) {
3146 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
3147 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
3148 
3149 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
3150 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3151 				mask &= ~IFCAP_TSO6;
3152 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
3153 				if_printf(ifp,
3154 				    "tso6 disabled due to -txcsum6.\n");
3155 			}
3156 		}
3157 		if (mask & IFCAP_RXCSUM)
3158 			if_togglecapenable(ifp, IFCAP_RXCSUM);
3159 		if (mask & IFCAP_RXCSUM_IPV6)
3160 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
3161 
3162 		/*
3163 		 * Note that we leave CSUM_TSO alone (it is always set).  The
3164 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
3165 		 * sending a TSO request our way, so it's sufficient to toggle
3166 		 * IFCAP_TSOx only.
3167 		 */
3168 		if (mask & IFCAP_TSO4) {
3169 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
3170 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3171 				if_printf(ifp, "enable txcsum first.\n");
3172 				rc = EAGAIN;
3173 				goto fail;
3174 			}
3175 			if_togglecapenable(ifp, IFCAP_TSO4);
3176 		}
3177 		if (mask & IFCAP_TSO6) {
3178 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
3179 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3180 				if_printf(ifp, "enable txcsum6 first.\n");
3181 				rc = EAGAIN;
3182 				goto fail;
3183 			}
3184 			if_togglecapenable(ifp, IFCAP_TSO6);
3185 		}
3186 		if (mask & IFCAP_LRO) {
3187 #if defined(INET) || defined(INET6)
3188 			int i;
3189 			struct sge_rxq *rxq;
3190 
3191 			if_togglecapenable(ifp, IFCAP_LRO);
3192 			for_each_rxq(vi, i, rxq) {
3193 				if (if_getcapenable(ifp) & IFCAP_LRO)
3194 					rxq->iq.flags |= IQ_LRO_ENABLED;
3195 				else
3196 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
3197 			}
3198 #endif
3199 		}
3200 #ifdef TCP_OFFLOAD
3201 		if (mask & IFCAP_TOE) {
3202 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
3203 
3204 			rc = toe_capability(vi, enable);
3205 			if (rc != 0)
3206 				goto fail;
3207 
3208 			if_togglecapenable(ifp, mask);
3209 		}
3210 #endif
3211 		if (mask & IFCAP_VLAN_HWTAGGING) {
3212 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3213 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3214 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3215 		}
3216 		if (mask & IFCAP_VLAN_MTU) {
3217 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3218 
3219 			/* Need to find out how to disable auto-mtu-inflation */
3220 		}
3221 		if (mask & IFCAP_VLAN_HWTSO)
3222 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3223 		if (mask & IFCAP_VLAN_HWCSUM)
3224 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3225 #ifdef RATELIMIT
3226 		if (mask & IFCAP_TXRTLMT)
3227 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3228 #endif
3229 		if (mask & IFCAP_HWRXTSTMP) {
3230 			int i;
3231 			struct sge_rxq *rxq;
3232 
3233 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3234 			for_each_rxq(vi, i, rxq) {
3235 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3236 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3237 				else
3238 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3239 			}
3240 		}
3241 		if (mask & IFCAP_MEXTPG)
3242 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3243 
3244 #ifdef KERN_TLS
3245 		if (mask & IFCAP_TXTLS) {
3246 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3247 
3248 			rc = ktls_capability(sc, enable);
3249 			if (rc != 0)
3250 				goto fail;
3251 
3252 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3253 		}
3254 #endif
3255 		if (mask & IFCAP_VXLAN_HWCSUM) {
3256 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3257 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3258 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3259 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3260 		}
3261 		if (mask & IFCAP_VXLAN_HWTSO) {
3262 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3263 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3264 			    CSUM_INNER_IP_TSO);
3265 		}
3266 
3267 #ifdef VLAN_CAPABILITIES
3268 		VLAN_CAPABILITIES(ifp);
3269 #endif
3270 fail:
3271 		end_synchronized_op(sc, 0);
3272 		break;
3273 
3274 	case SIOCSIFMEDIA:
3275 	case SIOCGIFMEDIA:
3276 	case SIOCGIFXMEDIA:
3277 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3278 		break;
3279 
3280 	case SIOCGI2C: {
3281 		struct ifi2creq i2c;
3282 
3283 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3284 		if (rc != 0)
3285 			break;
3286 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3287 			rc = EPERM;
3288 			break;
3289 		}
3290 		if (i2c.len > sizeof(i2c.data)) {
3291 			rc = EINVAL;
3292 			break;
3293 		}
3294 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3295 		if (rc)
3296 			return (rc);
3297 		if (!hw_all_ok(sc))
3298 			rc = ENXIO;
3299 		else
3300 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3301 			    i2c.offset, i2c.len, &i2c.data[0]);
3302 		end_synchronized_op(sc, 0);
3303 		if (rc == 0)
3304 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3305 		break;
3306 	}
3307 
3308 	default:
3309 		rc = ether_ioctl(ifp, cmd, data);
3310 	}
3311 
3312 	return (rc);
3313 }
3314 
3315 static int
3316 cxgbe_transmit(if_t ifp, struct mbuf *m)
3317 {
3318 	struct vi_info *vi = if_getsoftc(ifp);
3319 	struct port_info *pi = vi->pi;
3320 	struct adapter *sc;
3321 	struct sge_txq *txq;
3322 	void *items[1];
3323 	int rc;
3324 
3325 	M_ASSERTPKTHDR(m);
3326 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3327 #if defined(KERN_TLS) || defined(RATELIMIT)
3328 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3329 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3330 #endif
3331 
3332 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3333 		m_freem(m);
3334 		return (ENETDOWN);
3335 	}
3336 
3337 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3338 	if (__predict_false(rc != 0)) {
3339 		if (__predict_true(rc == EINPROGRESS)) {
3340 			/* queued by parse_pkt */
3341 			MPASS(m != NULL);
3342 			return (0);
3343 		}
3344 
3345 		MPASS(m == NULL);			/* was freed already */
3346 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3347 		return (rc);
3348 	}
3349 
3350 	/* Select a txq. */
3351 	sc = vi->adapter;
3352 	txq = &sc->sge.txq[vi->first_txq];
3353 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3354 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3355 		    vi->rsrv_noflowq);
3356 
3357 	items[0] = m;
3358 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3359 	if (__predict_false(rc != 0))
3360 		m_freem(m);
3361 
3362 	return (rc);
3363 }
3364 
3365 static void
3366 cxgbe_qflush(if_t ifp)
3367 {
3368 	struct vi_info *vi = if_getsoftc(ifp);
3369 	struct sge_txq *txq;
3370 	int i;
3371 
3372 	/* queues do not exist if !VI_INIT_DONE. */
3373 	if (vi->flags & VI_INIT_DONE) {
3374 		for_each_txq(vi, i, txq) {
3375 			TXQ_LOCK(txq);
3376 			txq->eq.flags |= EQ_QFLUSH;
3377 			TXQ_UNLOCK(txq);
3378 			while (!mp_ring_is_idle(txq->r)) {
3379 				mp_ring_check_drainage(txq->r, 4096);
3380 				pause("qflush", 1);
3381 			}
3382 			TXQ_LOCK(txq);
3383 			txq->eq.flags &= ~EQ_QFLUSH;
3384 			TXQ_UNLOCK(txq);
3385 		}
3386 	}
3387 	if_qflush(ifp);
3388 }
3389 
3390 static uint64_t
3391 vi_get_counter(if_t ifp, ift_counter c)
3392 {
3393 	struct vi_info *vi = if_getsoftc(ifp);
3394 	struct fw_vi_stats_vf *s = &vi->stats;
3395 
3396 	mtx_lock(&vi->tick_mtx);
3397 	vi_refresh_stats(vi);
3398 	mtx_unlock(&vi->tick_mtx);
3399 
3400 	switch (c) {
3401 	case IFCOUNTER_IPACKETS:
3402 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3403 		    s->rx_ucast_frames);
3404 	case IFCOUNTER_IERRORS:
3405 		return (s->rx_err_frames);
3406 	case IFCOUNTER_OPACKETS:
3407 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3408 		    s->tx_ucast_frames + s->tx_offload_frames);
3409 	case IFCOUNTER_OERRORS:
3410 		return (s->tx_drop_frames);
3411 	case IFCOUNTER_IBYTES:
3412 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3413 		    s->rx_ucast_bytes);
3414 	case IFCOUNTER_OBYTES:
3415 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3416 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3417 	case IFCOUNTER_IMCASTS:
3418 		return (s->rx_mcast_frames);
3419 	case IFCOUNTER_OMCASTS:
3420 		return (s->tx_mcast_frames);
3421 	case IFCOUNTER_OQDROPS: {
3422 		uint64_t drops;
3423 
3424 		drops = 0;
3425 		if (vi->flags & VI_INIT_DONE) {
3426 			int i;
3427 			struct sge_txq *txq;
3428 
3429 			for_each_txq(vi, i, txq)
3430 				drops += counter_u64_fetch(txq->r->dropped);
3431 		}
3432 
3433 		return (drops);
3434 
3435 	}
3436 
3437 	default:
3438 		return (if_get_counter_default(ifp, c));
3439 	}
3440 }
3441 
3442 static uint64_t
3443 cxgbe_get_counter(if_t ifp, ift_counter c)
3444 {
3445 	struct vi_info *vi = if_getsoftc(ifp);
3446 	struct port_info *pi = vi->pi;
3447 	struct port_stats *s = &pi->stats;
3448 
3449 	mtx_lock(&vi->tick_mtx);
3450 	cxgbe_refresh_stats(vi);
3451 	mtx_unlock(&vi->tick_mtx);
3452 
3453 	switch (c) {
3454 	case IFCOUNTER_IPACKETS:
3455 		return (s->rx_frames);
3456 
3457 	case IFCOUNTER_IERRORS:
3458 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3459 		    s->rx_fcs_err + s->rx_len_err);
3460 
3461 	case IFCOUNTER_OPACKETS:
3462 		return (s->tx_frames);
3463 
3464 	case IFCOUNTER_OERRORS:
3465 		return (s->tx_error_frames);
3466 
3467 	case IFCOUNTER_IBYTES:
3468 		return (s->rx_octets);
3469 
3470 	case IFCOUNTER_OBYTES:
3471 		return (s->tx_octets);
3472 
3473 	case IFCOUNTER_IMCASTS:
3474 		return (s->rx_mcast_frames);
3475 
3476 	case IFCOUNTER_OMCASTS:
3477 		return (s->tx_mcast_frames);
3478 
3479 	case IFCOUNTER_IQDROPS:
3480 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3481 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3482 		    s->rx_trunc3 + pi->tnl_cong_drops);
3483 
3484 	case IFCOUNTER_OQDROPS: {
3485 		uint64_t drops;
3486 
3487 		drops = s->tx_drop;
3488 		if (vi->flags & VI_INIT_DONE) {
3489 			int i;
3490 			struct sge_txq *txq;
3491 
3492 			for_each_txq(vi, i, txq)
3493 				drops += counter_u64_fetch(txq->r->dropped);
3494 		}
3495 
3496 		return (drops);
3497 
3498 	}
3499 
3500 	default:
3501 		return (if_get_counter_default(ifp, c));
3502 	}
3503 }
3504 
3505 #if defined(KERN_TLS) || defined(RATELIMIT)
3506 static int
3507 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3508     struct m_snd_tag **pt)
3509 {
3510 	int error;
3511 
3512 	switch (params->hdr.type) {
3513 #ifdef RATELIMIT
3514 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3515 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3516 		break;
3517 #endif
3518 #ifdef KERN_TLS
3519 	case IF_SND_TAG_TYPE_TLS:
3520 	{
3521 		struct vi_info *vi = if_getsoftc(ifp);
3522 
3523 		if (is_t6(vi->pi->adapter))
3524 			error = t6_tls_tag_alloc(ifp, params, pt);
3525 		else
3526 			error = t7_tls_tag_alloc(ifp, params, pt);
3527 		break;
3528 	}
3529 #endif
3530 	default:
3531 		error = EOPNOTSUPP;
3532 	}
3533 	return (error);
3534 }
3535 #endif
3536 
3537 /*
3538  * The kernel picks a media from the list we had provided but we still validate
3539  * the requeste.
3540  */
3541 int
3542 cxgbe_media_change(if_t ifp)
3543 {
3544 	struct vi_info *vi = if_getsoftc(ifp);
3545 	struct port_info *pi = vi->pi;
3546 	struct ifmedia *ifm = &pi->media;
3547 	struct link_config *lc = &pi->link_cfg;
3548 	struct adapter *sc = pi->adapter;
3549 	int rc;
3550 
3551 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3552 	if (rc != 0)
3553 		return (rc);
3554 	PORT_LOCK(pi);
3555 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3556 		/* ifconfig .. media autoselect */
3557 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3558 			rc = ENOTSUP; /* AN not supported by transceiver */
3559 			goto done;
3560 		}
3561 		lc->requested_aneg = AUTONEG_ENABLE;
3562 		lc->requested_speed = 0;
3563 		lc->requested_fc |= PAUSE_AUTONEG;
3564 	} else {
3565 		lc->requested_aneg = AUTONEG_DISABLE;
3566 		lc->requested_speed =
3567 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3568 		lc->requested_fc = 0;
3569 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3570 			lc->requested_fc |= PAUSE_RX;
3571 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3572 			lc->requested_fc |= PAUSE_TX;
3573 	}
3574 	if (pi->up_vis > 0 && hw_all_ok(sc)) {
3575 		fixup_link_config(pi);
3576 		rc = apply_link_config(pi);
3577 	}
3578 done:
3579 	PORT_UNLOCK(pi);
3580 	end_synchronized_op(sc, 0);
3581 	return (rc);
3582 }
3583 
3584 /*
3585  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3586  * given speed.
3587  */
3588 static int
3589 port_mword(struct port_info *pi, uint32_t speed)
3590 {
3591 
3592 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3593 	MPASS(powerof2(speed));
3594 
3595 	switch(pi->port_type) {
3596 	case FW_PORT_TYPE_BT_SGMII:
3597 	case FW_PORT_TYPE_BT_XFI:
3598 	case FW_PORT_TYPE_BT_XAUI:
3599 		/* BaseT */
3600 		switch (speed) {
3601 		case FW_PORT_CAP32_SPEED_100M:
3602 			return (IFM_100_T);
3603 		case FW_PORT_CAP32_SPEED_1G:
3604 			return (IFM_1000_T);
3605 		case FW_PORT_CAP32_SPEED_10G:
3606 			return (IFM_10G_T);
3607 		}
3608 		break;
3609 	case FW_PORT_TYPE_KX4:
3610 		if (speed == FW_PORT_CAP32_SPEED_10G)
3611 			return (IFM_10G_KX4);
3612 		break;
3613 	case FW_PORT_TYPE_CX4:
3614 		if (speed == FW_PORT_CAP32_SPEED_10G)
3615 			return (IFM_10G_CX4);
3616 		break;
3617 	case FW_PORT_TYPE_KX:
3618 		if (speed == FW_PORT_CAP32_SPEED_1G)
3619 			return (IFM_1000_KX);
3620 		break;
3621 	case FW_PORT_TYPE_KR:
3622 	case FW_PORT_TYPE_BP_AP:
3623 	case FW_PORT_TYPE_BP4_AP:
3624 	case FW_PORT_TYPE_BP40_BA:
3625 	case FW_PORT_TYPE_KR4_100G:
3626 	case FW_PORT_TYPE_KR_SFP28:
3627 	case FW_PORT_TYPE_KR_XLAUI:
3628 		switch (speed) {
3629 		case FW_PORT_CAP32_SPEED_1G:
3630 			return (IFM_1000_KX);
3631 		case FW_PORT_CAP32_SPEED_10G:
3632 			return (IFM_10G_KR);
3633 		case FW_PORT_CAP32_SPEED_25G:
3634 			return (IFM_25G_KR);
3635 		case FW_PORT_CAP32_SPEED_40G:
3636 			return (IFM_40G_KR4);
3637 		case FW_PORT_CAP32_SPEED_50G:
3638 			return (IFM_50G_KR2);
3639 		case FW_PORT_CAP32_SPEED_100G:
3640 			return (IFM_100G_KR4);
3641 		}
3642 		break;
3643 	case FW_PORT_TYPE_FIBER_XFI:
3644 	case FW_PORT_TYPE_FIBER_XAUI:
3645 	case FW_PORT_TYPE_SFP:
3646 	case FW_PORT_TYPE_QSFP_10G:
3647 	case FW_PORT_TYPE_QSA:
3648 	case FW_PORT_TYPE_QSFP:
3649 	case FW_PORT_TYPE_CR4_QSFP:
3650 	case FW_PORT_TYPE_CR_QSFP:
3651 	case FW_PORT_TYPE_CR2_QSFP:
3652 	case FW_PORT_TYPE_SFP28:
3653 	case FW_PORT_TYPE_SFP56:
3654 	case FW_PORT_TYPE_QSFP56:
3655 		/* Pluggable transceiver */
3656 		switch (pi->mod_type) {
3657 		case FW_PORT_MOD_TYPE_LR:
3658 		case FW_PORT_MOD_TYPE_LR_SIMPLEX:
3659 			switch (speed) {
3660 			case FW_PORT_CAP32_SPEED_1G:
3661 				return (IFM_1000_LX);
3662 			case FW_PORT_CAP32_SPEED_10G:
3663 				return (IFM_10G_LR);
3664 			case FW_PORT_CAP32_SPEED_25G:
3665 				return (IFM_25G_LR);
3666 			case FW_PORT_CAP32_SPEED_40G:
3667 				return (IFM_40G_LR4);
3668 			case FW_PORT_CAP32_SPEED_50G:
3669 				return (IFM_50G_LR2);
3670 			case FW_PORT_CAP32_SPEED_100G:
3671 				return (IFM_100G_LR4);
3672 			case FW_PORT_CAP32_SPEED_200G:
3673 				return (IFM_200G_LR4);
3674 			}
3675 			break;
3676 		case FW_PORT_MOD_TYPE_SR:
3677 			switch (speed) {
3678 			case FW_PORT_CAP32_SPEED_1G:
3679 				return (IFM_1000_SX);
3680 			case FW_PORT_CAP32_SPEED_10G:
3681 				return (IFM_10G_SR);
3682 			case FW_PORT_CAP32_SPEED_25G:
3683 				return (IFM_25G_SR);
3684 			case FW_PORT_CAP32_SPEED_40G:
3685 				return (IFM_40G_SR4);
3686 			case FW_PORT_CAP32_SPEED_50G:
3687 				return (IFM_50G_SR2);
3688 			case FW_PORT_CAP32_SPEED_100G:
3689 				return (IFM_100G_SR4);
3690 			case FW_PORT_CAP32_SPEED_200G:
3691 				return (IFM_200G_SR4);
3692 			}
3693 			break;
3694 		case FW_PORT_MOD_TYPE_ER:
3695 			if (speed == FW_PORT_CAP32_SPEED_10G)
3696 				return (IFM_10G_ER);
3697 			break;
3698 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3699 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3700 			switch (speed) {
3701 			case FW_PORT_CAP32_SPEED_1G:
3702 				return (IFM_1000_CX);
3703 			case FW_PORT_CAP32_SPEED_10G:
3704 				return (IFM_10G_TWINAX);
3705 			case FW_PORT_CAP32_SPEED_25G:
3706 				return (IFM_25G_CR);
3707 			case FW_PORT_CAP32_SPEED_40G:
3708 				return (IFM_40G_CR4);
3709 			case FW_PORT_CAP32_SPEED_50G:
3710 				return (IFM_50G_CR2);
3711 			case FW_PORT_CAP32_SPEED_100G:
3712 				return (IFM_100G_CR4);
3713 			case FW_PORT_CAP32_SPEED_200G:
3714 				return (IFM_200G_CR4_PAM4);
3715 			}
3716 			break;
3717 		case FW_PORT_MOD_TYPE_LRM:
3718 			if (speed == FW_PORT_CAP32_SPEED_10G)
3719 				return (IFM_10G_LRM);
3720 			break;
3721 		case FW_PORT_MOD_TYPE_DR:
3722 			if (speed == FW_PORT_CAP32_SPEED_100G)
3723 				return (IFM_100G_DR);
3724 			if (speed == FW_PORT_CAP32_SPEED_200G)
3725 				return (IFM_200G_DR4);
3726 			break;
3727 		case FW_PORT_MOD_TYPE_NA:
3728 			MPASS(0);	/* Not pluggable? */
3729 			/* fall throough */
3730 		case FW_PORT_MOD_TYPE_ERROR:
3731 		case FW_PORT_MOD_TYPE_UNKNOWN:
3732 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3733 			break;
3734 		case FW_PORT_MOD_TYPE_NONE:
3735 			return (IFM_NONE);
3736 		}
3737 		break;
3738 	case FW_PORT_TYPE_NONE:
3739 		return (IFM_NONE);
3740 	}
3741 
3742 	return (IFM_UNKNOWN);
3743 }
3744 
3745 void
3746 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3747 {
3748 	struct vi_info *vi = if_getsoftc(ifp);
3749 	struct port_info *pi = vi->pi;
3750 	struct adapter *sc = pi->adapter;
3751 	struct link_config *lc = &pi->link_cfg;
3752 
3753 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3754 		return;
3755 	PORT_LOCK(pi);
3756 
3757 	if (pi->up_vis == 0 && hw_all_ok(sc)) {
3758 		/*
3759 		 * If all the interfaces are administratively down the firmware
3760 		 * does not report transceiver changes.  Refresh port info here
3761 		 * so that ifconfig displays accurate ifmedia at all times.
3762 		 * This is the only reason we have a synchronized op in this
3763 		 * function.  Just PORT_LOCK would have been enough otherwise.
3764 		 */
3765 		t4_update_port_info(pi);
3766 		build_medialist(pi);
3767 	}
3768 
3769 	/* ifm_status */
3770 	ifmr->ifm_status = IFM_AVALID;
3771 	if (lc->link_ok == false)
3772 		goto done;
3773 	ifmr->ifm_status |= IFM_ACTIVE;
3774 
3775 	/* ifm_active */
3776 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3777 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3778 	if (lc->fc & PAUSE_RX)
3779 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3780 	if (lc->fc & PAUSE_TX)
3781 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3782 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3783 done:
3784 	PORT_UNLOCK(pi);
3785 	end_synchronized_op(sc, 0);
3786 }
3787 
3788 static int
3789 vcxgbe_probe(device_t dev)
3790 {
3791 	struct vi_info *vi = device_get_softc(dev);
3792 
3793 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3794 	    vi - vi->pi->vi);
3795 
3796 	return (BUS_PROBE_DEFAULT);
3797 }
3798 
3799 static int
3800 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3801 {
3802 	int func, index, rc;
3803 	uint32_t param, val;
3804 
3805 	ASSERT_SYNCHRONIZED_OP(sc);
3806 
3807 	index = vi - pi->vi;
3808 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3809 	KASSERT(index < nitems(vi_mac_funcs),
3810 	    ("%s: VI %s doesn't have a MAC func", __func__,
3811 	    device_get_nameunit(vi->dev)));
3812 	func = vi_mac_funcs[index];
3813 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->hw_port, sc->pf, 0, 1,
3814 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3815 	if (rc < 0) {
3816 		CH_ERR(vi, "failed to allocate virtual interface %d"
3817 		    "for port %d: %d\n", index, pi->port_id, -rc);
3818 		return (-rc);
3819 	}
3820 	vi->viid = rc;
3821 
3822 	if (vi->rss_size == 1) {
3823 		/*
3824 		 * This VI didn't get a slice of the RSS table.  Reduce the
3825 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3826 		 * configuration file (nvi, rssnvi for this PF) if this is a
3827 		 * problem.
3828 		 */
3829 		device_printf(vi->dev, "RSS table not available.\n");
3830 		vi->rss_base = 0xffff;
3831 
3832 		return (0);
3833 	}
3834 
3835 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3836 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3837 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3838 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3839 	if (rc)
3840 		vi->rss_base = 0xffff;
3841 	else {
3842 		MPASS((val >> 16) == vi->rss_size);
3843 		vi->rss_base = val & 0xffff;
3844 	}
3845 
3846 	return (0);
3847 }
3848 
3849 static int
3850 vcxgbe_attach(device_t dev)
3851 {
3852 	struct vi_info *vi;
3853 	struct port_info *pi;
3854 	struct adapter *sc;
3855 	int rc;
3856 
3857 	vi = device_get_softc(dev);
3858 	pi = vi->pi;
3859 	sc = pi->adapter;
3860 
3861 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3862 	if (rc)
3863 		return (rc);
3864 	rc = alloc_extra_vi(sc, pi, vi);
3865 	end_synchronized_op(sc, 0);
3866 	if (rc)
3867 		return (rc);
3868 
3869 	cxgbe_vi_attach(dev, vi);
3870 
3871 	return (0);
3872 }
3873 
3874 static int
3875 vcxgbe_detach(device_t dev)
3876 {
3877 	struct vi_info *vi;
3878 	struct adapter *sc;
3879 
3880 	vi = device_get_softc(dev);
3881 	sc = vi->adapter;
3882 
3883 	begin_vi_detach(sc, vi);
3884 	cxgbe_vi_detach(vi);
3885 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3886 	end_vi_detach(sc, vi);
3887 
3888 	return (0);
3889 }
3890 
3891 static struct callout fatal_callout;
3892 static struct taskqueue *reset_tq;
3893 
3894 static void
3895 delayed_panic(void *arg)
3896 {
3897 	struct adapter *sc = arg;
3898 
3899 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3900 }
3901 
3902 static void
3903 fatal_error_task(void *arg, int pending)
3904 {
3905 	struct adapter *sc = arg;
3906 	int rc;
3907 
3908 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3909 		dump_cim_regs(sc);
3910 		dump_cimla(sc);
3911 		dump_devlog(sc);
3912 	}
3913 
3914 	if (t4_reset_on_fatal_err) {
3915 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3916 		rc = reset_adapter(sc);
3917 		if (rc == 0 && t4_panic_on_fatal_err) {
3918 			CH_ALERT(sc, "reset was successful, "
3919 			    "system will NOT panic.\n");
3920 			return;
3921 		}
3922 	}
3923 
3924 	if (t4_panic_on_fatal_err) {
3925 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3926 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3927 	}
3928 }
3929 
3930 void
3931 t4_fatal_err(struct adapter *sc, bool fw_error)
3932 {
3933 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3934 
3935 	stop_adapter(sc);
3936 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3937 		return;
3938 	if (fw_error) {
3939 		/*
3940 		 * We are here because of a firmware error/timeout and not
3941 		 * because of a hardware interrupt.  It is possible (although
3942 		 * not very likely) that an error interrupt was also raised but
3943 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3944 		 * main INT_CAUSE registers here to make sure we haven't missed
3945 		 * anything interesting.
3946 		 */
3947 		t4_slow_intr_handler(sc, verbose);
3948 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3949 	}
3950 	t4_report_fw_error(sc);
3951 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3952 	    device_get_nameunit(sc->dev), fw_error);
3953 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3954 }
3955 
3956 void
3957 t4_add_adapter(struct adapter *sc)
3958 {
3959 	sx_xlock(&t4_list_lock);
3960 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3961 	sx_xunlock(&t4_list_lock);
3962 }
3963 
3964 int
3965 t4_map_bars_0_and_4(struct adapter *sc)
3966 {
3967 	sc->regs_rid = PCIR_BAR(0);
3968 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3969 	    &sc->regs_rid, RF_ACTIVE);
3970 	if (sc->regs_res == NULL) {
3971 		device_printf(sc->dev, "cannot map registers.\n");
3972 		return (ENXIO);
3973 	}
3974 	sc->bt = rman_get_bustag(sc->regs_res);
3975 	sc->bh = rman_get_bushandle(sc->regs_res);
3976 	sc->mmio_len = rman_get_size(sc->regs_res);
3977 	setbit(&sc->doorbells, DOORBELL_KDB);
3978 
3979 	sc->msix_rid = PCIR_BAR(4);
3980 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3981 	    &sc->msix_rid, RF_ACTIVE);
3982 	if (sc->msix_res == NULL) {
3983 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3984 		return (ENXIO);
3985 	}
3986 
3987 	return (0);
3988 }
3989 
3990 int
3991 t4_map_bar_2(struct adapter *sc)
3992 {
3993 
3994 	/*
3995 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3996 	 * to map it if RDMA is disabled.
3997 	 */
3998 	if (is_t4(sc) && sc->rdmacaps == 0)
3999 		return (0);
4000 
4001 	sc->udbs_rid = PCIR_BAR(2);
4002 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4003 	    &sc->udbs_rid, RF_ACTIVE);
4004 	if (sc->udbs_res == NULL) {
4005 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
4006 		return (ENXIO);
4007 	}
4008 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
4009 
4010 	if (chip_id(sc) >= CHELSIO_T5) {
4011 		setbit(&sc->doorbells, DOORBELL_UDB);
4012 #if defined(__i386__) || defined(__amd64__)
4013 		if (t5_write_combine) {
4014 			int rc, mode;
4015 
4016 			/*
4017 			 * Enable write combining on BAR2.  This is the
4018 			 * userspace doorbell BAR and is split into 128B
4019 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
4020 			 * with an egress queue.  The first 64B has the doorbell
4021 			 * and the second 64B can be used to submit a tx work
4022 			 * request with an implicit doorbell.
4023 			 */
4024 
4025 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
4026 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
4027 			if (rc == 0) {
4028 				clrbit(&sc->doorbells, DOORBELL_UDB);
4029 				setbit(&sc->doorbells, DOORBELL_WCWR);
4030 				setbit(&sc->doorbells, DOORBELL_UDBWC);
4031 			} else {
4032 				device_printf(sc->dev,
4033 				    "couldn't enable write combining: %d\n",
4034 				    rc);
4035 			}
4036 
4037 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
4038 			t4_write_reg(sc, A_SGE_STAT_CFG,
4039 			    V_STATSOURCE_T5(7) | mode);
4040 		}
4041 #endif
4042 	}
4043 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
4044 
4045 	return (0);
4046 }
4047 
4048 int
4049 t4_adj_doorbells(struct adapter *sc)
4050 {
4051 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
4052 		sc->doorbells &= t4_doorbells_allowed;
4053 		return (0);
4054 	}
4055 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
4056 	       sc->doorbells, t4_doorbells_allowed);
4057 	return (EINVAL);
4058 }
4059 
4060 struct memwin_init {
4061 	uint32_t base;
4062 	uint32_t aperture;
4063 };
4064 
4065 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
4066 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4067 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4068 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
4069 };
4070 
4071 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
4072 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4073 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4074 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
4075 };
4076 
4077 static void
4078 setup_memwin(struct adapter *sc)
4079 {
4080 	const struct memwin_init *mw_init;
4081 	struct memwin *mw;
4082 	int i;
4083 	uint32_t bar0, reg;
4084 
4085 	if (is_t4(sc)) {
4086 		/*
4087 		 * Read low 32b of bar0 indirectly via the hardware backdoor
4088 		 * mechanism.  Works from within PCI passthrough environments
4089 		 * too, where rman_get_start() can return a different value.  We
4090 		 * need to program the T4 memory window decoders with the actual
4091 		 * addresses that will be coming across the PCIe link.
4092 		 */
4093 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
4094 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
4095 
4096 		mw_init = &t4_memwin[0];
4097 	} else {
4098 		/* T5+ use the relative offset inside the PCIe BAR */
4099 		bar0 = 0;
4100 
4101 		mw_init = &t5_memwin[0];
4102 	}
4103 
4104 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
4105 		if (!rw_initialized(&mw->mw_lock)) {
4106 			rw_init(&mw->mw_lock, "memory window access");
4107 			mw->mw_base = mw_init->base;
4108 			mw->mw_aperture = mw_init->aperture;
4109 			mw->mw_curpos = 0;
4110 		}
4111 		reg = chip_id(sc) > CHELSIO_T6 ?
4112 		    PCIE_MEM_ACCESS_T7_REG(A_T7_PCIE_MEM_ACCESS_BASE_WIN, i) :
4113 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i);
4114 		t4_write_reg(sc, reg, (mw->mw_base + bar0) | V_BIR(0) |
4115 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
4116 		rw_wlock(&mw->mw_lock);
4117 		position_memwin(sc, i, mw->mw_curpos);
4118 		rw_wunlock(&mw->mw_lock);
4119 	}
4120 
4121 	/* flush */
4122 	t4_read_reg(sc, reg);
4123 }
4124 
4125 /*
4126  * Positions the memory window at the given address in the card's address space.
4127  * There are some alignment requirements and the actual position may be at an
4128  * address prior to the requested address.  mw->mw_curpos always has the actual
4129  * position of the window.
4130  */
4131 static void
4132 position_memwin(struct adapter *sc, int idx, uint32_t addr)
4133 {
4134 	struct memwin *mw;
4135 	uint32_t pf, reg, val;
4136 
4137 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4138 	mw = &sc->memwin[idx];
4139 	rw_assert(&mw->mw_lock, RA_WLOCKED);
4140 
4141 	if (is_t4(sc)) {
4142 		pf = 0;
4143 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
4144 	} else {
4145 		pf = V_PFNUM(sc->pf);
4146 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
4147 	}
4148 	if (chip_id(sc) > CHELSIO_T6) {
4149 		reg = PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, idx);
4150 		val = (mw->mw_curpos >> X_T7_MEMOFST_SHIFT) | pf;
4151 	} else {
4152 		reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
4153 		val = mw->mw_curpos | pf;
4154 	}
4155 	t4_write_reg(sc, reg, val);
4156 	t4_read_reg(sc, reg);	/* flush */
4157 }
4158 
4159 int
4160 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
4161     int len, int rw)
4162 {
4163 	struct memwin *mw;
4164 	uint32_t mw_end, v;
4165 
4166 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4167 
4168 	/* Memory can only be accessed in naturally aligned 4 byte units */
4169 	if (addr & 3 || len & 3 || len <= 0)
4170 		return (EINVAL);
4171 
4172 	mw = &sc->memwin[idx];
4173 	while (len > 0) {
4174 		rw_rlock(&mw->mw_lock);
4175 		mw_end = mw->mw_curpos + mw->mw_aperture;
4176 		if (addr >= mw_end || addr < mw->mw_curpos) {
4177 			/* Will need to reposition the window */
4178 			if (!rw_try_upgrade(&mw->mw_lock)) {
4179 				rw_runlock(&mw->mw_lock);
4180 				rw_wlock(&mw->mw_lock);
4181 			}
4182 			rw_assert(&mw->mw_lock, RA_WLOCKED);
4183 			position_memwin(sc, idx, addr);
4184 			rw_downgrade(&mw->mw_lock);
4185 			mw_end = mw->mw_curpos + mw->mw_aperture;
4186 		}
4187 		rw_assert(&mw->mw_lock, RA_RLOCKED);
4188 		while (addr < mw_end && len > 0) {
4189 			if (rw == 0) {
4190 				v = t4_read_reg(sc, mw->mw_base + addr -
4191 				    mw->mw_curpos);
4192 				*val++ = le32toh(v);
4193 			} else {
4194 				v = *val++;
4195 				t4_write_reg(sc, mw->mw_base + addr -
4196 				    mw->mw_curpos, htole32(v));
4197 			}
4198 			addr += 4;
4199 			len -= 4;
4200 		}
4201 		rw_runlock(&mw->mw_lock);
4202 	}
4203 
4204 	return (0);
4205 }
4206 
4207 CTASSERT(M_TID_COOKIE == M_COOKIE);
4208 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
4209 
4210 static void
4211 t4_init_atid_table(struct adapter *sc)
4212 {
4213 	struct tid_info *t;
4214 	int i;
4215 
4216 	t = &sc->tids;
4217 	if (t->natids == 0)
4218 		return;
4219 
4220 	MPASS(t->atid_tab == NULL);
4221 
4222 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
4223 	    M_ZERO | M_WAITOK);
4224 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
4225 	t->afree = t->atid_tab;
4226 	t->atids_in_use = 0;
4227 	t->atid_alloc_stopped = false;
4228 	for (i = 1; i < t->natids; i++)
4229 		t->atid_tab[i - 1].next = &t->atid_tab[i];
4230 	t->atid_tab[t->natids - 1].next = NULL;
4231 }
4232 
4233 static void
4234 t4_free_atid_table(struct adapter *sc)
4235 {
4236 	struct tid_info *t;
4237 
4238 	t = &sc->tids;
4239 
4240 	KASSERT(t->atids_in_use == 0,
4241 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4242 
4243 	if (mtx_initialized(&t->atid_lock))
4244 		mtx_destroy(&t->atid_lock);
4245 	free(t->atid_tab, M_CXGBE);
4246 	t->atid_tab = NULL;
4247 }
4248 
4249 static void
4250 stop_atid_allocator(struct adapter *sc)
4251 {
4252 	struct tid_info *t = &sc->tids;
4253 
4254 	if (t->natids == 0)
4255 		return;
4256 	mtx_lock(&t->atid_lock);
4257 	t->atid_alloc_stopped = true;
4258 	mtx_unlock(&t->atid_lock);
4259 }
4260 
4261 static void
4262 restart_atid_allocator(struct adapter *sc)
4263 {
4264 	struct tid_info *t = &sc->tids;
4265 
4266 	if (t->natids == 0)
4267 		return;
4268 	mtx_lock(&t->atid_lock);
4269 	KASSERT(t->atids_in_use == 0,
4270 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4271 	t->atid_alloc_stopped = false;
4272 	mtx_unlock(&t->atid_lock);
4273 }
4274 
4275 int
4276 alloc_atid(struct adapter *sc, void *ctx)
4277 {
4278 	struct tid_info *t = &sc->tids;
4279 	int atid = -1;
4280 
4281 	mtx_lock(&t->atid_lock);
4282 	if (t->afree && !t->atid_alloc_stopped) {
4283 		union aopen_entry *p = t->afree;
4284 
4285 		atid = p - t->atid_tab;
4286 		MPASS(atid <= M_TID_TID);
4287 		t->afree = p->next;
4288 		p->data = ctx;
4289 		t->atids_in_use++;
4290 	}
4291 	mtx_unlock(&t->atid_lock);
4292 	return (atid);
4293 }
4294 
4295 void *
4296 lookup_atid(struct adapter *sc, int atid)
4297 {
4298 	struct tid_info *t = &sc->tids;
4299 
4300 	return (t->atid_tab[atid].data);
4301 }
4302 
4303 void
4304 free_atid(struct adapter *sc, int atid)
4305 {
4306 	struct tid_info *t = &sc->tids;
4307 	union aopen_entry *p = &t->atid_tab[atid];
4308 
4309 	mtx_lock(&t->atid_lock);
4310 	p->next = t->afree;
4311 	t->afree = p;
4312 	t->atids_in_use--;
4313 	mtx_unlock(&t->atid_lock);
4314 }
4315 
4316 static void
4317 queue_tid_release(struct adapter *sc, int tid)
4318 {
4319 
4320 	CXGBE_UNIMPLEMENTED("deferred tid release");
4321 }
4322 
4323 void
4324 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4325 {
4326 	struct wrqe *wr;
4327 	struct cpl_tid_release *req;
4328 
4329 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4330 	if (wr == NULL) {
4331 		queue_tid_release(sc, tid);	/* defer */
4332 		return;
4333 	}
4334 	req = wrtod(wr);
4335 
4336 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4337 
4338 	t4_wrq_tx(sc, wr);
4339 }
4340 
4341 static int
4342 t4_range_cmp(const void *a, const void *b)
4343 {
4344 	return ((const struct t4_range *)a)->start -
4345 	       ((const struct t4_range *)b)->start;
4346 }
4347 
4348 /*
4349  * Verify that the memory range specified by the addr/len pair is valid within
4350  * the card's address space.
4351  */
4352 static int
4353 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4354 {
4355 	struct t4_range mem_ranges[4], *r, *next;
4356 	uint32_t em, addr_len;
4357 	int i, n, remaining;
4358 
4359 	/* Memory can only be accessed in naturally aligned 4 byte units */
4360 	if (addr & 3 || len & 3 || len == 0)
4361 		return (EINVAL);
4362 
4363 	/* Enabled memories */
4364 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4365 
4366 	r = &mem_ranges[0];
4367 	n = 0;
4368 	bzero(r, sizeof(mem_ranges));
4369 	if (em & F_EDRAM0_ENABLE) {
4370 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4371 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4372 		if (r->size > 0) {
4373 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4374 			if (addr >= r->start &&
4375 			    addr + len <= r->start + r->size)
4376 				return (0);
4377 			r++;
4378 			n++;
4379 		}
4380 	}
4381 	if (em & F_EDRAM1_ENABLE) {
4382 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4383 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4384 		if (r->size > 0) {
4385 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4386 			if (addr >= r->start &&
4387 			    addr + len <= r->start + r->size)
4388 				return (0);
4389 			r++;
4390 			n++;
4391 		}
4392 	}
4393 	if (em & F_EXT_MEM_ENABLE) {
4394 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4395 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4396 		if (r->size > 0) {
4397 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4398 			if (addr >= r->start &&
4399 			    addr + len <= r->start + r->size)
4400 				return (0);
4401 			r++;
4402 			n++;
4403 		}
4404 	}
4405 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4406 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4407 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4408 		if (r->size > 0) {
4409 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4410 			if (addr >= r->start &&
4411 			    addr + len <= r->start + r->size)
4412 				return (0);
4413 			r++;
4414 			n++;
4415 		}
4416 	}
4417 	MPASS(n <= nitems(mem_ranges));
4418 
4419 	if (n > 1) {
4420 		/* Sort and merge the ranges. */
4421 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4422 
4423 		/* Start from index 0 and examine the next n - 1 entries. */
4424 		r = &mem_ranges[0];
4425 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4426 
4427 			MPASS(r->size > 0);	/* r is a valid entry. */
4428 			next = r + 1;
4429 			MPASS(next->size > 0);	/* and so is the next one. */
4430 
4431 			while (r->start + r->size >= next->start) {
4432 				/* Merge the next one into the current entry. */
4433 				r->size = max(r->start + r->size,
4434 				    next->start + next->size) - r->start;
4435 				n--;	/* One fewer entry in total. */
4436 				if (--remaining == 0)
4437 					goto done;	/* short circuit */
4438 				next++;
4439 			}
4440 			if (next != r + 1) {
4441 				/*
4442 				 * Some entries were merged into r and next
4443 				 * points to the first valid entry that couldn't
4444 				 * be merged.
4445 				 */
4446 				MPASS(next->size > 0);	/* must be valid */
4447 				memcpy(r + 1, next, remaining * sizeof(*r));
4448 #ifdef INVARIANTS
4449 				/*
4450 				 * This so that the foo->size assertion in the
4451 				 * next iteration of the loop do the right
4452 				 * thing for entries that were pulled up and are
4453 				 * no longer valid.
4454 				 */
4455 				MPASS(n < nitems(mem_ranges));
4456 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4457 				    sizeof(struct t4_range));
4458 #endif
4459 			}
4460 		}
4461 done:
4462 		/* Done merging the ranges. */
4463 		MPASS(n > 0);
4464 		r = &mem_ranges[0];
4465 		for (i = 0; i < n; i++, r++) {
4466 			if (addr >= r->start &&
4467 			    addr + len <= r->start + r->size)
4468 				return (0);
4469 		}
4470 	}
4471 
4472 	return (EFAULT);
4473 }
4474 
4475 static int
4476 fwmtype_to_hwmtype(int mtype)
4477 {
4478 
4479 	switch (mtype) {
4480 	case FW_MEMTYPE_EDC0:
4481 		return (MEM_EDC0);
4482 	case FW_MEMTYPE_EDC1:
4483 		return (MEM_EDC1);
4484 	case FW_MEMTYPE_EXTMEM:
4485 		return (MEM_MC0);
4486 	case FW_MEMTYPE_EXTMEM1:
4487 		return (MEM_MC1);
4488 	default:
4489 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4490 	}
4491 }
4492 
4493 /*
4494  * Verify that the memory range specified by the memtype/offset/len pair is
4495  * valid and lies entirely within the memtype specified.  The global address of
4496  * the start of the range is returned in addr.
4497  */
4498 static int
4499 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4500     uint32_t *addr)
4501 {
4502 	uint32_t em, addr_len, maddr;
4503 
4504 	/* Memory can only be accessed in naturally aligned 4 byte units */
4505 	if (off & 3 || len & 3 || len == 0)
4506 		return (EINVAL);
4507 
4508 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4509 	switch (fwmtype_to_hwmtype(mtype)) {
4510 	case MEM_EDC0:
4511 		if (!(em & F_EDRAM0_ENABLE))
4512 			return (EINVAL);
4513 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4514 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4515 		break;
4516 	case MEM_EDC1:
4517 		if (!(em & F_EDRAM1_ENABLE))
4518 			return (EINVAL);
4519 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4520 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4521 		break;
4522 	case MEM_MC:
4523 		if (!(em & F_EXT_MEM_ENABLE))
4524 			return (EINVAL);
4525 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4526 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4527 		break;
4528 	case MEM_MC1:
4529 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4530 			return (EINVAL);
4531 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4532 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4533 		break;
4534 	default:
4535 		return (EINVAL);
4536 	}
4537 
4538 	*addr = maddr + off;	/* global address */
4539 	return (validate_mem_range(sc, *addr, len));
4540 }
4541 
4542 static int
4543 fixup_devlog_params(struct adapter *sc)
4544 {
4545 	struct devlog_params *dparams = &sc->params.devlog;
4546 	int rc;
4547 
4548 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4549 	    dparams->size, &dparams->addr);
4550 
4551 	return (rc);
4552 }
4553 
4554 static void
4555 update_nirq(struct intrs_and_queues *iaq, int nports)
4556 {
4557 
4558 	iaq->nirq = T4_EXTRA_INTR;
4559 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4560 	iaq->nirq += nports * iaq->nofldrxq;
4561 	iaq->nirq += nports * (iaq->num_vis - 1) *
4562 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4563 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4564 }
4565 
4566 /*
4567  * Adjust requirements to fit the number of interrupts available.
4568  */
4569 static void
4570 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4571     int navail)
4572 {
4573 	int old_nirq;
4574 	const int nports = sc->params.nports;
4575 
4576 	MPASS(nports > 0);
4577 	MPASS(navail > 0);
4578 
4579 	bzero(iaq, sizeof(*iaq));
4580 	iaq->intr_type = itype;
4581 	iaq->num_vis = t4_num_vis;
4582 	iaq->ntxq = t4_ntxq;
4583 	iaq->ntxq_vi = t4_ntxq_vi;
4584 	iaq->nrxq = t4_nrxq;
4585 	iaq->nrxq_vi = t4_nrxq_vi;
4586 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4587 	if (is_offload(sc) || is_ethoffload(sc)) {
4588 		if (sc->params.tid_qid_sel_mask == 0) {
4589 			iaq->nofldtxq = t4_nofldtxq;
4590 			iaq->nofldtxq_vi = t4_nofldtxq_vi;
4591 		} else {
4592 			iaq->nofldtxq = roundup(t4_nofldtxq, sc->params.ncores);
4593 			iaq->nofldtxq_vi = roundup(t4_nofldtxq_vi,
4594 			    sc->params.ncores);
4595 			if (iaq->nofldtxq != t4_nofldtxq)
4596 				device_printf(sc->dev,
4597 				    "nofldtxq updated (%d -> %d) for correct"
4598 				    " operation with %d firmware cores.\n",
4599 				    t4_nofldtxq, iaq->nofldtxq,
4600 				    sc->params.ncores);
4601 			if (iaq->num_vis > 1 &&
4602 			    iaq->nofldtxq_vi != t4_nofldtxq_vi)
4603 				device_printf(sc->dev,
4604 				    "nofldtxq_vi updated (%d -> %d) for correct"
4605 				    " operation with %d firmware cores.\n",
4606 				    t4_nofldtxq_vi, iaq->nofldtxq_vi,
4607 				    sc->params.ncores);
4608 		}
4609 	}
4610 #endif
4611 #ifdef TCP_OFFLOAD
4612 	if (is_offload(sc)) {
4613 		iaq->nofldrxq = t4_nofldrxq;
4614 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4615 	}
4616 #endif
4617 #ifdef DEV_NETMAP
4618 	if (t4_native_netmap & NN_MAIN_VI) {
4619 		iaq->nnmtxq = t4_nnmtxq;
4620 		iaq->nnmrxq = t4_nnmrxq;
4621 	}
4622 	if (t4_native_netmap & NN_EXTRA_VI) {
4623 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4624 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4625 	}
4626 #endif
4627 
4628 	update_nirq(iaq, nports);
4629 	if (iaq->nirq <= navail &&
4630 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4631 		/*
4632 		 * This is the normal case -- there are enough interrupts for
4633 		 * everything.
4634 		 */
4635 		goto done;
4636 	}
4637 
4638 	/*
4639 	 * If extra VIs have been configured try reducing their count and see if
4640 	 * that works.
4641 	 */
4642 	while (iaq->num_vis > 1) {
4643 		iaq->num_vis--;
4644 		update_nirq(iaq, nports);
4645 		if (iaq->nirq <= navail &&
4646 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4647 			device_printf(sc->dev, "virtual interfaces per port "
4648 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4649 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4650 			    "itype %d, navail %u, nirq %d.\n",
4651 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4652 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4653 			    itype, navail, iaq->nirq);
4654 			goto done;
4655 		}
4656 	}
4657 
4658 	/*
4659 	 * Extra VIs will not be created.  Log a message if they were requested.
4660 	 */
4661 	MPASS(iaq->num_vis == 1);
4662 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4663 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4664 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4665 	if (iaq->num_vis != t4_num_vis) {
4666 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4667 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4668 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4669 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4670 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4671 	}
4672 
4673 	/*
4674 	 * Keep reducing the number of NIC rx queues to the next lower power of
4675 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4676 	 * if that works.
4677 	 */
4678 	do {
4679 		if (iaq->nrxq > 1) {
4680 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4681 			if (iaq->nnmrxq > iaq->nrxq)
4682 				iaq->nnmrxq = iaq->nrxq;
4683 		}
4684 		if (iaq->nofldrxq > 1)
4685 			iaq->nofldrxq >>= 1;
4686 
4687 		old_nirq = iaq->nirq;
4688 		update_nirq(iaq, nports);
4689 		if (iaq->nirq <= navail &&
4690 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4691 			device_printf(sc->dev, "running with reduced number of "
4692 			    "rx queues because of shortage of interrupts.  "
4693 			    "nrxq=%u, nofldrxq=%u.  "
4694 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4695 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4696 			goto done;
4697 		}
4698 	} while (old_nirq != iaq->nirq);
4699 
4700 	/* One interrupt for everything.  Ugh. */
4701 	device_printf(sc->dev, "running with minimal number of queues.  "
4702 	    "itype %d, navail %u.\n", itype, navail);
4703 	iaq->nirq = 1;
4704 	iaq->nrxq = 1;
4705 	iaq->ntxq = 1;
4706 	if (iaq->nofldrxq > 0) {
4707 		iaq->nofldrxq = 1;
4708 		iaq->nofldtxq = 1;
4709 		if (sc->params.tid_qid_sel_mask == 0)
4710 			iaq->nofldtxq = 1;
4711 		else
4712 			iaq->nofldtxq = sc->params.ncores;
4713 	}
4714 	iaq->nnmtxq = 0;
4715 	iaq->nnmrxq = 0;
4716 done:
4717 	MPASS(iaq->num_vis > 0);
4718 	if (iaq->num_vis > 1) {
4719 		MPASS(iaq->nrxq_vi > 0);
4720 		MPASS(iaq->ntxq_vi > 0);
4721 	}
4722 	MPASS(iaq->nirq > 0);
4723 	MPASS(iaq->nrxq > 0);
4724 	MPASS(iaq->ntxq > 0);
4725 	if (itype == INTR_MSI)
4726 		MPASS(powerof2(iaq->nirq));
4727 	if (sc->params.tid_qid_sel_mask != 0)
4728 		MPASS(iaq->nofldtxq % sc->params.ncores == 0);
4729 }
4730 
4731 static int
4732 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4733 {
4734 	int rc, itype, navail, nalloc;
4735 
4736 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4737 
4738 		if ((itype & t4_intr_types) == 0)
4739 			continue;	/* not allowed */
4740 
4741 		if (itype == INTR_MSIX)
4742 			navail = pci_msix_count(sc->dev);
4743 		else if (itype == INTR_MSI)
4744 			navail = pci_msi_count(sc->dev);
4745 		else
4746 			navail = 1;
4747 restart:
4748 		if (navail == 0)
4749 			continue;
4750 
4751 		calculate_iaq(sc, iaq, itype, navail);
4752 		nalloc = iaq->nirq;
4753 		rc = 0;
4754 		if (itype == INTR_MSIX)
4755 			rc = pci_alloc_msix(sc->dev, &nalloc);
4756 		else if (itype == INTR_MSI)
4757 			rc = pci_alloc_msi(sc->dev, &nalloc);
4758 
4759 		if (rc == 0 && nalloc > 0) {
4760 			if (nalloc == iaq->nirq)
4761 				return (0);
4762 
4763 			/*
4764 			 * Didn't get the number requested.  Use whatever number
4765 			 * the kernel is willing to allocate.
4766 			 */
4767 			device_printf(sc->dev, "fewer vectors than requested, "
4768 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4769 			    itype, iaq->nirq, nalloc);
4770 			pci_release_msi(sc->dev);
4771 			navail = nalloc;
4772 			goto restart;
4773 		}
4774 
4775 		device_printf(sc->dev,
4776 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4777 		    itype, rc, iaq->nirq, nalloc);
4778 	}
4779 
4780 	device_printf(sc->dev,
4781 	    "failed to find a usable interrupt type.  "
4782 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4783 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4784 
4785 	return (ENXIO);
4786 }
4787 
4788 #define FW_VERSION(chip) ( \
4789     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4790     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4791     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4792     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4793 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4794 
4795 /* Just enough of fw_hdr to cover all version info. */
4796 struct fw_h {
4797 	__u8	ver;
4798 	__u8	chip;
4799 	__be16	len512;
4800 	__be32	fw_ver;
4801 	__be32	tp_microcode_ver;
4802 	__u8	intfver_nic;
4803 	__u8	intfver_vnic;
4804 	__u8	intfver_ofld;
4805 	__u8	intfver_ri;
4806 	__u8	intfver_iscsipdu;
4807 	__u8	intfver_iscsi;
4808 	__u8	intfver_fcoepdu;
4809 	__u8	intfver_fcoe;
4810 };
4811 /* Spot check a couple of fields. */
4812 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4813 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4814 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4815 
4816 struct fw_info {
4817 	uint8_t chip;
4818 	char *kld_name;
4819 	char *fw_mod_name;
4820 	struct fw_h fw_h;
4821 } fw_info[] = {
4822 	{
4823 		.chip = CHELSIO_T4,
4824 		.kld_name = "t4fw_cfg",
4825 		.fw_mod_name = "t4fw",
4826 		.fw_h = {
4827 			.chip = FW_HDR_CHIP_T4,
4828 			.fw_ver = htobe32(FW_VERSION(T4)),
4829 			.intfver_nic = FW_INTFVER(T4, NIC),
4830 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4831 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4832 			.intfver_ri = FW_INTFVER(T4, RI),
4833 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4834 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4835 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4836 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4837 		},
4838 	}, {
4839 		.chip = CHELSIO_T5,
4840 		.kld_name = "t5fw_cfg",
4841 		.fw_mod_name = "t5fw",
4842 		.fw_h = {
4843 			.chip = FW_HDR_CHIP_T5,
4844 			.fw_ver = htobe32(FW_VERSION(T5)),
4845 			.intfver_nic = FW_INTFVER(T5, NIC),
4846 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4847 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4848 			.intfver_ri = FW_INTFVER(T5, RI),
4849 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4850 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4851 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4852 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4853 		},
4854 	}, {
4855 		.chip = CHELSIO_T6,
4856 		.kld_name = "t6fw_cfg",
4857 		.fw_mod_name = "t6fw",
4858 		.fw_h = {
4859 			.chip = FW_HDR_CHIP_T6,
4860 			.fw_ver = htobe32(FW_VERSION(T6)),
4861 			.intfver_nic = FW_INTFVER(T6, NIC),
4862 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4863 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4864 			.intfver_ri = FW_INTFVER(T6, RI),
4865 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4866 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4867 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4868 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4869 		},
4870 	}, {
4871 		.chip = CHELSIO_T7,
4872 		.kld_name = "t7fw_cfg",
4873 		.fw_mod_name = "t7fw",
4874 		.fw_h = {
4875 			.chip = FW_HDR_CHIP_T7,
4876 			.fw_ver = htobe32(FW_VERSION(T7)),
4877 			.intfver_nic = FW_INTFVER(T7, NIC),
4878 			.intfver_vnic = FW_INTFVER(T7, VNIC),
4879 			.intfver_ofld = FW_INTFVER(T7, OFLD),
4880 			.intfver_ri = FW_INTFVER(T7, RI),
4881 			.intfver_iscsipdu = FW_INTFVER(T7, ISCSIPDU),
4882 			.intfver_iscsi = FW_INTFVER(T7, ISCSI),
4883 			.intfver_fcoepdu = FW_INTFVER(T7, FCOEPDU),
4884 			.intfver_fcoe = FW_INTFVER(T7, FCOE),
4885 		},
4886 	}
4887 };
4888 
4889 static struct fw_info *
4890 find_fw_info(int chip)
4891 {
4892 	int i;
4893 
4894 	for (i = 0; i < nitems(fw_info); i++) {
4895 		if (fw_info[i].chip == chip)
4896 			return (&fw_info[i]);
4897 	}
4898 	return (NULL);
4899 }
4900 
4901 /*
4902  * Is the given firmware API compatible with the one the driver was compiled
4903  * with?
4904  */
4905 static int
4906 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4907 {
4908 
4909 	/* short circuit if it's the exact same firmware version */
4910 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4911 		return (1);
4912 
4913 	/*
4914 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4915 	 * features that are supported in the driver.
4916 	 */
4917 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4918 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4919 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4920 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4921 		return (1);
4922 #undef SAME_INTF
4923 
4924 	return (0);
4925 }
4926 
4927 static int
4928 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4929     const struct firmware **fw)
4930 {
4931 	struct fw_info *fw_info;
4932 
4933 	*dcfg = NULL;
4934 	if (fw != NULL)
4935 		*fw = NULL;
4936 
4937 	fw_info = find_fw_info(chip_id(sc));
4938 	if (fw_info == NULL) {
4939 		device_printf(sc->dev,
4940 		    "unable to look up firmware information for chip %d.\n",
4941 		    chip_id(sc));
4942 		return (EINVAL);
4943 	}
4944 
4945 	*dcfg = firmware_get(fw_info->kld_name);
4946 	if (*dcfg != NULL) {
4947 		if (fw != NULL)
4948 			*fw = firmware_get(fw_info->fw_mod_name);
4949 		return (0);
4950 	}
4951 
4952 	return (ENOENT);
4953 }
4954 
4955 static void
4956 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4957     const struct firmware *fw)
4958 {
4959 
4960 	if (fw != NULL)
4961 		firmware_put(fw, FIRMWARE_UNLOAD);
4962 	if (dcfg != NULL)
4963 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4964 }
4965 
4966 /*
4967  * Return values:
4968  * 0 means no firmware install attempted.
4969  * ERESTART means a firmware install was attempted and was successful.
4970  * +ve errno means a firmware install was attempted but failed.
4971  */
4972 static int
4973 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4974     const struct fw_h *drv_fw, const char *reason, int *already)
4975 {
4976 	const struct firmware *cfg, *fw;
4977 	const uint32_t c = be32toh(card_fw->fw_ver);
4978 	uint32_t d, k;
4979 	int rc, fw_install;
4980 	struct fw_h bundled_fw;
4981 	bool load_attempted;
4982 
4983 	cfg = fw = NULL;
4984 	load_attempted = false;
4985 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4986 
4987 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4988 	if (t4_fw_install < 0) {
4989 		rc = load_fw_module(sc, &cfg, &fw);
4990 		if (rc != 0 || fw == NULL) {
4991 			device_printf(sc->dev,
4992 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4993 			    " will use compiled-in firmware version for"
4994 			    "hw.cxgbe.fw_install checks.\n",
4995 			    rc, cfg, fw);
4996 		} else {
4997 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4998 		}
4999 		load_attempted = true;
5000 	}
5001 	d = be32toh(bundled_fw.fw_ver);
5002 
5003 	if (reason != NULL)
5004 		goto install;
5005 
5006 	if ((sc->flags & FW_OK) == 0) {
5007 
5008 		if (c == 0xffffffff) {
5009 			reason = "missing";
5010 			goto install;
5011 		}
5012 
5013 		rc = 0;
5014 		goto done;
5015 	}
5016 
5017 	if (!fw_compatible(card_fw, &bundled_fw)) {
5018 		reason = "incompatible or unusable";
5019 		goto install;
5020 	}
5021 
5022 	if (d > c) {
5023 		reason = "older than the version bundled with this driver";
5024 		goto install;
5025 	}
5026 
5027 	if (fw_install == 2 && d != c) {
5028 		reason = "different than the version bundled with this driver";
5029 		goto install;
5030 	}
5031 
5032 	/* No reason to do anything to the firmware already on the card. */
5033 	rc = 0;
5034 	goto done;
5035 
5036 install:
5037 	rc = 0;
5038 	if ((*already)++)
5039 		goto done;
5040 
5041 	if (fw_install == 0) {
5042 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5043 		    "but the driver is prohibited from installing a firmware "
5044 		    "on the card.\n",
5045 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5046 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5047 
5048 		goto done;
5049 	}
5050 
5051 	/*
5052 	 * We'll attempt to install a firmware.  Load the module first (if it
5053 	 * hasn't been loaded already).
5054 	 */
5055 	if (!load_attempted) {
5056 		rc = load_fw_module(sc, &cfg, &fw);
5057 		if (rc != 0 || fw == NULL) {
5058 			device_printf(sc->dev,
5059 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
5060 			    rc, cfg, fw);
5061 			/* carry on */
5062 		}
5063 	}
5064 	if (fw == NULL) {
5065 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5066 		    "but the driver cannot take corrective action because it "
5067 		    "is unable to load the firmware module.\n",
5068 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5069 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5070 		rc = sc->flags & FW_OK ? 0 : ENOENT;
5071 		goto done;
5072 	}
5073 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
5074 	if (k != d) {
5075 		MPASS(t4_fw_install > 0);
5076 		device_printf(sc->dev,
5077 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
5078 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
5079 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
5080 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
5081 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5082 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5083 		rc = sc->flags & FW_OK ? 0 : EINVAL;
5084 		goto done;
5085 	}
5086 
5087 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5088 	    "installing firmware %u.%u.%u.%u on card.\n",
5089 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5090 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
5091 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5092 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5093 
5094 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
5095 	if (rc != 0) {
5096 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
5097 	} else {
5098 		/* Installed successfully, update the cached header too. */
5099 		rc = ERESTART;
5100 		memcpy(card_fw, fw->data, sizeof(*card_fw));
5101 	}
5102 done:
5103 	unload_fw_module(sc, cfg, fw);
5104 
5105 	return (rc);
5106 }
5107 
5108 /*
5109  * Establish contact with the firmware and attempt to become the master driver.
5110  *
5111  * A firmware will be installed to the card if needed (if the driver is allowed
5112  * to do so).
5113  */
5114 static int
5115 contact_firmware(struct adapter *sc)
5116 {
5117 	int rc, already = 0;
5118 	enum dev_state state;
5119 	struct fw_info *fw_info;
5120 	struct fw_hdr *card_fw;		/* fw on the card */
5121 	const struct fw_h *drv_fw;
5122 
5123 	fw_info = find_fw_info(chip_id(sc));
5124 	if (fw_info == NULL) {
5125 		device_printf(sc->dev,
5126 		    "unable to look up firmware information for chip %d.\n",
5127 		    chip_id(sc));
5128 		return (EINVAL);
5129 	}
5130 	drv_fw = &fw_info->fw_h;
5131 
5132 	/* Read the header of the firmware on the card */
5133 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
5134 restart:
5135 	rc = -t4_get_fw_hdr(sc, card_fw);
5136 	if (rc != 0) {
5137 		device_printf(sc->dev,
5138 		    "unable to read firmware header from card's flash: %d\n",
5139 		    rc);
5140 		goto done;
5141 	}
5142 
5143 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
5144 	    &already);
5145 	if (rc == ERESTART)
5146 		goto restart;
5147 	if (rc != 0)
5148 		goto done;
5149 
5150 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
5151 	if (rc < 0 || state == DEV_STATE_ERR) {
5152 		rc = -rc;
5153 		device_printf(sc->dev,
5154 		    "failed to connect to the firmware: %d, %d.  "
5155 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5156 #if 0
5157 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5158 		    "not responding properly to HELLO", &already) == ERESTART)
5159 			goto restart;
5160 #endif
5161 		goto done;
5162 	}
5163 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
5164 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
5165 
5166 	if (rc == sc->pf) {
5167 		sc->flags |= MASTER_PF;
5168 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5169 		    NULL, &already);
5170 		if (rc == ERESTART)
5171 			rc = 0;
5172 		else if (rc != 0)
5173 			goto done;
5174 	} else if (state == DEV_STATE_UNINIT) {
5175 		/*
5176 		 * We didn't get to be the master so we definitely won't be
5177 		 * configuring the chip.  It's a bug if someone else hasn't
5178 		 * configured it already.
5179 		 */
5180 		device_printf(sc->dev, "couldn't be master(%d), "
5181 		    "device not already initialized either(%d).  "
5182 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5183 		rc = EPROTO;
5184 		goto done;
5185 	} else {
5186 		/*
5187 		 * Some other PF is the master and has configured the chip.
5188 		 * This is allowed but untested.
5189 		 */
5190 		device_printf(sc->dev, "PF%d is master, device state %d.  "
5191 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5192 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
5193 		sc->cfcsum = 0;
5194 		rc = 0;
5195 	}
5196 done:
5197 	if (rc != 0 && sc->flags & FW_OK) {
5198 		t4_fw_bye(sc, sc->mbox);
5199 		sc->flags &= ~FW_OK;
5200 	}
5201 	free(card_fw, M_CXGBE);
5202 	return (rc);
5203 }
5204 
5205 static int
5206 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
5207     uint32_t mtype, uint32_t moff, u_int maxlen)
5208 {
5209 	struct fw_info *fw_info;
5210 	const struct firmware *dcfg, *rcfg = NULL;
5211 	const uint32_t *cfdata;
5212 	uint32_t cflen, addr;
5213 	int rc;
5214 
5215 	load_fw_module(sc, &dcfg, NULL);
5216 
5217 	/* Card specific interpretation of "default". */
5218 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5219 		if (pci_get_device(sc->dev) == 0x440a)
5220 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
5221 		if (is_fpga(sc))
5222 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
5223 	}
5224 
5225 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5226 		if (dcfg == NULL) {
5227 			device_printf(sc->dev,
5228 			    "KLD with default config is not available.\n");
5229 			rc = ENOENT;
5230 			goto done;
5231 		}
5232 		cfdata = dcfg->data;
5233 		cflen = dcfg->datasize & ~3;
5234 	} else {
5235 		char s[32];
5236 
5237 		fw_info = find_fw_info(chip_id(sc));
5238 		if (fw_info == NULL) {
5239 			device_printf(sc->dev,
5240 			    "unable to look up firmware information for chip %d.\n",
5241 			    chip_id(sc));
5242 			rc = EINVAL;
5243 			goto done;
5244 		}
5245 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
5246 
5247 		rcfg = firmware_get(s);
5248 		if (rcfg == NULL) {
5249 			device_printf(sc->dev,
5250 			    "unable to load module \"%s\" for configuration "
5251 			    "profile \"%s\".\n", s, cfg_file);
5252 			rc = ENOENT;
5253 			goto done;
5254 		}
5255 		cfdata = rcfg->data;
5256 		cflen = rcfg->datasize & ~3;
5257 	}
5258 
5259 	if (cflen > maxlen) {
5260 		device_printf(sc->dev,
5261 		    "config file too long (%d, max allowed is %d).\n",
5262 		    cflen, maxlen);
5263 		rc = EINVAL;
5264 		goto done;
5265 	}
5266 
5267 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
5268 	if (rc != 0) {
5269 		device_printf(sc->dev,
5270 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
5271 		    __func__, mtype, moff, cflen, rc);
5272 		rc = EINVAL;
5273 		goto done;
5274 	}
5275 	write_via_memwin(sc, 2, addr, cfdata, cflen);
5276 done:
5277 	if (rcfg != NULL)
5278 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5279 	unload_fw_module(sc, dcfg, NULL);
5280 	return (rc);
5281 }
5282 
5283 struct caps_allowed {
5284 	uint16_t nbmcaps;
5285 	uint16_t linkcaps;
5286 	uint16_t switchcaps;
5287 	uint16_t nvmecaps;
5288 	uint16_t niccaps;
5289 	uint16_t toecaps;
5290 	uint16_t rdmacaps;
5291 	uint16_t cryptocaps;
5292 	uint16_t iscsicaps;
5293 	uint16_t fcoecaps;
5294 };
5295 
5296 #define FW_PARAM_DEV(param) \
5297 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5298 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5299 #define FW_PARAM_PFVF(param) \
5300 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5301 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5302 
5303 /*
5304  * Provide a configuration profile to the firmware and have it initialize the
5305  * chip accordingly.  This may involve uploading a configuration file to the
5306  * card.
5307  */
5308 static int
5309 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5310     const struct caps_allowed *caps_allowed)
5311 {
5312 	int rc;
5313 	struct fw_caps_config_cmd caps;
5314 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5315 	unsigned int maxlen = 0;
5316 	const int cfg_addr = t4_flash_cfg_addr(sc, &maxlen);
5317 
5318 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5319 	if (rc != 0) {
5320 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5321 		return (rc);
5322 	}
5323 
5324 	bzero(&caps, sizeof(caps));
5325 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5326 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5327 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5328 		mtype = 0;
5329 		moff = 0;
5330 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5331 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5332 		mtype = FW_MEMTYPE_FLASH;
5333 		moff = cfg_addr;
5334 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5335 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5336 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5337 		    FW_LEN16(caps));
5338 	} else {
5339 		/*
5340 		 * Ask the firmware where it wants us to upload the config file.
5341 		 */
5342 		param = FW_PARAM_DEV(CF);
5343 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5344 		if (rc != 0) {
5345 			/* No support for config file?  Shouldn't happen. */
5346 			device_printf(sc->dev,
5347 			    "failed to query config file location: %d.\n", rc);
5348 			goto done;
5349 		}
5350 		mtype = G_FW_PARAMS_PARAM_Y(val);
5351 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5352 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5353 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5354 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5355 		    FW_LEN16(caps));
5356 
5357 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff, maxlen);
5358 		if (rc != 0) {
5359 			device_printf(sc->dev,
5360 			    "failed to upload config file to card: %d.\n", rc);
5361 			goto done;
5362 		}
5363 	}
5364 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5365 	if (rc != 0) {
5366 		device_printf(sc->dev, "failed to pre-process config file: %d "
5367 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5368 		goto done;
5369 	}
5370 
5371 	finicsum = be32toh(caps.finicsum);
5372 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5373 	if (finicsum != cfcsum) {
5374 		device_printf(sc->dev,
5375 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5376 		    finicsum, cfcsum);
5377 	}
5378 	sc->cfcsum = cfcsum;
5379 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5380 
5381 	/*
5382 	 * Let the firmware know what features will (not) be used so it can tune
5383 	 * things accordingly.
5384 	 */
5385 #define LIMIT_CAPS(x) do { \
5386 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5387 } while (0)
5388 	LIMIT_CAPS(nbm);
5389 	LIMIT_CAPS(link);
5390 	LIMIT_CAPS(switch);
5391 	LIMIT_CAPS(nvme);
5392 	LIMIT_CAPS(nic);
5393 	LIMIT_CAPS(toe);
5394 	LIMIT_CAPS(rdma);
5395 	LIMIT_CAPS(crypto);
5396 	LIMIT_CAPS(iscsi);
5397 	LIMIT_CAPS(fcoe);
5398 #undef LIMIT_CAPS
5399 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5400 		/*
5401 		 * TOE and hashfilters are mutually exclusive.  It is a config
5402 		 * file or firmware bug if both are reported as available.  Try
5403 		 * to cope with the situation in non-debug builds by disabling
5404 		 * TOE.
5405 		 */
5406 		MPASS(caps.toecaps == 0);
5407 
5408 		caps.toecaps = 0;
5409 		caps.rdmacaps = 0;
5410 		caps.iscsicaps = 0;
5411 	}
5412 
5413 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5414 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5415 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5416 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5417 	if (rc != 0) {
5418 		device_printf(sc->dev,
5419 		    "failed to process config file: %d.\n", rc);
5420 		goto done;
5421 	}
5422 
5423 	t4_tweak_chip_settings(sc);
5424 	set_params__pre_init(sc);
5425 
5426 	/* get basic stuff going */
5427 	rc = -t4_fw_initialize(sc, sc->mbox);
5428 	if (rc != 0) {
5429 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5430 		goto done;
5431 	}
5432 done:
5433 	return (rc);
5434 }
5435 
5436 /*
5437  * Partition chip resources for use between various PFs, VFs, etc.
5438  */
5439 static int
5440 partition_resources(struct adapter *sc)
5441 {
5442 	char cfg_file[sizeof(t4_cfg_file)];
5443 	struct caps_allowed caps_allowed;
5444 	int rc;
5445 	bool fallback;
5446 
5447 	/* Only the master driver gets to configure the chip resources. */
5448 	MPASS(sc->flags & MASTER_PF);
5449 
5450 #define COPY_CAPS(x) do { \
5451 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5452 } while (0)
5453 	bzero(&caps_allowed, sizeof(caps_allowed));
5454 	COPY_CAPS(nbm);
5455 	COPY_CAPS(link);
5456 	COPY_CAPS(switch);
5457 	COPY_CAPS(nvme);
5458 	COPY_CAPS(nic);
5459 	COPY_CAPS(toe);
5460 	COPY_CAPS(rdma);
5461 	COPY_CAPS(crypto);
5462 	COPY_CAPS(iscsi);
5463 	COPY_CAPS(fcoe);
5464 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5465 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5466 retry:
5467 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5468 	if (rc != 0 && fallback) {
5469 		dump_devlog(sc);
5470 		device_printf(sc->dev,
5471 		    "failed (%d) to configure card with \"%s\" profile, "
5472 		    "will fall back to a basic configuration and retry.\n",
5473 		    rc, cfg_file);
5474 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5475 		bzero(&caps_allowed, sizeof(caps_allowed));
5476 		COPY_CAPS(switch);
5477 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5478 		fallback = false;
5479 		goto retry;
5480 	}
5481 #undef COPY_CAPS
5482 	return (rc);
5483 }
5484 
5485 /*
5486  * Retrieve parameters that are needed (or nice to have) very early.
5487  */
5488 static int
5489 get_params__pre_init(struct adapter *sc)
5490 {
5491 	int rc;
5492 	uint32_t param[2], val[2];
5493 
5494 	t4_get_version_info(sc);
5495 
5496 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5497 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5498 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5499 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5500 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5501 
5502 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5503 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5504 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5505 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5506 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5507 
5508 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5509 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5510 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5511 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5512 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5513 
5514 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5515 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5516 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5517 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5518 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5519 
5520 	param[0] = FW_PARAM_DEV(PORTVEC);
5521 	param[1] = FW_PARAM_DEV(CCLK);
5522 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5523 	if (rc != 0) {
5524 		device_printf(sc->dev,
5525 		    "failed to query parameters (pre_init): %d.\n", rc);
5526 		return (rc);
5527 	}
5528 
5529 	sc->params.portvec = val[0];
5530 	sc->params.nports = bitcount32(val[0]);
5531 	sc->params.vpd.cclk = val[1];
5532 
5533 	/* Read device log parameters. */
5534 	rc = -t4_init_devlog_ncores_params(sc, 1);
5535 	if (rc == 0)
5536 		fixup_devlog_params(sc);
5537 	else {
5538 		device_printf(sc->dev,
5539 		    "failed to get devlog parameters: %d.\n", rc);
5540 		rc = 0;	/* devlog isn't critical for device operation */
5541 	}
5542 
5543 	return (rc);
5544 }
5545 
5546 /*
5547  * Any params that need to be set before FW_INITIALIZE.
5548  */
5549 static int
5550 set_params__pre_init(struct adapter *sc)
5551 {
5552 	int rc = 0;
5553 	uint32_t param, val;
5554 
5555 	if (chip_id(sc) >= CHELSIO_T6) {
5556 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5557 		val = 1;
5558 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5559 		/* firmwares < 1.20.1.0 do not have this param. */
5560 		if (rc == FW_EINVAL &&
5561 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5562 			rc = 0;
5563 		}
5564 		if (rc != 0) {
5565 			device_printf(sc->dev,
5566 			    "failed to enable high priority filters :%d.\n",
5567 			    rc);
5568 		}
5569 
5570 		param = FW_PARAM_DEV(PPOD_EDRAM);
5571 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5572 		if (rc == 0 && val == 1) {
5573 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5574 			    &val);
5575 			if (rc != 0) {
5576 				device_printf(sc->dev,
5577 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5578 			}
5579 		}
5580 	}
5581 
5582 	/* Enable opaque VIIDs with firmwares that support it. */
5583 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5584 	val = 1;
5585 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5586 	if (rc == 0 && val == 1)
5587 		sc->params.viid_smt_extn_support = true;
5588 	else
5589 		sc->params.viid_smt_extn_support = false;
5590 
5591 	return (rc);
5592 }
5593 
5594 /*
5595  * Retrieve various parameters that are of interest to the driver.  The device
5596  * has been initialized by the firmware at this point.
5597  */
5598 static int
5599 get_params__post_init(struct adapter *sc)
5600 {
5601 	int rc;
5602 	uint32_t param[7], val[7];
5603 	struct fw_caps_config_cmd caps;
5604 
5605 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5606 	param[1] = FW_PARAM_PFVF(EQ_START);
5607 	param[2] = FW_PARAM_PFVF(FILTER_START);
5608 	param[3] = FW_PARAM_PFVF(FILTER_END);
5609 	param[4] = FW_PARAM_PFVF(L2T_START);
5610 	param[5] = FW_PARAM_PFVF(L2T_END);
5611 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5612 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5613 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5614 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5615 	if (rc != 0) {
5616 		device_printf(sc->dev,
5617 		    "failed to query parameters (post_init): %d.\n", rc);
5618 		return (rc);
5619 	}
5620 
5621 	sc->sge.iq_start = val[0];
5622 	sc->sge.eq_start = val[1];
5623 	if ((int)val[3] > (int)val[2]) {
5624 		sc->tids.ftid_base = val[2];
5625 		sc->tids.ftid_end = val[3];
5626 		sc->tids.nftids = val[3] - val[2] + 1;
5627 	}
5628 	sc->vres.l2t.start = val[4];
5629 	sc->vres.l2t.size = val[5] - val[4] + 1;
5630 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5631 	if (sc->vres.l2t.size > 0)
5632 		MPASS(fls(val[5]) <= S_SYNC_WR);
5633 	sc->params.core_vdd = val[6];
5634 
5635 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5636 	param[1] = FW_PARAM_PFVF(EQ_END);
5637 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5638 	if (rc != 0) {
5639 		device_printf(sc->dev,
5640 		    "failed to query parameters (post_init2): %d.\n", rc);
5641 		return (rc);
5642 	}
5643 	MPASS((int)val[0] >= sc->sge.iq_start);
5644 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5645 	MPASS((int)val[1] >= sc->sge.eq_start);
5646 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5647 
5648 	if (chip_id(sc) >= CHELSIO_T6) {
5649 
5650 		sc->tids.tid_base = t4_read_reg(sc,
5651 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5652 
5653 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5654 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5655 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5656 		if (rc != 0) {
5657 			device_printf(sc->dev,
5658 			   "failed to query hpfilter parameters: %d.\n", rc);
5659 			return (rc);
5660 		}
5661 		if ((int)val[1] > (int)val[0]) {
5662 			sc->tids.hpftid_base = val[0];
5663 			sc->tids.hpftid_end = val[1];
5664 			sc->tids.nhpftids = val[1] - val[0] + 1;
5665 
5666 			/*
5667 			 * These should go off if the layout changes and the
5668 			 * driver needs to catch up.
5669 			 */
5670 			MPASS(sc->tids.hpftid_base == 0);
5671 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5672 		}
5673 
5674 		param[0] = FW_PARAM_PFVF(RAWF_START);
5675 		param[1] = FW_PARAM_PFVF(RAWF_END);
5676 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5677 		if (rc != 0) {
5678 			device_printf(sc->dev,
5679 			   "failed to query rawf parameters: %d.\n", rc);
5680 			return (rc);
5681 		}
5682 		if ((int)val[1] > (int)val[0]) {
5683 			sc->rawf_base = val[0];
5684 			sc->nrawf = val[1] - val[0] + 1;
5685 		}
5686 	}
5687 
5688 	if (sc->params.ncores > 1) {
5689 		MPASS(chip_id(sc) >= CHELSIO_T7);
5690 
5691 		param[0] = FW_PARAM_DEV(TID_QID_SEL_MASK);
5692 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5693 		sc->params.tid_qid_sel_mask = rc == 0 ? val[0] : 0;
5694 	}
5695 
5696 	/*
5697 	 * The parameters that follow may not be available on all firmwares.  We
5698 	 * query them individually rather than in a compound query because old
5699 	 * firmwares fail the entire query if an unknown parameter is queried.
5700 	 */
5701 
5702 	/*
5703 	 * MPS buffer group configuration.
5704 	 */
5705 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5706 	val[0] = 0;
5707 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5708 	if (rc == 0)
5709 		sc->params.mps_bg_map = val[0];
5710 	else
5711 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5712 
5713 	param[0] = FW_PARAM_DEV(TPCHMAP);
5714 	val[0] = 0;
5715 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5716 	if (rc == 0)
5717 		sc->params.tp_ch_map = val[0];
5718 	else
5719 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5720 
5721 	param[0] = FW_PARAM_DEV(TX_TPCHMAP);
5722 	val[0] = 0;
5723 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5724 	if (rc == 0)
5725 		sc->params.tx_tp_ch_map = val[0];
5726 	else
5727 		sc->params.tx_tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5728 
5729 	/*
5730 	 * Determine whether the firmware supports the filter2 work request.
5731 	 */
5732 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5733 	val[0] = 0;
5734 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5735 	if (rc == 0)
5736 		sc->params.filter2_wr_support = val[0] != 0;
5737 	else
5738 		sc->params.filter2_wr_support = 0;
5739 
5740 	/*
5741 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5742 	 */
5743 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5744 	val[0] = 0;
5745 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5746 	if (rc == 0)
5747 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5748 	else
5749 		sc->params.ulptx_memwrite_dsgl = false;
5750 
5751 	/* FW_RI_FR_NSMR_TPTE_WR support */
5752 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5753 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5754 	if (rc == 0)
5755 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5756 	else
5757 		sc->params.fr_nsmr_tpte_wr_support = false;
5758 
5759 	/* Support for 512 SGL entries per FR MR. */
5760 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5761 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5762 	if (rc == 0)
5763 		sc->params.dev_512sgl_mr = val[0] != 0;
5764 	else
5765 		sc->params.dev_512sgl_mr = false;
5766 
5767 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5768 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5769 	if (rc == 0)
5770 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5771 	else
5772 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5773 
5774 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5775 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5776 	if (rc == 0) {
5777 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5778 		sc->params.nsched_cls = val[0];
5779 	} else
5780 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5781 
5782 	/* get capabilites */
5783 	bzero(&caps, sizeof(caps));
5784 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5785 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5786 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5787 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5788 	if (rc != 0) {
5789 		device_printf(sc->dev,
5790 		    "failed to get card capabilities: %d.\n", rc);
5791 		return (rc);
5792 	}
5793 
5794 #define READ_CAPS(x) do { \
5795 	sc->x = htobe16(caps.x); \
5796 } while (0)
5797 	READ_CAPS(nbmcaps);
5798 	READ_CAPS(linkcaps);
5799 	READ_CAPS(switchcaps);
5800 	READ_CAPS(nvmecaps);
5801 	READ_CAPS(niccaps);
5802 	READ_CAPS(toecaps);
5803 	READ_CAPS(rdmacaps);
5804 	READ_CAPS(cryptocaps);
5805 	READ_CAPS(iscsicaps);
5806 	READ_CAPS(fcoecaps);
5807 
5808 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5809 		MPASS(chip_id(sc) > CHELSIO_T4);
5810 		MPASS(sc->toecaps == 0);
5811 		sc->toecaps = 0;
5812 
5813 		param[0] = FW_PARAM_DEV(NTID);
5814 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5815 		if (rc != 0) {
5816 			device_printf(sc->dev,
5817 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5818 			return (rc);
5819 		}
5820 		sc->tids.ntids = val[0];
5821 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5822 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5823 			sc->tids.ntids -= sc->tids.nhpftids;
5824 		}
5825 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5826 		sc->params.hash_filter = 1;
5827 	}
5828 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5829 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5830 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5831 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5832 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5833 		if (rc != 0) {
5834 			device_printf(sc->dev,
5835 			    "failed to query NIC parameters: %d.\n", rc);
5836 			return (rc);
5837 		}
5838 		if ((int)val[1] > (int)val[0]) {
5839 			sc->tids.etid_base = val[0];
5840 			sc->tids.etid_end = val[1];
5841 			sc->tids.netids = val[1] - val[0] + 1;
5842 			sc->params.eo_wr_cred = val[2];
5843 			sc->params.ethoffload = 1;
5844 		}
5845 	}
5846 	if (sc->toecaps) {
5847 		/* query offload-related parameters */
5848 		param[0] = FW_PARAM_DEV(NTID);
5849 		param[1] = FW_PARAM_PFVF(SERVER_START);
5850 		param[2] = FW_PARAM_PFVF(SERVER_END);
5851 		param[3] = FW_PARAM_PFVF(TDDP_START);
5852 		param[4] = FW_PARAM_PFVF(TDDP_END);
5853 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5854 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5855 		if (rc != 0) {
5856 			device_printf(sc->dev,
5857 			    "failed to query TOE parameters: %d.\n", rc);
5858 			return (rc);
5859 		}
5860 		sc->tids.ntids = val[0];
5861 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5862 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5863 			sc->tids.ntids -= sc->tids.nhpftids;
5864 		}
5865 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5866 		if ((int)val[2] > (int)val[1]) {
5867 			sc->tids.stid_base = val[1];
5868 			sc->tids.nstids = val[2] - val[1] + 1;
5869 		}
5870 		sc->vres.ddp.start = val[3];
5871 		sc->vres.ddp.size = val[4] - val[3] + 1;
5872 		sc->params.ofldq_wr_cred = val[5];
5873 		sc->params.offload = 1;
5874 	} else {
5875 		/*
5876 		 * The firmware attempts memfree TOE configuration for -SO cards
5877 		 * and will report toecaps=0 if it runs out of resources (this
5878 		 * depends on the config file).  It may not report 0 for other
5879 		 * capabilities dependent on the TOE in this case.  Set them to
5880 		 * 0 here so that the driver doesn't bother tracking resources
5881 		 * that will never be used.
5882 		 */
5883 		sc->iscsicaps = 0;
5884 		sc->rdmacaps = 0;
5885 	}
5886 	if (sc->rdmacaps) {
5887 		param[0] = FW_PARAM_PFVF(STAG_START);
5888 		param[1] = FW_PARAM_PFVF(STAG_END);
5889 		param[2] = FW_PARAM_PFVF(RQ_START);
5890 		param[3] = FW_PARAM_PFVF(RQ_END);
5891 		param[4] = FW_PARAM_PFVF(PBL_START);
5892 		param[5] = FW_PARAM_PFVF(PBL_END);
5893 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5894 		if (rc != 0) {
5895 			device_printf(sc->dev,
5896 			    "failed to query RDMA parameters(1): %d.\n", rc);
5897 			return (rc);
5898 		}
5899 		sc->vres.stag.start = val[0];
5900 		sc->vres.stag.size = val[1] - val[0] + 1;
5901 		sc->vres.rq.start = val[2];
5902 		sc->vres.rq.size = val[3] - val[2] + 1;
5903 		sc->vres.pbl.start = val[4];
5904 		sc->vres.pbl.size = val[5] - val[4] + 1;
5905 
5906 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5907 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5908 		param[2] = FW_PARAM_PFVF(CQ_START);
5909 		param[3] = FW_PARAM_PFVF(CQ_END);
5910 		param[4] = FW_PARAM_PFVF(OCQ_START);
5911 		param[5] = FW_PARAM_PFVF(OCQ_END);
5912 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5913 		if (rc != 0) {
5914 			device_printf(sc->dev,
5915 			    "failed to query RDMA parameters(2): %d.\n", rc);
5916 			return (rc);
5917 		}
5918 		sc->vres.qp.start = val[0];
5919 		sc->vres.qp.size = val[1] - val[0] + 1;
5920 		sc->vres.cq.start = val[2];
5921 		sc->vres.cq.size = val[3] - val[2] + 1;
5922 		sc->vres.ocq.start = val[4];
5923 		sc->vres.ocq.size = val[5] - val[4] + 1;
5924 
5925 		param[0] = FW_PARAM_PFVF(SRQ_START);
5926 		param[1] = FW_PARAM_PFVF(SRQ_END);
5927 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5928 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5929 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5930 		if (rc != 0) {
5931 			device_printf(sc->dev,
5932 			    "failed to query RDMA parameters(3): %d.\n", rc);
5933 			return (rc);
5934 		}
5935 		sc->vres.srq.start = val[0];
5936 		sc->vres.srq.size = val[1] - val[0] + 1;
5937 		sc->params.max_ordird_qp = val[2];
5938 		sc->params.max_ird_adapter = val[3];
5939 	}
5940 	if (sc->iscsicaps) {
5941 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5942 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5943 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5944 		if (rc != 0) {
5945 			device_printf(sc->dev,
5946 			    "failed to query iSCSI parameters: %d.\n", rc);
5947 			return (rc);
5948 		}
5949 		sc->vres.iscsi.start = val[0];
5950 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5951 	}
5952 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5953 		param[0] = FW_PARAM_PFVF(TLS_START);
5954 		param[1] = FW_PARAM_PFVF(TLS_END);
5955 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5956 		if (rc != 0) {
5957 			device_printf(sc->dev,
5958 			    "failed to query TLS parameters: %d.\n", rc);
5959 			return (rc);
5960 		}
5961 		sc->vres.key.start = val[0];
5962 		sc->vres.key.size = val[1] - val[0] + 1;
5963 	}
5964 
5965 	/*
5966 	 * We've got the params we wanted to query directly from the firmware.
5967 	 * Grab some others via other means.
5968 	 */
5969 	t4_init_sge_params(sc);
5970 	t4_init_tp_params(sc);
5971 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5972 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5973 
5974 	rc = t4_verify_chip_settings(sc);
5975 	if (rc != 0)
5976 		return (rc);
5977 	t4_init_rx_buf_info(sc);
5978 
5979 	return (rc);
5980 }
5981 
5982 #ifdef KERN_TLS
5983 static void
5984 ktls_tick(void *arg)
5985 {
5986 	struct adapter *sc;
5987 	uint32_t tstamp;
5988 
5989 	sc = arg;
5990 	tstamp = tcp_ts_getticks();
5991 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5992 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5993 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5994 }
5995 
5996 static int
5997 t6_config_kern_tls(struct adapter *sc, bool enable)
5998 {
5999 	int rc;
6000 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6001 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
6002 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
6003 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
6004 
6005 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
6006 	if (rc != 0) {
6007 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
6008 		    enable ?  "enable" : "disable", rc);
6009 		return (rc);
6010 	}
6011 
6012 	if (enable) {
6013 		sc->flags |= KERN_TLS_ON;
6014 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6015 		    C_HARDCLOCK);
6016 	} else {
6017 		sc->flags &= ~KERN_TLS_ON;
6018 		callout_stop(&sc->ktls_tick);
6019 	}
6020 
6021 	return (rc);
6022 }
6023 #endif
6024 
6025 static int
6026 set_params__post_init(struct adapter *sc)
6027 {
6028 	uint32_t mask, param, val;
6029 #ifdef TCP_OFFLOAD
6030 	int i, v, shift;
6031 #endif
6032 
6033 	/* ask for encapsulated CPLs */
6034 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
6035 	val = 1;
6036 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6037 
6038 	/* Enable 32b port caps if the firmware supports it. */
6039 	param = FW_PARAM_PFVF(PORT_CAPS32);
6040 	val = 1;
6041 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
6042 		sc->params.port_caps32 = 1;
6043 
6044 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
6045 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
6046 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
6047 	    V_MASKFILTER(val - 1));
6048 
6049 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
6050 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
6051 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6052 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
6053 	val = 0;
6054 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
6055 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
6056 		    F_ATTACKFILTERENABLE);
6057 		val |= F_DROPERRORATTACK;
6058 	}
6059 	if (t4_drop_ip_fragments != 0) {
6060 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
6061 		    F_FRAGMENTDROP);
6062 		val |= F_DROPERRORFRAG;
6063 	}
6064 	if (t4_drop_pkts_with_l2_errors != 0)
6065 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
6066 	if (t4_drop_pkts_with_l3_errors != 0) {
6067 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
6068 		    F_DROPERRORCSUMIP;
6069 	}
6070 	if (t4_drop_pkts_with_l4_errors != 0) {
6071 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6072 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
6073 	}
6074 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
6075 
6076 #ifdef TCP_OFFLOAD
6077 	/*
6078 	 * Override the TOE timers with user provided tunables.  This is not the
6079 	 * recommended way to change the timers (the firmware config file is) so
6080 	 * these tunables are not documented.
6081 	 *
6082 	 * All the timer tunables are in microseconds.
6083 	 */
6084 	if (t4_toe_keepalive_idle != 0) {
6085 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
6086 		v &= M_KEEPALIVEIDLE;
6087 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
6088 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
6089 	}
6090 	if (t4_toe_keepalive_interval != 0) {
6091 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
6092 		v &= M_KEEPALIVEINTVL;
6093 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
6094 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
6095 	}
6096 	if (t4_toe_keepalive_count != 0) {
6097 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
6098 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6099 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
6100 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
6101 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
6102 	}
6103 	if (t4_toe_rexmt_min != 0) {
6104 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
6105 		v &= M_RXTMIN;
6106 		t4_set_reg_field(sc, A_TP_RXT_MIN,
6107 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
6108 	}
6109 	if (t4_toe_rexmt_max != 0) {
6110 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
6111 		v &= M_RXTMAX;
6112 		t4_set_reg_field(sc, A_TP_RXT_MAX,
6113 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
6114 	}
6115 	if (t4_toe_rexmt_count != 0) {
6116 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
6117 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6118 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
6119 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
6120 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
6121 	}
6122 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
6123 		if (t4_toe_rexmt_backoff[i] != -1) {
6124 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
6125 			shift = (i & 3) << 3;
6126 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
6127 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
6128 		}
6129 	}
6130 #endif
6131 
6132 	/*
6133 	 * Limit TOE connections to 2 reassembly "islands".  This is
6134 	 * required to permit migrating TOE connections to either
6135 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
6136 	 */
6137 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
6138 	    V_PASSMODE(2));
6139 
6140 #ifdef KERN_TLS
6141 	if (is_ktls(sc)) {
6142 		sc->tlst.inline_keys = t4_tls_inline_keys;
6143 		if (t4_kern_tls != 0 && is_t6(sc)) {
6144 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
6145 			t6_config_kern_tls(sc, true);
6146 		} else {
6147 			sc->tlst.short_records = t4_tls_short_records;
6148 			sc->tlst.partial_ghash = t4_tls_partial_ghash;
6149 		}
6150 	}
6151 #endif
6152 	return (0);
6153 }
6154 
6155 #undef FW_PARAM_PFVF
6156 #undef FW_PARAM_DEV
6157 
6158 static void
6159 t4_set_desc(struct adapter *sc)
6160 {
6161 	struct adapter_params *p = &sc->params;
6162 
6163 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
6164 }
6165 
6166 static inline void
6167 ifmedia_add4(struct ifmedia *ifm, int m)
6168 {
6169 
6170 	ifmedia_add(ifm, m, 0, NULL);
6171 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
6172 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
6173 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
6174 }
6175 
6176 /*
6177  * This is the selected media, which is not quite the same as the active media.
6178  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
6179  * and active are not the same, and "media: Ethernet selected" otherwise.
6180  */
6181 static void
6182 set_current_media(struct port_info *pi)
6183 {
6184 	struct link_config *lc;
6185 	struct ifmedia *ifm;
6186 	int mword;
6187 	u_int speed;
6188 
6189 	PORT_LOCK_ASSERT_OWNED(pi);
6190 
6191 	/* Leave current media alone if it's already set to IFM_NONE. */
6192 	ifm = &pi->media;
6193 	if (ifm->ifm_cur != NULL &&
6194 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
6195 		return;
6196 
6197 	lc = &pi->link_cfg;
6198 	if (lc->requested_aneg != AUTONEG_DISABLE &&
6199 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
6200 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
6201 		return;
6202 	}
6203 	mword = IFM_ETHER | IFM_FDX;
6204 	if (lc->requested_fc & PAUSE_TX)
6205 		mword |= IFM_ETH_TXPAUSE;
6206 	if (lc->requested_fc & PAUSE_RX)
6207 		mword |= IFM_ETH_RXPAUSE;
6208 	if (lc->requested_speed == 0)
6209 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
6210 	else
6211 		speed = lc->requested_speed;
6212 	mword |= port_mword(pi, speed_to_fwcap(speed));
6213 	ifmedia_set(ifm, mword);
6214 }
6215 
6216 /*
6217  * Returns true if the ifmedia list for the port cannot change.
6218  */
6219 static bool
6220 fixed_ifmedia(struct port_info *pi)
6221 {
6222 
6223 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
6224 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
6225 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
6226 	    pi->port_type == FW_PORT_TYPE_KX4 ||
6227 	    pi->port_type == FW_PORT_TYPE_KX ||
6228 	    pi->port_type == FW_PORT_TYPE_KR ||
6229 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
6230 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
6231 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
6232 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
6233 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
6234 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
6235 }
6236 
6237 static void
6238 build_medialist(struct port_info *pi)
6239 {
6240 	uint32_t ss, speed;
6241 	int unknown, mword, bit;
6242 	struct link_config *lc;
6243 	struct ifmedia *ifm;
6244 
6245 	PORT_LOCK_ASSERT_OWNED(pi);
6246 
6247 	if (pi->flags & FIXED_IFMEDIA)
6248 		return;
6249 
6250 	/*
6251 	 * Rebuild the ifmedia list.
6252 	 */
6253 	ifm = &pi->media;
6254 	ifmedia_removeall(ifm);
6255 	lc = &pi->link_cfg;
6256 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
6257 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
6258 		MPASS(ss != 0);
6259 no_media:
6260 		MPASS(LIST_EMPTY(&ifm->ifm_list));
6261 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
6262 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
6263 		return;
6264 	}
6265 
6266 	unknown = 0;
6267 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
6268 		speed = 1 << bit;
6269 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
6270 		if (ss & speed) {
6271 			mword = port_mword(pi, speed);
6272 			if (mword == IFM_NONE) {
6273 				goto no_media;
6274 			} else if (mword == IFM_UNKNOWN)
6275 				unknown++;
6276 			else
6277 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
6278 		}
6279 	}
6280 	if (unknown > 0) /* Add one unknown for all unknown media types. */
6281 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
6282 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
6283 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
6284 
6285 	set_current_media(pi);
6286 }
6287 
6288 /*
6289  * Initialize the requested fields in the link config based on driver tunables.
6290  */
6291 static void
6292 init_link_config(struct port_info *pi)
6293 {
6294 	struct link_config *lc = &pi->link_cfg;
6295 
6296 	PORT_LOCK_ASSERT_OWNED(pi);
6297 
6298 	lc->requested_caps = 0;
6299 	lc->requested_speed = 0;
6300 
6301 	if (t4_autoneg == 0)
6302 		lc->requested_aneg = AUTONEG_DISABLE;
6303 	else if (t4_autoneg == 1)
6304 		lc->requested_aneg = AUTONEG_ENABLE;
6305 	else
6306 		lc->requested_aneg = AUTONEG_AUTO;
6307 
6308 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6309 	    PAUSE_AUTONEG);
6310 
6311 	if (t4_fec & FEC_AUTO)
6312 		lc->requested_fec = FEC_AUTO;
6313 	else if (t4_fec == 0)
6314 		lc->requested_fec = FEC_NONE;
6315 	else {
6316 		/* -1 is handled by the FEC_AUTO block above and not here. */
6317 		lc->requested_fec = t4_fec &
6318 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6319 		if (lc->requested_fec == 0)
6320 			lc->requested_fec = FEC_AUTO;
6321 	}
6322 	if (t4_force_fec < 0)
6323 		lc->force_fec = -1;
6324 	else if (t4_force_fec > 0)
6325 		lc->force_fec = 1;
6326 	else
6327 		lc->force_fec = 0;
6328 }
6329 
6330 /*
6331  * Makes sure that all requested settings comply with what's supported by the
6332  * port.  Returns the number of settings that were invalid and had to be fixed.
6333  */
6334 static int
6335 fixup_link_config(struct port_info *pi)
6336 {
6337 	int n = 0;
6338 	struct link_config *lc = &pi->link_cfg;
6339 	uint32_t fwspeed;
6340 
6341 	PORT_LOCK_ASSERT_OWNED(pi);
6342 
6343 	/* Speed (when not autonegotiating) */
6344 	if (lc->requested_speed != 0) {
6345 		fwspeed = speed_to_fwcap(lc->requested_speed);
6346 		if ((fwspeed & lc->pcaps) == 0) {
6347 			n++;
6348 			lc->requested_speed = 0;
6349 		}
6350 	}
6351 
6352 	/* Link autonegotiation */
6353 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6354 	    lc->requested_aneg == AUTONEG_DISABLE ||
6355 	    lc->requested_aneg == AUTONEG_AUTO);
6356 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6357 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6358 		n++;
6359 		lc->requested_aneg = AUTONEG_AUTO;
6360 	}
6361 
6362 	/* Flow control */
6363 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6364 	if (lc->requested_fc & PAUSE_TX &&
6365 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6366 		n++;
6367 		lc->requested_fc &= ~PAUSE_TX;
6368 	}
6369 	if (lc->requested_fc & PAUSE_RX &&
6370 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6371 		n++;
6372 		lc->requested_fc &= ~PAUSE_RX;
6373 	}
6374 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6375 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6376 		n++;
6377 		lc->requested_fc |= PAUSE_AUTONEG;
6378 	}
6379 
6380 	/* FEC */
6381 	if ((lc->requested_fec & FEC_RS &&
6382 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6383 	    (lc->requested_fec & FEC_BASER_RS &&
6384 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6385 		n++;
6386 		lc->requested_fec = FEC_AUTO;
6387 	}
6388 
6389 	return (n);
6390 }
6391 
6392 /*
6393  * Apply the requested L1 settings, which are expected to be valid, to the
6394  * hardware.
6395  */
6396 static int
6397 apply_link_config(struct port_info *pi)
6398 {
6399 	struct adapter *sc = pi->adapter;
6400 	struct link_config *lc = &pi->link_cfg;
6401 	int rc;
6402 
6403 #ifdef INVARIANTS
6404 	ASSERT_SYNCHRONIZED_OP(sc);
6405 	PORT_LOCK_ASSERT_OWNED(pi);
6406 
6407 	if (lc->requested_aneg == AUTONEG_ENABLE)
6408 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6409 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6410 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6411 	if (lc->requested_fc & PAUSE_TX)
6412 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6413 	if (lc->requested_fc & PAUSE_RX)
6414 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6415 	if (lc->requested_fec & FEC_RS)
6416 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6417 	if (lc->requested_fec & FEC_BASER_RS)
6418 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6419 #endif
6420 	if (!(sc->flags & IS_VF)) {
6421 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->hw_port, lc);
6422 		if (rc != 0) {
6423 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6424 			return (rc);
6425 		}
6426 	}
6427 
6428 	/*
6429 	 * An L1_CFG will almost always result in a link-change event if the
6430 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6431 	 * the notification is processed.  If the link is down then the actual
6432 	 * settings are meaningless.
6433 	 *
6434 	 * This takes care of the case where a change in the L1 settings may not
6435 	 * result in a notification.
6436 	 */
6437 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6438 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6439 
6440 	return (0);
6441 }
6442 
6443 #define FW_MAC_EXACT_CHUNK	7
6444 struct mcaddr_ctx {
6445 	if_t ifp;
6446 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6447 	uint64_t hash;
6448 	int i;
6449 	int del;
6450 	int rc;
6451 };
6452 
6453 static u_int
6454 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6455 {
6456 	struct mcaddr_ctx *ctx = arg;
6457 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6458 	struct port_info *pi = vi->pi;
6459 	struct adapter *sc = pi->adapter;
6460 
6461 	if (ctx->rc < 0)
6462 		return (0);
6463 
6464 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6465 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6466 	ctx->i++;
6467 
6468 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6469 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6470 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6471 		if (ctx->rc < 0) {
6472 			int j;
6473 
6474 			for (j = 0; j < ctx->i; j++) {
6475 				if_printf(ctx->ifp,
6476 				    "failed to add mc address"
6477 				    " %02x:%02x:%02x:"
6478 				    "%02x:%02x:%02x rc=%d\n",
6479 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6480 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6481 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6482 				    -ctx->rc);
6483 			}
6484 			return (0);
6485 		}
6486 		ctx->del = 0;
6487 		ctx->i = 0;
6488 	}
6489 
6490 	return (1);
6491 }
6492 
6493 /*
6494  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6495  * indicates which parameters should be programmed (the rest are left alone).
6496  */
6497 int
6498 update_mac_settings(if_t ifp, int flags)
6499 {
6500 	int rc = 0;
6501 	struct vi_info *vi = if_getsoftc(ifp);
6502 	struct port_info *pi = vi->pi;
6503 	struct adapter *sc = pi->adapter;
6504 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6505 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6506 
6507 	ASSERT_SYNCHRONIZED_OP(sc);
6508 	KASSERT(flags, ("%s: not told what to update.", __func__));
6509 
6510 	if (flags & XGMAC_MTU)
6511 		mtu = if_getmtu(ifp);
6512 
6513 	if (flags & XGMAC_PROMISC)
6514 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6515 
6516 	if (flags & XGMAC_ALLMULTI)
6517 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6518 
6519 	if (flags & XGMAC_VLANEX)
6520 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6521 
6522 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6523 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6524 		    allmulti, 1, vlanex, false);
6525 		if (rc) {
6526 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6527 			    rc);
6528 			return (rc);
6529 		}
6530 	}
6531 
6532 	if (flags & XGMAC_UCADDR) {
6533 		uint8_t ucaddr[ETHER_ADDR_LEN];
6534 
6535 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6536 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6537 		    ucaddr, true, &vi->smt_idx);
6538 		if (rc < 0) {
6539 			rc = -rc;
6540 			if_printf(ifp, "change_mac failed: %d\n", rc);
6541 			return (rc);
6542 		} else {
6543 			vi->xact_addr_filt = rc;
6544 			rc = 0;
6545 		}
6546 	}
6547 
6548 	if (flags & XGMAC_MCADDRS) {
6549 		struct epoch_tracker et;
6550 		struct mcaddr_ctx ctx;
6551 		int j;
6552 
6553 		ctx.ifp = ifp;
6554 		ctx.hash = 0;
6555 		ctx.i = 0;
6556 		ctx.del = 1;
6557 		ctx.rc = 0;
6558 		/*
6559 		 * Unlike other drivers, we accumulate list of pointers into
6560 		 * interface address lists and we need to keep it safe even
6561 		 * after if_foreach_llmaddr() returns, thus we must enter the
6562 		 * network epoch.
6563 		 */
6564 		NET_EPOCH_ENTER(et);
6565 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6566 		if (ctx.rc < 0) {
6567 			NET_EPOCH_EXIT(et);
6568 			rc = -ctx.rc;
6569 			return (rc);
6570 		}
6571 		if (ctx.i > 0) {
6572 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6573 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6574 			NET_EPOCH_EXIT(et);
6575 			if (rc < 0) {
6576 				rc = -rc;
6577 				for (j = 0; j < ctx.i; j++) {
6578 					if_printf(ifp,
6579 					    "failed to add mcast address"
6580 					    " %02x:%02x:%02x:"
6581 					    "%02x:%02x:%02x rc=%d\n",
6582 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6583 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6584 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6585 					    rc);
6586 				}
6587 				return (rc);
6588 			}
6589 			ctx.del = 0;
6590 		} else
6591 			NET_EPOCH_EXIT(et);
6592 
6593 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6594 		if (rc != 0)
6595 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6596 			    rc);
6597 		if (ctx.del == 0) {
6598 			/* We clobbered the VXLAN entry if there was one. */
6599 			pi->vxlan_tcam_entry = false;
6600 		}
6601 	}
6602 
6603 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6604 	    pi->vxlan_tcam_entry == false) {
6605 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6606 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6607 		    true);
6608 		if (rc < 0) {
6609 			rc = -rc;
6610 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6611 			    rc);
6612 		} else {
6613 			MPASS(rc == sc->rawf_base + pi->port_id);
6614 			rc = 0;
6615 			pi->vxlan_tcam_entry = true;
6616 		}
6617 	}
6618 
6619 	return (rc);
6620 }
6621 
6622 /*
6623  * {begin|end}_synchronized_op must be called from the same thread.
6624  */
6625 int
6626 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6627     char *wmesg)
6628 {
6629 	int rc;
6630 
6631 #ifdef WITNESS
6632 	/* the caller thinks it's ok to sleep, but is it really? */
6633 	if (flags & SLEEP_OK)
6634 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
6635 #endif
6636 	ADAPTER_LOCK(sc);
6637 	for (;;) {
6638 
6639 		if (vi && IS_DETACHING(vi)) {
6640 			rc = ENXIO;
6641 			goto done;
6642 		}
6643 
6644 		if (!IS_BUSY(sc)) {
6645 			rc = 0;
6646 			break;
6647 		}
6648 
6649 		if (!(flags & SLEEP_OK)) {
6650 			rc = EBUSY;
6651 			goto done;
6652 		}
6653 
6654 		if (mtx_sleep(&sc->flags, &sc->sc_lock,
6655 		    flags & INTR_OK ? PCATCH : 0, wmesg, 0)) {
6656 			rc = EINTR;
6657 			goto done;
6658 		}
6659 	}
6660 
6661 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6662 	SET_BUSY(sc);
6663 #ifdef INVARIANTS
6664 	sc->last_op = wmesg;
6665 	sc->last_op_thr = curthread;
6666 	sc->last_op_flags = flags;
6667 #endif
6668 
6669 done:
6670 	if (!(flags & HOLD_LOCK) || rc)
6671 		ADAPTER_UNLOCK(sc);
6672 
6673 	return (rc);
6674 }
6675 
6676 /*
6677  * Tell if_ioctl and if_init that the VI is going away.  This is
6678  * special variant of begin_synchronized_op and must be paired with a
6679  * call to end_vi_detach.
6680  */
6681 void
6682 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6683 {
6684 	ADAPTER_LOCK(sc);
6685 	SET_DETACHING(vi);
6686 	wakeup(&sc->flags);
6687 	while (IS_BUSY(sc))
6688 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6689 	SET_BUSY(sc);
6690 #ifdef INVARIANTS
6691 	sc->last_op = "t4detach";
6692 	sc->last_op_thr = curthread;
6693 	sc->last_op_flags = 0;
6694 #endif
6695 	ADAPTER_UNLOCK(sc);
6696 }
6697 
6698 void
6699 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6700 {
6701 	ADAPTER_LOCK(sc);
6702 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6703 	CLR_BUSY(sc);
6704 	CLR_DETACHING(vi);
6705 	wakeup(&sc->flags);
6706 	ADAPTER_UNLOCK(sc);
6707 }
6708 
6709 /*
6710  * {begin|end}_synchronized_op must be called from the same thread.
6711  */
6712 void
6713 end_synchronized_op(struct adapter *sc, int flags)
6714 {
6715 
6716 	if (flags & LOCK_HELD)
6717 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6718 	else
6719 		ADAPTER_LOCK(sc);
6720 
6721 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6722 	CLR_BUSY(sc);
6723 	wakeup(&sc->flags);
6724 	ADAPTER_UNLOCK(sc);
6725 }
6726 
6727 static int
6728 cxgbe_init_synchronized(struct vi_info *vi)
6729 {
6730 	struct port_info *pi = vi->pi;
6731 	struct adapter *sc = pi->adapter;
6732 	if_t ifp = vi->ifp;
6733 	int rc = 0, i;
6734 	struct sge_txq *txq;
6735 
6736 	ASSERT_SYNCHRONIZED_OP(sc);
6737 
6738 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6739 		return (0);	/* already running */
6740 
6741 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6742 		return (rc);	/* error message displayed already */
6743 
6744 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6745 		return (rc); /* error message displayed already */
6746 
6747 	rc = update_mac_settings(ifp, XGMAC_ALL);
6748 	if (rc)
6749 		goto done;	/* error message displayed already */
6750 
6751 	PORT_LOCK(pi);
6752 	if (pi->up_vis == 0) {
6753 		t4_update_port_info(pi);
6754 		fixup_link_config(pi);
6755 		build_medialist(pi);
6756 		apply_link_config(pi);
6757 	}
6758 
6759 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6760 	if (rc != 0) {
6761 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6762 		PORT_UNLOCK(pi);
6763 		goto done;
6764 	}
6765 
6766 	/*
6767 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6768 	 * if this changes.
6769 	 */
6770 
6771 	for_each_txq(vi, i, txq) {
6772 		TXQ_LOCK(txq);
6773 		txq->eq.flags |= EQ_ENABLED;
6774 		TXQ_UNLOCK(txq);
6775 	}
6776 
6777 	/*
6778 	 * The first iq of the first port to come up is used for tracing.
6779 	 */
6780 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6781 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6782 		t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
6783 		pi->flags |= HAS_TRACEQ;
6784 	}
6785 
6786 	/* all ok */
6787 	pi->up_vis++;
6788 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6789 	if (pi->link_cfg.link_ok)
6790 		t4_os_link_changed(pi);
6791 	PORT_UNLOCK(pi);
6792 
6793 	mtx_lock(&vi->tick_mtx);
6794 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6795 		callout_reset(&vi->tick, hz, vi_tick, vi);
6796 	else
6797 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6798 	mtx_unlock(&vi->tick_mtx);
6799 done:
6800 	if (rc != 0)
6801 		cxgbe_uninit_synchronized(vi);
6802 
6803 	return (rc);
6804 }
6805 
6806 /*
6807  * Idempotent.
6808  */
6809 static int
6810 cxgbe_uninit_synchronized(struct vi_info *vi)
6811 {
6812 	struct port_info *pi = vi->pi;
6813 	struct adapter *sc = pi->adapter;
6814 	if_t ifp = vi->ifp;
6815 	int rc, i;
6816 	struct sge_txq *txq;
6817 
6818 	ASSERT_SYNCHRONIZED_OP(sc);
6819 
6820 	if (!(vi->flags & VI_INIT_DONE)) {
6821 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6822 			KASSERT(0, ("uninited VI is running"));
6823 			if_printf(ifp, "uninited VI with running ifnet.  "
6824 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6825 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6826 			    if_getdrvflags(ifp));
6827 		}
6828 		return (0);
6829 	}
6830 
6831 	/*
6832 	 * Disable the VI so that all its data in either direction is discarded
6833 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6834 	 * tick) intact as the TP can deliver negative advice or data that it's
6835 	 * holding in its RAM (for an offloaded connection) even after the VI is
6836 	 * disabled.
6837 	 */
6838 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6839 	if (rc) {
6840 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6841 		return (rc);
6842 	}
6843 
6844 	for_each_txq(vi, i, txq) {
6845 		TXQ_LOCK(txq);
6846 		txq->eq.flags &= ~EQ_ENABLED;
6847 		TXQ_UNLOCK(txq);
6848 	}
6849 
6850 	mtx_lock(&vi->tick_mtx);
6851 	callout_stop(&vi->tick);
6852 	mtx_unlock(&vi->tick_mtx);
6853 
6854 	PORT_LOCK(pi);
6855 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6856 		PORT_UNLOCK(pi);
6857 		return (0);
6858 	}
6859 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6860 	pi->up_vis--;
6861 	if (pi->up_vis > 0) {
6862 		PORT_UNLOCK(pi);
6863 		return (0);
6864 	}
6865 
6866 	pi->link_cfg.link_ok = false;
6867 	pi->link_cfg.speed = 0;
6868 	pi->link_cfg.link_down_rc = 255;
6869 	t4_os_link_changed(pi);
6870 	PORT_UNLOCK(pi);
6871 
6872 	return (0);
6873 }
6874 
6875 /*
6876  * It is ok for this function to fail midway and return right away.  t4_detach
6877  * will walk the entire sc->irq list and clean up whatever is valid.
6878  */
6879 int
6880 t4_setup_intr_handlers(struct adapter *sc)
6881 {
6882 	int rc, rid, p, q, v;
6883 	char s[8];
6884 	struct irq *irq;
6885 	struct port_info *pi;
6886 	struct vi_info *vi;
6887 	struct sge *sge = &sc->sge;
6888 	struct sge_rxq *rxq;
6889 #ifdef TCP_OFFLOAD
6890 	struct sge_ofld_rxq *ofld_rxq;
6891 #endif
6892 #ifdef DEV_NETMAP
6893 	struct sge_nm_rxq *nm_rxq;
6894 #endif
6895 #ifdef RSS
6896 	int nbuckets = rss_getnumbuckets();
6897 #endif
6898 
6899 	/*
6900 	 * Setup interrupts.
6901 	 */
6902 	irq = &sc->irq[0];
6903 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6904 	if (forwarding_intr_to_fwq(sc))
6905 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6906 
6907 	/* Multiple interrupts. */
6908 	if (sc->flags & IS_VF)
6909 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6910 		    ("%s: too few intr.", __func__));
6911 	else
6912 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6913 		    ("%s: too few intr.", __func__));
6914 
6915 	/* The first one is always error intr on PFs */
6916 	if (!(sc->flags & IS_VF)) {
6917 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6918 		if (rc != 0)
6919 			return (rc);
6920 		irq++;
6921 		rid++;
6922 	}
6923 
6924 	/* The second one is always the firmware event queue (first on VFs) */
6925 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6926 	if (rc != 0)
6927 		return (rc);
6928 	irq++;
6929 	rid++;
6930 
6931 	for_each_port(sc, p) {
6932 		pi = sc->port[p];
6933 		for_each_vi(pi, v, vi) {
6934 			vi->first_intr = rid - 1;
6935 
6936 			if (vi->nnmrxq > 0) {
6937 				int n = max(vi->nrxq, vi->nnmrxq);
6938 
6939 				rxq = &sge->rxq[vi->first_rxq];
6940 #ifdef DEV_NETMAP
6941 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6942 #endif
6943 				for (q = 0; q < n; q++) {
6944 					snprintf(s, sizeof(s), "%x%c%x", p,
6945 					    'a' + v, q);
6946 					if (q < vi->nrxq)
6947 						irq->rxq = rxq++;
6948 #ifdef DEV_NETMAP
6949 					if (q < vi->nnmrxq)
6950 						irq->nm_rxq = nm_rxq++;
6951 
6952 					if (irq->nm_rxq != NULL &&
6953 					    irq->rxq == NULL) {
6954 						/* Netmap rx only */
6955 						rc = t4_alloc_irq(sc, irq, rid,
6956 						    t4_nm_intr, irq->nm_rxq, s);
6957 					}
6958 					if (irq->nm_rxq != NULL &&
6959 					    irq->rxq != NULL) {
6960 						/* NIC and Netmap rx */
6961 						rc = t4_alloc_irq(sc, irq, rid,
6962 						    t4_vi_intr, irq, s);
6963 					}
6964 #endif
6965 					if (irq->rxq != NULL &&
6966 					    irq->nm_rxq == NULL) {
6967 						/* NIC rx only */
6968 						rc = t4_alloc_irq(sc, irq, rid,
6969 						    t4_intr, irq->rxq, s);
6970 					}
6971 					if (rc != 0)
6972 						return (rc);
6973 #ifdef RSS
6974 					if (q < vi->nrxq) {
6975 						bus_bind_intr(sc->dev, irq->res,
6976 						    rss_getcpu(q % nbuckets));
6977 					}
6978 #endif
6979 					irq++;
6980 					rid++;
6981 					vi->nintr++;
6982 				}
6983 			} else {
6984 				for_each_rxq(vi, q, rxq) {
6985 					snprintf(s, sizeof(s), "%x%c%x", p,
6986 					    'a' + v, q);
6987 					rc = t4_alloc_irq(sc, irq, rid,
6988 					    t4_intr, rxq, s);
6989 					if (rc != 0)
6990 						return (rc);
6991 #ifdef RSS
6992 					bus_bind_intr(sc->dev, irq->res,
6993 					    rss_getcpu(q % nbuckets));
6994 #endif
6995 					irq++;
6996 					rid++;
6997 					vi->nintr++;
6998 				}
6999 			}
7000 #ifdef TCP_OFFLOAD
7001 			for_each_ofld_rxq(vi, q, ofld_rxq) {
7002 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
7003 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
7004 				    ofld_rxq, s);
7005 				if (rc != 0)
7006 					return (rc);
7007 				irq++;
7008 				rid++;
7009 				vi->nintr++;
7010 			}
7011 #endif
7012 		}
7013 	}
7014 	MPASS(irq == &sc->irq[sc->intr_count]);
7015 
7016 	return (0);
7017 }
7018 
7019 static void
7020 write_global_rss_key(struct adapter *sc)
7021 {
7022 #ifdef RSS
7023 	int i;
7024 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7025 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7026 
7027 	CTASSERT(RSS_KEYSIZE == 40);
7028 
7029 	rss_getkey((void *)&raw_rss_key[0]);
7030 	for (i = 0; i < nitems(rss_key); i++) {
7031 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
7032 	}
7033 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
7034 #endif
7035 }
7036 
7037 /*
7038  * Idempotent.
7039  */
7040 static int
7041 adapter_full_init(struct adapter *sc)
7042 {
7043 	int rc, i;
7044 
7045 	ASSERT_SYNCHRONIZED_OP(sc);
7046 
7047 	/*
7048 	 * queues that belong to the adapter (not any particular port).
7049 	 */
7050 	rc = t4_setup_adapter_queues(sc);
7051 	if (rc != 0)
7052 		return (rc);
7053 
7054 	MPASS(sc->params.nports <= nitems(sc->tq));
7055 	for (i = 0; i < sc->params.nports; i++) {
7056 		if (sc->tq[i] != NULL)
7057 			continue;
7058 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
7059 		    taskqueue_thread_enqueue, &sc->tq[i]);
7060 		if (sc->tq[i] == NULL) {
7061 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
7062 			return (ENOMEM);
7063 		}
7064 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
7065 		    device_get_nameunit(sc->dev), i);
7066 	}
7067 
7068 	if (!(sc->flags & IS_VF)) {
7069 		write_global_rss_key(sc);
7070 		t4_intr_enable(sc);
7071 	}
7072 	return (0);
7073 }
7074 
7075 int
7076 adapter_init(struct adapter *sc)
7077 {
7078 	int rc;
7079 
7080 	ASSERT_SYNCHRONIZED_OP(sc);
7081 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
7082 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
7083 	    ("%s: FULL_INIT_DONE already", __func__));
7084 
7085 	rc = adapter_full_init(sc);
7086 	if (rc != 0)
7087 		adapter_full_uninit(sc);
7088 	else
7089 		sc->flags |= FULL_INIT_DONE;
7090 
7091 	return (rc);
7092 }
7093 
7094 /*
7095  * Idempotent.
7096  */
7097 static void
7098 adapter_full_uninit(struct adapter *sc)
7099 {
7100 	int i;
7101 
7102 	t4_teardown_adapter_queues(sc);
7103 
7104 	for (i = 0; i < nitems(sc->tq); i++) {
7105 		if (sc->tq[i] == NULL)
7106 			continue;
7107 		taskqueue_free(sc->tq[i]);
7108 		sc->tq[i] = NULL;
7109 	}
7110 
7111 	sc->flags &= ~FULL_INIT_DONE;
7112 }
7113 
7114 #ifdef RSS
7115 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
7116     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
7117     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
7118     RSS_HASHTYPE_RSS_UDP_IPV6)
7119 
7120 /* Translates kernel hash types to hardware. */
7121 static int
7122 hashconfig_to_hashen(int hashconfig)
7123 {
7124 	int hashen = 0;
7125 
7126 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
7127 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
7128 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
7129 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
7130 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
7131 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7132 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7133 	}
7134 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
7135 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7136 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7137 	}
7138 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
7139 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7140 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
7141 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7142 
7143 	return (hashen);
7144 }
7145 
7146 /* Translates hardware hash types to kernel. */
7147 static int
7148 hashen_to_hashconfig(int hashen)
7149 {
7150 	int hashconfig = 0;
7151 
7152 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
7153 		/*
7154 		 * If UDP hashing was enabled it must have been enabled for
7155 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
7156 		 * enabling any 4-tuple hash is nonsense configuration.
7157 		 */
7158 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7159 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
7160 
7161 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7162 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
7163 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7164 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
7165 	}
7166 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7167 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
7168 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7169 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
7170 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
7171 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
7172 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
7173 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
7174 
7175 	return (hashconfig);
7176 }
7177 #endif
7178 
7179 /*
7180  * Idempotent.
7181  */
7182 static int
7183 vi_full_init(struct vi_info *vi)
7184 {
7185 	struct adapter *sc = vi->adapter;
7186 	struct sge_rxq *rxq;
7187 	int rc, i, j;
7188 #ifdef RSS
7189 	int nbuckets = rss_getnumbuckets();
7190 	int hashconfig = rss_gethashconfig();
7191 	int extra;
7192 #endif
7193 
7194 	ASSERT_SYNCHRONIZED_OP(sc);
7195 
7196 	/*
7197 	 * Allocate tx/rx/fl queues for this VI.
7198 	 */
7199 	rc = t4_setup_vi_queues(vi);
7200 	if (rc != 0)
7201 		return (rc);
7202 
7203 	/*
7204 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
7205 	 */
7206 	if (vi->nrxq > vi->rss_size) {
7207 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
7208 		    "some queues will never receive traffic.\n", vi->nrxq,
7209 		    vi->rss_size);
7210 	} else if (vi->rss_size % vi->nrxq) {
7211 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
7212 		    "expect uneven traffic distribution.\n", vi->nrxq,
7213 		    vi->rss_size);
7214 	}
7215 #ifdef RSS
7216 	if (vi->nrxq != nbuckets) {
7217 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
7218 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
7219 	}
7220 #endif
7221 	if (vi->rss == NULL)
7222 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
7223 		    M_ZERO | M_WAITOK);
7224 	for (i = 0; i < vi->rss_size;) {
7225 #ifdef RSS
7226 		j = rss_get_indirection_to_bucket(i);
7227 		j %= vi->nrxq;
7228 		rxq = &sc->sge.rxq[vi->first_rxq + j];
7229 		vi->rss[i++] = rxq->iq.abs_id;
7230 #else
7231 		for_each_rxq(vi, j, rxq) {
7232 			vi->rss[i++] = rxq->iq.abs_id;
7233 			if (i == vi->rss_size)
7234 				break;
7235 		}
7236 #endif
7237 	}
7238 
7239 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
7240 	    vi->rss, vi->rss_size);
7241 	if (rc != 0) {
7242 		CH_ERR(vi, "rss_config failed: %d\n", rc);
7243 		return (rc);
7244 	}
7245 
7246 #ifdef RSS
7247 	vi->hashen = hashconfig_to_hashen(hashconfig);
7248 
7249 	/*
7250 	 * We may have had to enable some hashes even though the global config
7251 	 * wants them disabled.  This is a potential problem that must be
7252 	 * reported to the user.
7253 	 */
7254 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
7255 
7256 	/*
7257 	 * If we consider only the supported hash types, then the enabled hashes
7258 	 * are a superset of the requested hashes.  In other words, there cannot
7259 	 * be any supported hash that was requested but not enabled, but there
7260 	 * can be hashes that were not requested but had to be enabled.
7261 	 */
7262 	extra &= SUPPORTED_RSS_HASHTYPES;
7263 	MPASS((extra & hashconfig) == 0);
7264 
7265 	if (extra) {
7266 		CH_ALERT(vi,
7267 		    "global RSS config (0x%x) cannot be accommodated.\n",
7268 		    hashconfig);
7269 	}
7270 	if (extra & RSS_HASHTYPE_RSS_IPV4)
7271 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
7272 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
7273 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
7274 	if (extra & RSS_HASHTYPE_RSS_IPV6)
7275 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
7276 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
7277 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
7278 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
7279 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
7280 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
7281 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
7282 #else
7283 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
7284 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
7285 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7286 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
7287 #endif
7288 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
7289 	    0, 0);
7290 	if (rc != 0) {
7291 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
7292 		return (rc);
7293 	}
7294 
7295 	return (0);
7296 }
7297 
7298 int
7299 vi_init(struct vi_info *vi)
7300 {
7301 	int rc;
7302 
7303 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7304 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7305 	    ("%s: VI_INIT_DONE already", __func__));
7306 
7307 	rc = vi_full_init(vi);
7308 	if (rc != 0)
7309 		vi_full_uninit(vi);
7310 	else
7311 		vi->flags |= VI_INIT_DONE;
7312 
7313 	return (rc);
7314 }
7315 
7316 /*
7317  * Idempotent.
7318  */
7319 static void
7320 vi_full_uninit(struct vi_info *vi)
7321 {
7322 
7323 	if (vi->flags & VI_INIT_DONE) {
7324 		quiesce_vi(vi);
7325 		free(vi->rss, M_CXGBE);
7326 		free(vi->nm_rss, M_CXGBE);
7327 	}
7328 
7329 	t4_teardown_vi_queues(vi);
7330 	vi->flags &= ~VI_INIT_DONE;
7331 }
7332 
7333 static void
7334 quiesce_txq(struct sge_txq *txq)
7335 {
7336 	struct sge_eq *eq = &txq->eq;
7337 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7338 
7339 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7340 	MPASS(!(eq->flags & EQ_ENABLED));
7341 
7342 	/* Wait for the mp_ring to empty. */
7343 	while (!mp_ring_is_idle(txq->r)) {
7344 		mp_ring_check_drainage(txq->r, 4096);
7345 		pause("rquiesce", 1);
7346 	}
7347 	MPASS(txq->txp.npkt == 0);
7348 
7349 	if (eq->flags & EQ_HW_ALLOCATED) {
7350 		/*
7351 		 * Hardware is alive and working normally.  Wait for it to
7352 		 * finish and then wait for the driver to catch up and reclaim
7353 		 * all descriptors.
7354 		 */
7355 		while (spg->cidx != htobe16(eq->pidx))
7356 			pause("equiesce", 1);
7357 		while (eq->cidx != eq->pidx)
7358 			pause("dquiesce", 1);
7359 	} else {
7360 		/*
7361 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7362 		 * descriptors directly.
7363 		 */
7364 		TXQ_LOCK(txq);
7365 		while (eq->cidx != eq->pidx) {
7366 			struct mbuf *m, *nextpkt;
7367 			struct tx_sdesc *txsd;
7368 
7369 			txsd = &txq->sdesc[eq->cidx];
7370 			for (m = txsd->m; m != NULL; m = nextpkt) {
7371 				nextpkt = m->m_nextpkt;
7372 				m->m_nextpkt = NULL;
7373 				m_freem(m);
7374 			}
7375 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7376 		}
7377 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7378 		TXQ_UNLOCK(txq);
7379 	}
7380 }
7381 
7382 static void
7383 quiesce_wrq(struct sge_wrq *wrq)
7384 {
7385 	struct wrqe *wr;
7386 
7387 	TXQ_LOCK(wrq);
7388 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7389 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7390 #ifdef INVARIANTS
7391 		wrq->nwr_pending--;
7392 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7393 #endif
7394 		free(wr, M_CXGBE);
7395 	}
7396 	MPASS(wrq->nwr_pending == 0);
7397 	MPASS(wrq->ndesc_needed == 0);
7398 	wrq->nwr_pending = 0;
7399 	wrq->ndesc_needed = 0;
7400 	TXQ_UNLOCK(wrq);
7401 }
7402 
7403 static void
7404 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7405 {
7406 	/* Synchronize with the interrupt handler */
7407 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7408 		pause("iqfree", 1);
7409 
7410 	if (fl != NULL) {
7411 		MPASS(iq->flags & IQ_HAS_FL);
7412 
7413 		mtx_lock(&sc->sfl_lock);
7414 		FL_LOCK(fl);
7415 		fl->flags |= FL_DOOMED;
7416 		FL_UNLOCK(fl);
7417 		callout_stop(&sc->sfl_callout);
7418 		mtx_unlock(&sc->sfl_lock);
7419 
7420 		KASSERT((fl->flags & FL_STARVING) == 0,
7421 		    ("%s: still starving", __func__));
7422 
7423 		/* Release all buffers if hardware is no longer available. */
7424 		if (!(iq->flags & IQ_HW_ALLOCATED))
7425 			free_fl_buffers(sc, fl);
7426 	}
7427 }
7428 
7429 /*
7430  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7431  * that no new work is being enqueued by the hardware or the driver.  That part
7432  * should be arranged before calling this function.
7433  */
7434 static void
7435 quiesce_vi(struct vi_info *vi)
7436 {
7437 	int i;
7438 	struct adapter *sc = vi->adapter;
7439 	struct sge_rxq *rxq;
7440 	struct sge_txq *txq;
7441 #ifdef TCP_OFFLOAD
7442 	struct sge_ofld_rxq *ofld_rxq;
7443 #endif
7444 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7445 	struct sge_ofld_txq *ofld_txq;
7446 #endif
7447 
7448 	if (!(vi->flags & VI_INIT_DONE))
7449 		return;
7450 
7451 	for_each_txq(vi, i, txq) {
7452 		quiesce_txq(txq);
7453 	}
7454 
7455 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7456 	for_each_ofld_txq(vi, i, ofld_txq) {
7457 		quiesce_wrq(&ofld_txq->wrq);
7458 	}
7459 #endif
7460 
7461 	for_each_rxq(vi, i, rxq) {
7462 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7463 	}
7464 
7465 #ifdef TCP_OFFLOAD
7466 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7467 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7468 	}
7469 #endif
7470 }
7471 
7472 static int
7473 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7474     driver_intr_t *handler, void *arg, char *name)
7475 {
7476 	int rc;
7477 
7478 	irq->rid = rid;
7479 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7480 	    RF_SHAREABLE | RF_ACTIVE);
7481 	if (irq->res == NULL) {
7482 		device_printf(sc->dev,
7483 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7484 		return (ENOMEM);
7485 	}
7486 
7487 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7488 	    NULL, handler, arg, &irq->tag);
7489 	if (rc != 0) {
7490 		device_printf(sc->dev,
7491 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7492 		    rid, name, rc);
7493 	} else if (name)
7494 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7495 
7496 	return (rc);
7497 }
7498 
7499 static int
7500 t4_free_irq(struct adapter *sc, struct irq *irq)
7501 {
7502 	if (irq->tag)
7503 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7504 	if (irq->res)
7505 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7506 
7507 	bzero(irq, sizeof(*irq));
7508 
7509 	return (0);
7510 }
7511 
7512 static void
7513 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7514 {
7515 
7516 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7517 	t4_get_regs(sc, buf, regs->len);
7518 }
7519 
7520 #define	A_PL_INDIR_CMD	0x1f8
7521 
7522 #define	S_PL_AUTOINC	31
7523 #define	M_PL_AUTOINC	0x1U
7524 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7525 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7526 
7527 #define	S_PL_VFID	20
7528 #define	M_PL_VFID	0xffU
7529 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7530 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7531 
7532 #define	S_PL_ADDR	0
7533 #define	M_PL_ADDR	0xfffffU
7534 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7535 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7536 
7537 #define	A_PL_INDIR_DATA	0x1fc
7538 
7539 static uint64_t
7540 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7541 {
7542 	u32 stats[2];
7543 
7544 	if (sc->flags & IS_VF) {
7545 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7546 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7547 	} else {
7548 		mtx_assert(&sc->reg_lock, MA_OWNED);
7549 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7550 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7551 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7552 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7553 	}
7554 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7555 }
7556 
7557 static void
7558 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7559 {
7560 
7561 #define GET_STAT(name) \
7562 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7563 
7564 	if (!(sc->flags & IS_VF))
7565 		mtx_lock(&sc->reg_lock);
7566 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7567 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7568 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7569 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7570 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7571 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7572 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7573 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7574 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7575 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7576 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7577 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7578 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7579 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7580 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7581 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7582 	if (!(sc->flags & IS_VF))
7583 		mtx_unlock(&sc->reg_lock);
7584 
7585 #undef GET_STAT
7586 }
7587 
7588 static void
7589 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7590 {
7591 	int reg;
7592 
7593 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7594 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7595 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7596 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7597 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7598 }
7599 
7600 static void
7601 vi_refresh_stats(struct vi_info *vi)
7602 {
7603 	struct timeval tv;
7604 	const struct timeval interval = {0, 250000};	/* 250ms */
7605 
7606 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7607 
7608 	if (vi->flags & VI_SKIP_STATS)
7609 		return;
7610 
7611 	getmicrotime(&tv);
7612 	timevalsub(&tv, &interval);
7613 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7614 		return;
7615 
7616 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7617 	getmicrotime(&vi->last_refreshed);
7618 }
7619 
7620 static void
7621 cxgbe_refresh_stats(struct vi_info *vi)
7622 {
7623 	u_int i, v, tnl_cong_drops, chan_map;
7624 	struct timeval tv;
7625 	const struct timeval interval = {0, 250000};	/* 250ms */
7626 	struct port_info *pi;
7627 	struct adapter *sc;
7628 
7629 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7630 
7631 	if (vi->flags & VI_SKIP_STATS)
7632 		return;
7633 
7634 	getmicrotime(&tv);
7635 	timevalsub(&tv, &interval);
7636 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7637 		return;
7638 
7639 	pi = vi->pi;
7640 	sc = vi->adapter;
7641 	tnl_cong_drops = 0;
7642 	t4_get_port_stats(sc, pi->hw_port, &pi->stats);
7643 	chan_map = pi->rx_e_chan_map;
7644 	while (chan_map) {
7645 		i = ffs(chan_map) - 1;
7646 		mtx_lock(&sc->reg_lock);
7647 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7648 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7649 		mtx_unlock(&sc->reg_lock);
7650 		tnl_cong_drops += v;
7651 		chan_map &= ~(1 << i);
7652 	}
7653 	pi->tnl_cong_drops = tnl_cong_drops;
7654 	getmicrotime(&vi->last_refreshed);
7655 }
7656 
7657 static void
7658 cxgbe_tick(void *arg)
7659 {
7660 	struct vi_info *vi = arg;
7661 
7662 	MPASS(IS_MAIN_VI(vi));
7663 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7664 
7665 	cxgbe_refresh_stats(vi);
7666 	callout_schedule(&vi->tick, hz);
7667 }
7668 
7669 static void
7670 vi_tick(void *arg)
7671 {
7672 	struct vi_info *vi = arg;
7673 
7674 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7675 
7676 	vi_refresh_stats(vi);
7677 	callout_schedule(&vi->tick, hz);
7678 }
7679 
7680 /* CIM inbound queues */
7681 static const char *t4_ibq[CIM_NUM_IBQ] = {
7682 	"ibq_tp0", "ibq_tp1", "ibq_ulp", "ibq_sge0", "ibq_sge1", "ibq_ncsi"
7683 };
7684 static const char *t7_ibq[CIM_NUM_IBQ_T7] = {
7685 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7686 	"ibq_sge1", "ibq_ncsi", NULL, "ibq_ipc1", "ibq_ipc2", "ibq_ipc3",
7687 	"ibq_ipc4", "ibq_ipc5", "ibq_ipc6", "ibq_ipc7"
7688 };
7689 static const char *t7_ibq_sec[] = {
7690 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7691 	NULL, NULL, NULL, "ibq_ipc0"
7692 };
7693 
7694 /* CIM outbound queues */
7695 static const char *t4_obq[CIM_NUM_OBQ_T5] = {
7696 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7697 	"obq_sge_rx_q0", "obq_sge_rx_q1" /* These two are T5/T6 only */
7698 };
7699 static const char *t7_obq[CIM_NUM_OBQ_T7] = {
7700 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7701 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc1", "obq_ipc2", "obq_ipc3",
7702 	"obq_ipc4", "obq_ipc5", "obq_ipc6", "obq_ipc7"
7703 };
7704 static const char *t7_obq_sec[] = {
7705 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", NULL,
7706 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc0"
7707 };
7708 
7709 static void
7710 cim_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
7711     struct sysctl_oid_list *c0)
7712 {
7713 	struct sysctl_oid *oid;
7714 	struct sysctl_oid_list *children1;
7715 	int i, j, qcount;
7716 	char s[16];
7717 	const char **qname;
7718 
7719 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "cim",
7720 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM block");
7721 	c0 = SYSCTL_CHILDREN(oid);
7722 
7723 	SYSCTL_ADD_U8(ctx, c0, OID_AUTO, "ncores", CTLFLAG_RD, NULL,
7724 	    sc->params.ncores, "# of active CIM cores");
7725 
7726 	for (i = 0; i < sc->params.ncores; i++) {
7727 		snprintf(s, sizeof(s), "%u", i);
7728 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, s,
7729 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM core");
7730 		children1 = SYSCTL_CHILDREN(oid);
7731 
7732 		/*
7733 		 * CTLFLAG_SKIP because the misc.devlog sysctl already displays
7734 		 * the log for all cores.  Use this sysctl to get the log for a
7735 		 * particular core only.
7736 		 */
7737 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "devlog",
7738 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7739 		    sc, i, sysctl_devlog, "A", "firmware's device log");
7740 
7741 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "loadavg",
7742 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7743 		    sysctl_loadavg, "A",
7744 		    "microprocessor load averages (select firmwares only)");
7745 
7746 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "qcfg",
7747 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7748 		    chip_id(sc) > CHELSIO_T6 ? sysctl_cim_qcfg_t7 : sysctl_cim_qcfg,
7749 		    "A", "Queue configuration");
7750 
7751 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "la",
7752 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7753 		    sysctl_cim_la, "A", "Logic analyzer");
7754 
7755 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "ma_la",
7756 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7757 		    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7758 
7759 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "pif_la",
7760 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7761 		    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7762 
7763 		/* IBQs */
7764 		switch (chip_id(sc)) {
7765 		case CHELSIO_T4:
7766 		case CHELSIO_T5:
7767 		case CHELSIO_T6:
7768 			qname = &t4_ibq[0];
7769 			qcount = nitems(t4_ibq);
7770 			break;
7771 		case CHELSIO_T7:
7772 		default:
7773 			if (i == 0) {
7774 				qname = &t7_ibq[0];
7775 				qcount = nitems(t7_ibq);
7776 			} else {
7777 				qname = &t7_ibq_sec[0];
7778 				qcount = nitems(t7_ibq_sec);
7779 			}
7780 			break;
7781 		}
7782 		MPASS(qcount <= sc->chip_params->cim_num_ibq);
7783 		for (j = 0; j < qcount; j++) {
7784 			if (qname[j] == NULL)
7785 				continue;
7786 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7787 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7788 			    (i << 16) | j, sysctl_cim_ibq, "A", NULL);
7789 		}
7790 
7791 		/* OBQs */
7792 		switch (chip_id(sc)) {
7793 		case CHELSIO_T4:
7794 			qname = t4_obq;
7795 			qcount = CIM_NUM_OBQ;
7796 			break;
7797 		case CHELSIO_T5:
7798 		case CHELSIO_T6:
7799 			qname = t4_obq;
7800 			qcount = nitems(t4_obq);
7801 			break;
7802 		case CHELSIO_T7:
7803 		default:
7804 			if (i == 0) {
7805 				qname = t7_obq;
7806 				qcount = nitems(t7_obq);
7807 			} else {
7808 				qname = t7_obq_sec;
7809 				qcount = nitems(t7_obq_sec);
7810 			}
7811 			break;
7812 		}
7813 		MPASS(qcount <= sc->chip_params->cim_num_obq);
7814 		for (j = 0; j < qcount; j++) {
7815 			if (qname[j] == NULL)
7816 				continue;
7817 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7818 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7819 			    (i << 16) | j, sysctl_cim_obq, "A", NULL);
7820 		}
7821 	}
7822 }
7823 
7824 /*
7825  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7826  */
7827 static char *caps_decoder[] = {
7828 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7829 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7830 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7831 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7832 	    "\006HASHFILTER\007ETHOFLD",
7833 	"\20\001TOE\002SENDPATH",			/* 4: TOE */
7834 	"\20\001RDDP\002RDMAC\003ROCEv2",		/* 5: RDMA */
7835 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7836 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7837 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7838 	    "\007T10DIF"
7839 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7840 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7841 	    "\004TLS_HW,\005TOE_IPSEC",
7842 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7843 		    "\004PO_INITIATOR\005PO_TARGET",
7844 	"\20\001NVMe_TCP",				/* 9: NVMe */
7845 };
7846 
7847 void
7848 t4_sysctls(struct adapter *sc)
7849 {
7850 	struct sysctl_ctx_list *ctx = &sc->ctx;
7851 	struct sysctl_oid *oid;
7852 	struct sysctl_oid_list *children, *c0;
7853 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7854 
7855 	/*
7856 	 * dev.t4nex.X.
7857 	 */
7858 	oid = device_get_sysctl_tree(sc->dev);
7859 	c0 = children = SYSCTL_CHILDREN(oid);
7860 
7861 	sc->sc_do_rxcopy = 1;
7862 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7863 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7864 
7865 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7866 	    sc->params.nports, "# of ports");
7867 
7868 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7869 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7870 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7871 	    "available doorbells");
7872 
7873 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7874 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7875 
7876 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7877 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7878 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7879 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7880 
7881 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7882 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7883 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7884 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7885 
7886 	t4_sge_sysctls(sc, ctx, children);
7887 
7888 	sc->lro_timeout = 100;
7889 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7890 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7891 
7892 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7893 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7894 
7895 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7896 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7897 
7898 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7899 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7900 
7901 	if (sc->flags & IS_VF)
7902 		return;
7903 
7904 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7905 	    NULL, chip_rev(sc), "chip hardware revision");
7906 
7907 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7908 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7909 
7910 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7911 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7912 
7913 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7914 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7915 
7916 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7917 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7918 
7919 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7920 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7921 
7922 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7923 	    sc->er_version, 0, "expansion ROM version");
7924 
7925 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7926 	    sc->bs_version, 0, "bootstrap firmware version");
7927 
7928 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7929 	    NULL, sc->params.scfg_vers, "serial config version");
7930 
7931 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7932 	    NULL, sc->params.vpd_vers, "VPD version");
7933 
7934 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7935 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7936 
7937 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7938 	    sc->cfcsum, "config file checksum");
7939 
7940 #define SYSCTL_CAP(name, n, text) \
7941 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7942 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7943 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7944 	    "available " text " capabilities")
7945 
7946 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7947 	SYSCTL_CAP(linkcaps, 1, "link");
7948 	SYSCTL_CAP(switchcaps, 2, "switch");
7949 	SYSCTL_CAP(nvmecaps, 9, "NVMe");
7950 	SYSCTL_CAP(niccaps, 3, "NIC");
7951 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7952 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7953 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7954 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7955 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7956 #undef SYSCTL_CAP
7957 
7958 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7959 	    NULL, sc->tids.nftids, "number of filters");
7960 
7961 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7962 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7963 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7964 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7965 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7966 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7967 
7968 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7969 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7970 	    "I", "core Vdd (in mV)");
7971 
7972 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7973 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7974 	    sysctl_cpus, "A", "local CPUs");
7975 
7976 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7977 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7978 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7979 
7980 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7981 	    &sc->swintr, 0, "software triggered interrupts");
7982 
7983 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7984 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7985 	    "1 = reset adapter, 0 = zero reset counter");
7986 
7987 	/*
7988 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7989 	 */
7990 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7991 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7992 	    "logs and miscellaneous information");
7993 	children = SYSCTL_CHILDREN(oid);
7994 
7995 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7996 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7997 	    sysctl_cctrl, "A", "congestion control");
7998 
7999 	cim_sysctls(sc, ctx, children);
8000 
8001 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
8002 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8003 	    sysctl_cpl_stats, "A", "CPL statistics");
8004 
8005 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
8006 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8007 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
8008 
8009 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
8010 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8011 	    sysctl_tid_stats, "A", "tid stats");
8012 
8013 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
8014 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, -1,
8015 	    sysctl_devlog, "A", "firmware's device log (all cores)");
8016 
8017 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
8018 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8019 	    sysctl_fcoe_stats, "A", "FCoE statistics");
8020 
8021 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
8022 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8023 	    sysctl_hw_sched, "A", "hardware scheduler ");
8024 
8025 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
8026 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8027 	    sysctl_l2t, "A", "hardware L2 table");
8028 
8029 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
8030 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8031 	    sysctl_smt, "A", "hardware source MAC table");
8032 
8033 #ifdef INET6
8034 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
8035 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8036 	    sysctl_clip, "A", "active CLIP table entries");
8037 #endif
8038 
8039 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
8040 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8041 	    sysctl_lb_stats, "A", "loopback statistics");
8042 
8043 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
8044 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8045 	    sysctl_meminfo, "A", "memory regions");
8046 
8047 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
8048 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8049 	    chip_id(sc) >= CHELSIO_T7 ? sysctl_mps_tcam_t7 :
8050 	    (chip_id(sc) >= CHELSIO_T6 ? sysctl_mps_tcam_t6 : sysctl_mps_tcam),
8051 	    "A", "MPS TCAM entries");
8052 
8053 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
8054 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8055 	    sysctl_path_mtus, "A", "path MTUs");
8056 
8057 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
8058 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8059 	    sysctl_pm_stats, "A", "PM statistics");
8060 
8061 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
8062 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8063 	    sysctl_rdma_stats, "A", "RDMA statistics");
8064 
8065 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
8066 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8067 	    sysctl_tcp_stats, "A", "TCP statistics");
8068 
8069 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
8070 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8071 	    sysctl_tids, "A", "TID information");
8072 
8073 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
8074 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8075 	    sysctl_tp_err_stats, "A", "TP error statistics");
8076 
8077 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
8078 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8079 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
8080 
8081 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
8082 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8083 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
8084 
8085 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
8086 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8087 	    sysctl_tp_la, "A", "TP logic analyzer");
8088 
8089 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
8090 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8091 	    sysctl_tx_rate, "A", "Tx rate");
8092 
8093 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
8094 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8095 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
8096 
8097 	if (chip_id(sc) >= CHELSIO_T5) {
8098 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
8099 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8100 		    sysctl_wcwr_stats, "A", "write combined work requests");
8101 	}
8102 
8103 #ifdef KERN_TLS
8104 	if (is_ktls(sc)) {
8105 		/*
8106 		 * dev.t4nex.0.tls.
8107 		 */
8108 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
8109 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
8110 		children = SYSCTL_CHILDREN(oid);
8111 
8112 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
8113 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
8114 		    "keys in work requests (1) or attempt to store TLS keys "
8115 		    "in card memory.");
8116 
8117 		if (is_t6(sc))
8118 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
8119 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
8120 			    "combine TCB field updates with TLS record work "
8121 			    "requests.");
8122 		else {
8123 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "short_records",
8124 			    CTLFLAG_RW, &sc->tlst.short_records, 0,
8125 			    "Use cipher-only mode for short records.");
8126 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "partial_ghash",
8127 			    CTLFLAG_RW, &sc->tlst.partial_ghash, 0,
8128 			    "Use partial GHASH for AES-GCM records.");
8129 		}
8130 	}
8131 #endif
8132 
8133 #ifdef TCP_OFFLOAD
8134 	if (is_offload(sc)) {
8135 		int i;
8136 		char s[4];
8137 
8138 		/*
8139 		 * dev.t4nex.X.toe.
8140 		 */
8141 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
8142 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
8143 		children = SYSCTL_CHILDREN(oid);
8144 
8145 		sc->tt.cong_algorithm = -1;
8146 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
8147 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
8148 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
8149 		    "3 = highspeed)");
8150 
8151 		sc->tt.sndbuf = -1;
8152 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
8153 		    &sc->tt.sndbuf, 0, "hardware send buffer");
8154 
8155 		sc->tt.ddp = 0;
8156 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
8157 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
8158 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
8159 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
8160 
8161 		sc->tt.rx_coalesce = -1;
8162 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
8163 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
8164 
8165 		sc->tt.tls = 1;
8166 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
8167 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
8168 		    "Inline TLS allowed");
8169 
8170 		sc->tt.tx_align = -1;
8171 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
8172 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
8173 
8174 		sc->tt.tx_zcopy = 0;
8175 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
8176 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
8177 		    "Enable zero-copy aio_write(2)");
8178 
8179 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
8180 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8181 		    "cop_managed_offloading", CTLFLAG_RW,
8182 		    &sc->tt.cop_managed_offloading, 0,
8183 		    "COP (Connection Offload Policy) controls all TOE offload");
8184 
8185 		sc->tt.autorcvbuf_inc = 16 * 1024;
8186 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
8187 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
8188 		    "autorcvbuf increment");
8189 
8190 		sc->tt.update_hc_on_pmtu_change = 1;
8191 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8192 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
8193 		    &sc->tt.update_hc_on_pmtu_change, 0,
8194 		    "Update hostcache entry if the PMTU changes");
8195 
8196 		sc->tt.iso = 1;
8197 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
8198 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
8199 
8200 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
8201 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8202 		    sysctl_tp_tick, "A", "TP timer tick (us)");
8203 
8204 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
8205 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
8206 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
8207 
8208 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
8209 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
8210 		    sysctl_tp_tick, "A", "DACK tick (us)");
8211 
8212 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
8213 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8214 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
8215 
8216 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
8217 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8218 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
8219 		    "Minimum retransmit interval (us)");
8220 
8221 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
8222 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8223 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
8224 		    "Maximum retransmit interval (us)");
8225 
8226 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
8227 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8228 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
8229 		    "Persist timer min (us)");
8230 
8231 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
8232 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8233 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
8234 		    "Persist timer max (us)");
8235 
8236 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
8237 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8238 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
8239 		    "Keepalive idle timer (us)");
8240 
8241 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
8242 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8243 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
8244 		    "Keepalive interval timer (us)");
8245 
8246 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
8247 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8248 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
8249 
8250 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
8251 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8252 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
8253 		    "FINWAIT2 timer (us)");
8254 
8255 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
8256 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8257 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
8258 		    "Number of SYN retransmissions before abort");
8259 
8260 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
8261 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8262 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
8263 		    "Number of retransmissions before abort");
8264 
8265 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
8266 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8267 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
8268 		    "Number of keepalive probes before abort");
8269 
8270 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
8271 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8272 		    "TOE retransmit backoffs");
8273 		children = SYSCTL_CHILDREN(oid);
8274 		for (i = 0; i < 16; i++) {
8275 			snprintf(s, sizeof(s), "%u", i);
8276 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
8277 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8278 			    i, sysctl_tp_backoff, "IU",
8279 			    "TOE retransmit backoff");
8280 		}
8281 	}
8282 #endif
8283 }
8284 
8285 void
8286 vi_sysctls(struct vi_info *vi)
8287 {
8288 	struct sysctl_ctx_list *ctx = &vi->ctx;
8289 	struct sysctl_oid *oid;
8290 	struct sysctl_oid_list *children;
8291 
8292 	/*
8293 	 * dev.v?(cxgbe|cxl).X.
8294 	 */
8295 	oid = device_get_sysctl_tree(vi->dev);
8296 	children = SYSCTL_CHILDREN(oid);
8297 
8298 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
8299 	    vi->viid, "VI identifer");
8300 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
8301 	    &vi->nrxq, 0, "# of rx queues");
8302 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
8303 	    &vi->ntxq, 0, "# of tx queues");
8304 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
8305 	    &vi->first_rxq, 0, "index of first rx queue");
8306 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
8307 	    &vi->first_txq, 0, "index of first tx queue");
8308 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
8309 	    vi->rss_base, "start of RSS indirection table");
8310 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
8311 	    vi->rss_size, "size of RSS indirection table");
8312 
8313 	if (IS_MAIN_VI(vi)) {
8314 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
8315 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8316 		    sysctl_noflowq, "IU",
8317 		    "Reserve queue 0 for non-flowid packets");
8318 	}
8319 
8320 	if (vi->adapter->flags & IS_VF) {
8321 		MPASS(vi->flags & TX_USES_VM_WR);
8322 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
8323 		    NULL, 1, "use VM work requests for transmit");
8324 	} else {
8325 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
8326 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8327 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
8328 	}
8329 
8330 #ifdef TCP_OFFLOAD
8331 	if (vi->nofldrxq != 0) {
8332 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
8333 		    &vi->nofldrxq, 0,
8334 		    "# of rx queues for offloaded TCP connections");
8335 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
8336 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
8337 		    "index of first TOE rx queue");
8338 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
8339 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8340 		    sysctl_holdoff_tmr_idx_ofld, "I",
8341 		    "holdoff timer index for TOE queues");
8342 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
8343 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8344 		    sysctl_holdoff_pktc_idx_ofld, "I",
8345 		    "holdoff packet counter index for TOE queues");
8346 	}
8347 #endif
8348 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
8349 	if (vi->nofldtxq != 0) {
8350 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
8351 		    &vi->nofldtxq, 0,
8352 		    "# of tx queues for TOE/ETHOFLD");
8353 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
8354 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
8355 		    "index of first TOE/ETHOFLD tx queue");
8356 	}
8357 #endif
8358 #ifdef DEV_NETMAP
8359 	if (vi->nnmrxq != 0) {
8360 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
8361 		    &vi->nnmrxq, 0, "# of netmap rx queues");
8362 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
8363 		    &vi->nnmtxq, 0, "# of netmap tx queues");
8364 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
8365 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
8366 		    "index of first netmap rx queue");
8367 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
8368 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
8369 		    "index of first netmap tx queue");
8370 	}
8371 #endif
8372 
8373 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8374 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8375 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8376 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8377 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8378 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8379 
8380 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8381 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8382 	    sysctl_qsize_rxq, "I", "rx queue size");
8383 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8384 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8385 	    sysctl_qsize_txq, "I", "tx queue size");
8386 }
8387 
8388 static void
8389 cxgbe_sysctls(struct port_info *pi)
8390 {
8391 	struct sysctl_ctx_list *ctx = &pi->ctx;
8392 	struct sysctl_oid *oid;
8393 	struct sysctl_oid_list *children, *children2;
8394 	struct adapter *sc = pi->adapter;
8395 	int i;
8396 	char name[16];
8397 	static char *tc_flags = {"\20\1USER"};
8398 
8399 	/*
8400 	 * dev.cxgbe.X.
8401 	 */
8402 	oid = device_get_sysctl_tree(pi->dev);
8403 	children = SYSCTL_CHILDREN(oid);
8404 
8405 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8406 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8407 	    sysctl_linkdnrc, "A", "reason why link is down");
8408 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8409 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8410 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8411 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8412 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8413 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8414 		    sysctl_btphy, "I", "PHY firmware version");
8415 	}
8416 
8417 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8418 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8419 	    sysctl_pause_settings, "A",
8420 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8421 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8422 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8423 	    "FEC in use on the link");
8424 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8425 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8426 	    sysctl_requested_fec, "A",
8427 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8428 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8429 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8430 	    "FEC recommended by the cable/transceiver");
8431 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8432 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8433 	    sysctl_autoneg, "I",
8434 	    "autonegotiation (-1 = not supported)");
8435 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8436 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8437 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8438 
8439 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8440 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8441 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8442 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8443 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8444 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8445 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8446 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8447 
8448 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8449 	    port_top_speed(pi), "max speed (in Gbps)");
8450 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8451 	    pi->mps_bg_map, "MPS buffer group map");
8452 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8453 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8454 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8455 	    pi->tx_chan, "TP tx c-channel");
8456 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8457 	    pi->rx_chan, "TP rx c-channel");
8458 
8459 	if (sc->flags & IS_VF)
8460 		return;
8461 
8462 	/*
8463 	 * dev.(cxgbe|cxl).X.tc.
8464 	 */
8465 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8466 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8467 	    "Tx scheduler traffic classes (cl_rl)");
8468 	children2 = SYSCTL_CHILDREN(oid);
8469 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8470 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8471 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8472 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8473 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8474 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8475 	for (i = 0; i < sc->params.nsched_cls; i++) {
8476 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8477 
8478 		snprintf(name, sizeof(name), "%d", i);
8479 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8480 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8481 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8482 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8483 		    CTLFLAG_RD, &tc->state, 0, "current state");
8484 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8485 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8486 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8487 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8488 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8489 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8490 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8491 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8492 		    "traffic class parameters");
8493 	}
8494 
8495 	/*
8496 	 * dev.cxgbe.X.stats.
8497 	 */
8498 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8499 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8500 	children = SYSCTL_CHILDREN(oid);
8501 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8502 	    &pi->tx_parse_error, 0,
8503 	    "# of tx packets with invalid length or # of segments");
8504 
8505 #define T4_LBSTAT(name, stat, desc) do { \
8506 	if (sc->params.tp.lb_mode) { \
8507 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8508 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, \
8509 		    A_MPS_PORT_STAT_##stat##_L, \
8510 		    sysctl_handle_t4_portstat64, "QU", desc); \
8511 	} else { \
8512 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8513 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8514 		    t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8515 		    sysctl_handle_t4_reg64, "QU", desc); \
8516 	} \
8517 } while (0)
8518 
8519 	T4_LBSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8520 	T4_LBSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8521 	T4_LBSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8522 	T4_LBSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8523 	T4_LBSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8524 	T4_LBSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8525 	T4_LBSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8526 	T4_LBSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8527 	T4_LBSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8528 	T4_LBSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8529 	T4_LBSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8530 	T4_LBSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8531 	T4_LBSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8532 	T4_LBSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8533 	T4_LBSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8534 	T4_LBSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8535 	T4_LBSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8536 	T4_LBSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8537 	T4_LBSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8538 	T4_LBSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8539 	T4_LBSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8540 	T4_LBSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8541 	T4_LBSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8542 
8543 	T4_LBSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8544 	T4_LBSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8545 	T4_LBSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8546 	T4_LBSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8547 	T4_LBSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8548 	T4_LBSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8549 	T4_LBSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8550 	if (is_t6(sc)) {
8551 		/* Read from port_stats and may be stale by up to 1s */
8552 		SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "rx_fcs_err",
8553 		    CTLFLAG_RD, &pi->stats.rx_fcs_err,
8554 		    "# of frames received with bad FCS since last link up");
8555 	} else {
8556 		T4_LBSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8557 		    "# of frames received with bad FCS");
8558 	}
8559 	T4_LBSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8560 	T4_LBSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8561 	T4_LBSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8562 	T4_LBSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8563 	T4_LBSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8564 	T4_LBSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8565 	T4_LBSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8566 	T4_LBSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8567 	T4_LBSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8568 	T4_LBSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8569 	T4_LBSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8570 	T4_LBSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8571 	T4_LBSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8572 	T4_LBSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8573 	T4_LBSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8574 	T4_LBSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8575 	T4_LBSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8576 	T4_LBSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8577 	T4_LBSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8578 #undef T4_LBSTAT
8579 
8580 #define T4_REGSTAT(name, stat, desc) do { \
8581 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8582 	    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8583 	    A_MPS_STAT_##stat##_L, sysctl_handle_t4_reg64, "QU", desc); \
8584 } while (0)
8585 
8586 	if (pi->mps_bg_map & 1) {
8587 		T4_REGSTAT(rx_ovflow0, RX_BG_0_MAC_DROP_FRAME,
8588 		    "# drops due to buffer-group 0 overflows");
8589 		T4_REGSTAT(rx_trunc0, RX_BG_0_MAC_TRUNC_FRAME,
8590 		    "# of buffer-group 0 truncated packets");
8591 	}
8592 	if (pi->mps_bg_map & 2) {
8593 		T4_REGSTAT(rx_ovflow1, RX_BG_1_MAC_DROP_FRAME,
8594 		    "# drops due to buffer-group 1 overflows");
8595 		T4_REGSTAT(rx_trunc1, RX_BG_1_MAC_TRUNC_FRAME,
8596 		    "# of buffer-group 1 truncated packets");
8597 	}
8598 	if (pi->mps_bg_map & 4) {
8599 		T4_REGSTAT(rx_ovflow2, RX_BG_2_MAC_DROP_FRAME,
8600 		    "# drops due to buffer-group 2 overflows");
8601 		T4_REGSTAT(rx_trunc2, RX_BG_2_MAC_TRUNC_FRAME,
8602 		    "# of buffer-group 2 truncated packets");
8603 	}
8604 	if (pi->mps_bg_map & 8) {
8605 		T4_REGSTAT(rx_ovflow3, RX_BG_3_MAC_DROP_FRAME,
8606 		    "# drops due to buffer-group 3 overflows");
8607 		T4_REGSTAT(rx_trunc3, RX_BG_3_MAC_TRUNC_FRAME,
8608 		    "# of buffer-group 3 truncated packets");
8609 	}
8610 #undef T4_REGSTAT
8611 }
8612 
8613 static int
8614 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8615 {
8616 	int rc, *i, space = 0;
8617 	struct sbuf sb;
8618 
8619 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8620 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8621 		if (space)
8622 			sbuf_printf(&sb, " ");
8623 		sbuf_printf(&sb, "%d", *i);
8624 		space = 1;
8625 	}
8626 	rc = sbuf_finish(&sb);
8627 	sbuf_delete(&sb);
8628 	return (rc);
8629 }
8630 
8631 static int
8632 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8633 {
8634 	int rc;
8635 	struct sbuf *sb;
8636 
8637 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8638 	if (sb == NULL)
8639 		return (ENOMEM);
8640 
8641 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8642 	rc = sbuf_finish(sb);
8643 	sbuf_delete(sb);
8644 
8645 	return (rc);
8646 }
8647 
8648 static int
8649 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8650 {
8651 	int rc;
8652 	struct sbuf *sb;
8653 
8654 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8655 	if (sb == NULL)
8656 		return (ENOMEM);
8657 
8658 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8659 	rc = sbuf_finish(sb);
8660 	sbuf_delete(sb);
8661 
8662 	return (rc);
8663 }
8664 
8665 static int
8666 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8667 {
8668 	struct port_info *pi = arg1;
8669 	int op = arg2;
8670 	struct adapter *sc = pi->adapter;
8671 	u_int v;
8672 	int rc;
8673 
8674 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8675 	if (rc)
8676 		return (rc);
8677 	if (!hw_all_ok(sc))
8678 		rc = ENXIO;
8679 	else {
8680 		/* XXX: magic numbers */
8681 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8682 		    op ? 0x20 : 0xc820, &v);
8683 	}
8684 	end_synchronized_op(sc, 0);
8685 	if (rc)
8686 		return (rc);
8687 	if (op == 0)
8688 		v /= 256;
8689 
8690 	rc = sysctl_handle_int(oidp, &v, 0, req);
8691 	return (rc);
8692 }
8693 
8694 static int
8695 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8696 {
8697 	struct vi_info *vi = arg1;
8698 	int rc, val;
8699 
8700 	val = vi->rsrv_noflowq;
8701 	rc = sysctl_handle_int(oidp, &val, 0, req);
8702 	if (rc != 0 || req->newptr == NULL)
8703 		return (rc);
8704 
8705 	if ((val >= 1) && (vi->ntxq > 1))
8706 		vi->rsrv_noflowq = 1;
8707 	else
8708 		vi->rsrv_noflowq = 0;
8709 
8710 	return (rc);
8711 }
8712 
8713 static int
8714 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8715 {
8716 	struct vi_info *vi = arg1;
8717 	struct adapter *sc = vi->adapter;
8718 	int rc, val, i;
8719 
8720 	MPASS(!(sc->flags & IS_VF));
8721 
8722 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8723 	rc = sysctl_handle_int(oidp, &val, 0, req);
8724 	if (rc != 0 || req->newptr == NULL)
8725 		return (rc);
8726 
8727 	if (val != 0 && val != 1)
8728 		return (EINVAL);
8729 
8730 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8731 	    "t4txvm");
8732 	if (rc)
8733 		return (rc);
8734 	if (!hw_all_ok(sc))
8735 		rc = ENXIO;
8736 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8737 		/*
8738 		 * We don't want parse_pkt to run with one setting (VF or PF)
8739 		 * and then eth_tx to see a different setting but still use
8740 		 * stale information calculated by parse_pkt.
8741 		 */
8742 		rc = EBUSY;
8743 	} else {
8744 		struct port_info *pi = vi->pi;
8745 		struct sge_txq *txq;
8746 		uint32_t ctrl0;
8747 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8748 
8749 		if (val) {
8750 			vi->flags |= TX_USES_VM_WR;
8751 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8752 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8753 			    V_TXPKT_INTF(pi->hw_port));
8754 			if (!(sc->flags & IS_VF))
8755 				npkt--;
8756 		} else {
8757 			vi->flags &= ~TX_USES_VM_WR;
8758 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8759 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8760 			    V_TXPKT_INTF(pi->hw_port) | V_TXPKT_PF(sc->pf) |
8761 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8762 		}
8763 		for_each_txq(vi, i, txq) {
8764 			txq->cpl_ctrl0 = ctrl0;
8765 			txq->txp.max_npkt = npkt;
8766 		}
8767 	}
8768 	end_synchronized_op(sc, LOCK_HELD);
8769 	return (rc);
8770 }
8771 
8772 static int
8773 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8774 {
8775 	struct vi_info *vi = arg1;
8776 	struct adapter *sc = vi->adapter;
8777 	int idx, rc, i;
8778 	struct sge_rxq *rxq;
8779 	uint8_t v;
8780 
8781 	idx = vi->tmr_idx;
8782 
8783 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8784 	if (rc != 0 || req->newptr == NULL)
8785 		return (rc);
8786 
8787 	if (idx < 0 || idx >= SGE_NTIMERS)
8788 		return (EINVAL);
8789 
8790 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8791 	    "t4tmr");
8792 	if (rc)
8793 		return (rc);
8794 
8795 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8796 	for_each_rxq(vi, i, rxq) {
8797 #ifdef atomic_store_rel_8
8798 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8799 #else
8800 		rxq->iq.intr_params = v;
8801 #endif
8802 	}
8803 	vi->tmr_idx = idx;
8804 
8805 	end_synchronized_op(sc, LOCK_HELD);
8806 	return (0);
8807 }
8808 
8809 static int
8810 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8811 {
8812 	struct vi_info *vi = arg1;
8813 	struct adapter *sc = vi->adapter;
8814 	int idx, rc;
8815 
8816 	idx = vi->pktc_idx;
8817 
8818 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8819 	if (rc != 0 || req->newptr == NULL)
8820 		return (rc);
8821 
8822 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8823 		return (EINVAL);
8824 
8825 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8826 	    "t4pktc");
8827 	if (rc)
8828 		return (rc);
8829 
8830 	if (vi->flags & VI_INIT_DONE)
8831 		rc = EBUSY; /* cannot be changed once the queues are created */
8832 	else
8833 		vi->pktc_idx = idx;
8834 
8835 	end_synchronized_op(sc, LOCK_HELD);
8836 	return (rc);
8837 }
8838 
8839 static int
8840 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8841 {
8842 	struct vi_info *vi = arg1;
8843 	struct adapter *sc = vi->adapter;
8844 	int qsize, rc;
8845 
8846 	qsize = vi->qsize_rxq;
8847 
8848 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8849 	if (rc != 0 || req->newptr == NULL)
8850 		return (rc);
8851 
8852 	if (qsize < 128 || (qsize & 7))
8853 		return (EINVAL);
8854 
8855 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8856 	    "t4rxqs");
8857 	if (rc)
8858 		return (rc);
8859 
8860 	if (vi->flags & VI_INIT_DONE)
8861 		rc = EBUSY; /* cannot be changed once the queues are created */
8862 	else
8863 		vi->qsize_rxq = qsize;
8864 
8865 	end_synchronized_op(sc, LOCK_HELD);
8866 	return (rc);
8867 }
8868 
8869 static int
8870 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8871 {
8872 	struct vi_info *vi = arg1;
8873 	struct adapter *sc = vi->adapter;
8874 	int qsize, rc;
8875 
8876 	qsize = vi->qsize_txq;
8877 
8878 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8879 	if (rc != 0 || req->newptr == NULL)
8880 		return (rc);
8881 
8882 	if (qsize < 128 || qsize > 65536)
8883 		return (EINVAL);
8884 
8885 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8886 	    "t4txqs");
8887 	if (rc)
8888 		return (rc);
8889 
8890 	if (vi->flags & VI_INIT_DONE)
8891 		rc = EBUSY; /* cannot be changed once the queues are created */
8892 	else
8893 		vi->qsize_txq = qsize;
8894 
8895 	end_synchronized_op(sc, LOCK_HELD);
8896 	return (rc);
8897 }
8898 
8899 static int
8900 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8901 {
8902 	struct port_info *pi = arg1;
8903 	struct adapter *sc = pi->adapter;
8904 	struct link_config *lc = &pi->link_cfg;
8905 	int rc;
8906 
8907 	if (req->newptr == NULL) {
8908 		struct sbuf *sb;
8909 		static char *bits = "\20\1RX\2TX\3AUTO";
8910 
8911 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8912 		if (sb == NULL)
8913 			return (ENOMEM);
8914 
8915 		if (lc->link_ok) {
8916 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8917 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8918 		} else {
8919 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8920 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8921 		}
8922 		rc = sbuf_finish(sb);
8923 		sbuf_delete(sb);
8924 	} else {
8925 		char s[2];
8926 		int n;
8927 
8928 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8929 		    PAUSE_AUTONEG));
8930 		s[1] = 0;
8931 
8932 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8933 		if (rc != 0)
8934 			return(rc);
8935 
8936 		if (s[1] != 0)
8937 			return (EINVAL);
8938 		if (s[0] < '0' || s[0] > '9')
8939 			return (EINVAL);	/* not a number */
8940 		n = s[0] - '0';
8941 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8942 			return (EINVAL);	/* some other bit is set too */
8943 
8944 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8945 		    "t4PAUSE");
8946 		if (rc)
8947 			return (rc);
8948 		if (hw_all_ok(sc)) {
8949 			PORT_LOCK(pi);
8950 			lc->requested_fc = n;
8951 			fixup_link_config(pi);
8952 			if (pi->up_vis > 0)
8953 				rc = apply_link_config(pi);
8954 			set_current_media(pi);
8955 			PORT_UNLOCK(pi);
8956 		}
8957 		end_synchronized_op(sc, 0);
8958 	}
8959 
8960 	return (rc);
8961 }
8962 
8963 static int
8964 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8965 {
8966 	struct port_info *pi = arg1;
8967 	struct link_config *lc = &pi->link_cfg;
8968 	int rc;
8969 	struct sbuf *sb;
8970 
8971 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8972 	if (sb == NULL)
8973 		return (ENOMEM);
8974 	if (lc->link_ok)
8975 		sbuf_printf(sb, "%b", lc->fec, t4_fec_bits);
8976 	else
8977 		sbuf_printf(sb, "no link");
8978 	rc = sbuf_finish(sb);
8979 	sbuf_delete(sb);
8980 
8981 	return (rc);
8982 }
8983 
8984 static int
8985 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8986 {
8987 	struct port_info *pi = arg1;
8988 	struct adapter *sc = pi->adapter;
8989 	struct link_config *lc = &pi->link_cfg;
8990 	int rc;
8991 	int8_t old;
8992 
8993 	if (req->newptr == NULL) {
8994 		struct sbuf *sb;
8995 
8996 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8997 		if (sb == NULL)
8998 			return (ENOMEM);
8999 
9000 		sbuf_printf(sb, "%b", lc->requested_fec, t4_fec_bits);
9001 		rc = sbuf_finish(sb);
9002 		sbuf_delete(sb);
9003 	} else {
9004 		char s[8];
9005 		int n;
9006 
9007 		snprintf(s, sizeof(s), "%d",
9008 		    lc->requested_fec == FEC_AUTO ? -1 :
9009 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
9010 
9011 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9012 		if (rc != 0)
9013 			return(rc);
9014 
9015 		n = strtol(&s[0], NULL, 0);
9016 		if (n < 0 || n & FEC_AUTO)
9017 			n = FEC_AUTO;
9018 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
9019 			return (EINVAL);/* some other bit is set too */
9020 
9021 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9022 		    "t4reqf");
9023 		if (rc)
9024 			return (rc);
9025 		PORT_LOCK(pi);
9026 		old = lc->requested_fec;
9027 		if (n == FEC_AUTO)
9028 			lc->requested_fec = FEC_AUTO;
9029 		else if (n == 0 || n == FEC_NONE)
9030 			lc->requested_fec = FEC_NONE;
9031 		else {
9032 			if ((lc->pcaps |
9033 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
9034 			    lc->pcaps) {
9035 				rc = ENOTSUP;
9036 				goto done;
9037 			}
9038 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
9039 			    FEC_MODULE);
9040 		}
9041 		if (hw_all_ok(sc)) {
9042 			fixup_link_config(pi);
9043 			if (pi->up_vis > 0) {
9044 				rc = apply_link_config(pi);
9045 				if (rc != 0) {
9046 					lc->requested_fec = old;
9047 					if (rc == FW_EPROTO)
9048 						rc = ENOTSUP;
9049 				}
9050 			}
9051 		}
9052 done:
9053 		PORT_UNLOCK(pi);
9054 		end_synchronized_op(sc, 0);
9055 	}
9056 
9057 	return (rc);
9058 }
9059 
9060 static int
9061 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
9062 {
9063 	struct port_info *pi = arg1;
9064 	struct adapter *sc = pi->adapter;
9065 	struct link_config *lc = &pi->link_cfg;
9066 	int rc;
9067 	int8_t fec;
9068 	struct sbuf *sb;
9069 
9070 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9071 	if (sb == NULL)
9072 		return (ENOMEM);
9073 
9074 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
9075 		rc = EBUSY;
9076 		goto done;
9077 	}
9078 	if (!hw_all_ok(sc)) {
9079 		rc = ENXIO;
9080 		goto done;
9081 	}
9082 	PORT_LOCK(pi);
9083 	if (pi->up_vis == 0) {
9084 		/*
9085 		 * If all the interfaces are administratively down the firmware
9086 		 * does not report transceiver changes.  Refresh port info here.
9087 		 * This is the only reason we have a synchronized op in this
9088 		 * function.  Just PORT_LOCK would have been enough otherwise.
9089 		 */
9090 		t4_update_port_info(pi);
9091 	}
9092 
9093 	fec = lc->fec_hint;
9094 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
9095 	    !fec_supported(lc->pcaps)) {
9096 		PORT_UNLOCK(pi);
9097 		sbuf_printf(sb, "n/a");
9098 	} else {
9099 		if (fec == 0)
9100 			fec = FEC_NONE;
9101 		PORT_UNLOCK(pi);
9102 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, t4_fec_bits);
9103 	}
9104 	rc = sbuf_finish(sb);
9105 done:
9106 	sbuf_delete(sb);
9107 	end_synchronized_op(sc, 0);
9108 
9109 	return (rc);
9110 }
9111 
9112 static int
9113 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
9114 {
9115 	struct port_info *pi = arg1;
9116 	struct adapter *sc = pi->adapter;
9117 	struct link_config *lc = &pi->link_cfg;
9118 	int rc, val;
9119 
9120 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
9121 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
9122 	else
9123 		val = -1;
9124 	rc = sysctl_handle_int(oidp, &val, 0, req);
9125 	if (rc != 0 || req->newptr == NULL)
9126 		return (rc);
9127 	if (val == 0)
9128 		val = AUTONEG_DISABLE;
9129 	else if (val == 1)
9130 		val = AUTONEG_ENABLE;
9131 	else
9132 		val = AUTONEG_AUTO;
9133 
9134 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9135 	    "t4aneg");
9136 	if (rc)
9137 		return (rc);
9138 	PORT_LOCK(pi);
9139 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
9140 		rc = ENOTSUP;
9141 		goto done;
9142 	}
9143 	lc->requested_aneg = val;
9144 	if (hw_all_ok(sc)) {
9145 		fixup_link_config(pi);
9146 		if (pi->up_vis > 0)
9147 			rc = apply_link_config(pi);
9148 		set_current_media(pi);
9149 	}
9150 done:
9151 	PORT_UNLOCK(pi);
9152 	end_synchronized_op(sc, 0);
9153 	return (rc);
9154 }
9155 
9156 static int
9157 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
9158 {
9159 	struct port_info *pi = arg1;
9160 	struct adapter *sc = pi->adapter;
9161 	struct link_config *lc = &pi->link_cfg;
9162 	int rc, val;
9163 
9164 	val = lc->force_fec;
9165 	MPASS(val >= -1 && val <= 1);
9166 	rc = sysctl_handle_int(oidp, &val, 0, req);
9167 	if (rc != 0 || req->newptr == NULL)
9168 		return (rc);
9169 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
9170 		return (ENOTSUP);
9171 	if (val < -1 || val > 1)
9172 		return (EINVAL);
9173 
9174 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
9175 	if (rc)
9176 		return (rc);
9177 	PORT_LOCK(pi);
9178 	lc->force_fec = val;
9179 	if (hw_all_ok(sc)) {
9180 		fixup_link_config(pi);
9181 		if (pi->up_vis > 0)
9182 			rc = apply_link_config(pi);
9183 	}
9184 	PORT_UNLOCK(pi);
9185 	end_synchronized_op(sc, 0);
9186 	return (rc);
9187 }
9188 
9189 static int
9190 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
9191 {
9192 	struct adapter *sc = arg1;
9193 	int rc, reg = arg2;
9194 	uint64_t val;
9195 
9196 	mtx_lock(&sc->reg_lock);
9197 	if (hw_off_limits(sc))
9198 		rc = ENXIO;
9199 	else {
9200 		rc = 0;
9201 		val = t4_read_reg64(sc, reg);
9202 	}
9203 	mtx_unlock(&sc->reg_lock);
9204 	if (rc == 0)
9205 		rc = sysctl_handle_64(oidp, &val, 0, req);
9206 	return (rc);
9207 }
9208 
9209 static int
9210 sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS)
9211 {
9212 	struct port_info *pi = arg1;
9213 	struct adapter *sc = pi->adapter;
9214 	int rc, i, reg = arg2;
9215 	uint64_t val;
9216 
9217 	mtx_lock(&sc->reg_lock);
9218 	if (hw_off_limits(sc))
9219 		rc = ENXIO;
9220 	else {
9221 		val = 0;
9222 		for (i = 0; i < sc->params.tp.lb_nchan; i++) {
9223 			val += t4_read_reg64(sc,
9224 			    t4_port_reg(sc, pi->tx_chan + i, reg));
9225 		}
9226 		rc = 0;
9227 	}
9228 	mtx_unlock(&sc->reg_lock);
9229 	if (rc == 0)
9230 		rc = sysctl_handle_64(oidp, &val, 0, req);
9231 	return (rc);
9232 }
9233 
9234 static int
9235 sysctl_temperature(SYSCTL_HANDLER_ARGS)
9236 {
9237 	struct adapter *sc = arg1;
9238 	int rc, t;
9239 	uint32_t param, val;
9240 
9241 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
9242 	if (rc)
9243 		return (rc);
9244 	if (!hw_all_ok(sc))
9245 		rc = ENXIO;
9246 	else {
9247 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9248 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9249 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
9250 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9251 	}
9252 	end_synchronized_op(sc, 0);
9253 	if (rc)
9254 		return (rc);
9255 
9256 	/* unknown is returned as 0 but we display -1 in that case */
9257 	t = val == 0 ? -1 : val;
9258 
9259 	rc = sysctl_handle_int(oidp, &t, 0, req);
9260 	return (rc);
9261 }
9262 
9263 static int
9264 sysctl_vdd(SYSCTL_HANDLER_ARGS)
9265 {
9266 	struct adapter *sc = arg1;
9267 	int rc;
9268 	uint32_t param, val;
9269 
9270 	if (sc->params.core_vdd == 0) {
9271 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9272 		    "t4vdd");
9273 		if (rc)
9274 			return (rc);
9275 		if (!hw_all_ok(sc))
9276 			rc = ENXIO;
9277 		else {
9278 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9279 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9280 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
9281 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
9282 			    &param, &val);
9283 		}
9284 		end_synchronized_op(sc, 0);
9285 		if (rc)
9286 			return (rc);
9287 		sc->params.core_vdd = val;
9288 	}
9289 
9290 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
9291 }
9292 
9293 static int
9294 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
9295 {
9296 	struct adapter *sc = arg1;
9297 	int rc, v;
9298 	uint32_t param, val;
9299 
9300 	v = sc->sensor_resets;
9301 	rc = sysctl_handle_int(oidp, &v, 0, req);
9302 	if (rc != 0 || req->newptr == NULL || v <= 0)
9303 		return (rc);
9304 
9305 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
9306 	    chip_id(sc) < CHELSIO_T5)
9307 		return (ENOTSUP);
9308 
9309 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
9310 	if (rc)
9311 		return (rc);
9312 	if (!hw_all_ok(sc))
9313 		rc = ENXIO;
9314 	else {
9315 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9316 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9317 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
9318 		val = 1;
9319 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9320 	}
9321 	end_synchronized_op(sc, 0);
9322 	if (rc == 0)
9323 		sc->sensor_resets++;
9324 	return (rc);
9325 }
9326 
9327 static int
9328 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
9329 {
9330 	struct adapter *sc = arg1;
9331 	struct sbuf *sb;
9332 	int rc;
9333 	uint32_t param, val;
9334 	uint8_t coreid = (uint8_t)arg2;
9335 
9336 	KASSERT(coreid < sc->params.ncores,
9337 	    ("%s: bad coreid %u\n", __func__, coreid));
9338 
9339 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
9340 	if (rc)
9341 		return (rc);
9342 	if (!hw_all_ok(sc))
9343 		rc = ENXIO;
9344 	else {
9345 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9346 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD) |
9347 		    V_FW_PARAMS_PARAM_Y(coreid);
9348 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9349 	}
9350 	end_synchronized_op(sc, 0);
9351 	if (rc)
9352 		return (rc);
9353 
9354 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9355 	if (sb == NULL)
9356 		return (ENOMEM);
9357 
9358 	if (val == 0xffffffff) {
9359 		/* Only debug and custom firmwares report load averages. */
9360 		sbuf_printf(sb, "not available");
9361 	} else {
9362 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
9363 		    (val >> 16) & 0xff);
9364 	}
9365 	rc = sbuf_finish(sb);
9366 	sbuf_delete(sb);
9367 
9368 	return (rc);
9369 }
9370 
9371 static int
9372 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
9373 {
9374 	struct adapter *sc = arg1;
9375 	struct sbuf *sb;
9376 	int rc, i;
9377 	uint16_t incr[NMTUS][NCCTRL_WIN];
9378 	static const char *dec_fac[] = {
9379 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
9380 		"0.9375"
9381 	};
9382 
9383 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9384 	if (sb == NULL)
9385 		return (ENOMEM);
9386 
9387 	rc = 0;
9388 	mtx_lock(&sc->reg_lock);
9389 	if (hw_off_limits(sc))
9390 		rc = ENXIO;
9391 	else
9392 		t4_read_cong_tbl(sc, incr);
9393 	mtx_unlock(&sc->reg_lock);
9394 	if (rc)
9395 		goto done;
9396 
9397 	for (i = 0; i < NCCTRL_WIN; ++i) {
9398 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
9399 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
9400 		    incr[5][i], incr[6][i], incr[7][i]);
9401 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
9402 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
9403 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
9404 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
9405 	}
9406 
9407 	rc = sbuf_finish(sb);
9408 done:
9409 	sbuf_delete(sb);
9410 	return (rc);
9411 }
9412 
9413 static int
9414 sysctl_cim_ibq(SYSCTL_HANDLER_ARGS)
9415 {
9416 	struct adapter *sc = arg1;
9417 	struct sbuf *sb;
9418 	int rc, i, n, qid, coreid;
9419 	uint32_t *buf, *p;
9420 
9421 	qid = arg2 & 0xffff;
9422 	coreid = arg2 >> 16;
9423 
9424 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_ibq,
9425 	    ("%s: bad ibq qid %d\n", __func__, qid));
9426 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9427 	    ("%s: bad coreid %d\n", __func__, coreid));
9428 
9429 	n = 4 * CIM_IBQ_SIZE;
9430 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9431 	mtx_lock(&sc->reg_lock);
9432 	if (hw_off_limits(sc))
9433 		rc = -ENXIO;
9434 	else
9435 		rc = t4_read_cim_ibq_core(sc, coreid, qid, buf, n);
9436 	mtx_unlock(&sc->reg_lock);
9437 	if (rc < 0) {
9438 		rc = -rc;
9439 		goto done;
9440 	}
9441 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9442 
9443 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9444 	if (sb == NULL) {
9445 		rc = ENOMEM;
9446 		goto done;
9447 	}
9448 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9449 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9450 		    p[2], p[3]);
9451 	rc = sbuf_finish(sb);
9452 	sbuf_delete(sb);
9453 done:
9454 	free(buf, M_CXGBE);
9455 	return (rc);
9456 }
9457 
9458 static int
9459 sysctl_cim_obq(SYSCTL_HANDLER_ARGS)
9460 {
9461 	struct adapter *sc = arg1;
9462 	struct sbuf *sb;
9463 	int rc, i, n, qid, coreid;
9464 	uint32_t *buf, *p;
9465 
9466 	qid = arg2 & 0xffff;
9467 	coreid = arg2 >> 16;
9468 
9469 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_obq,
9470 	    ("%s: bad obq qid %d\n", __func__, qid));
9471 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9472 	    ("%s: bad coreid %d\n", __func__, coreid));
9473 
9474 	n = 6 * CIM_OBQ_SIZE * 4;
9475 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9476 	mtx_lock(&sc->reg_lock);
9477 	if (hw_off_limits(sc))
9478 		rc = -ENXIO;
9479 	else
9480 		rc = t4_read_cim_obq_core(sc, coreid, qid, buf, n);
9481 	mtx_unlock(&sc->reg_lock);
9482 	if (rc < 0) {
9483 		rc = -rc;
9484 		goto done;
9485 	}
9486 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9487 
9488 	rc = sysctl_wire_old_buffer(req, 0);
9489 	if (rc != 0)
9490 		goto done;
9491 
9492 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9493 	if (sb == NULL) {
9494 		rc = ENOMEM;
9495 		goto done;
9496 	}
9497 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9498 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9499 		    p[2], p[3]);
9500 	rc = sbuf_finish(sb);
9501 	sbuf_delete(sb);
9502 done:
9503 	free(buf, M_CXGBE);
9504 	return (rc);
9505 }
9506 
9507 static void
9508 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9509 {
9510 	uint32_t *p;
9511 
9512 	sbuf_printf(sb, "Status   Data      PC%s",
9513 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9514 	    "     LS0Stat  LS0Addr             LS0Data");
9515 
9516 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9517 		if (cfg & F_UPDBGLACAPTPCONLY) {
9518 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9519 			    p[6], p[7]);
9520 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9521 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9522 			    p[4] & 0xff, p[5] >> 8);
9523 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9524 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9525 			    p[1] & 0xf, p[2] >> 4);
9526 		} else {
9527 			sbuf_printf(sb,
9528 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9529 			    "%08x%08x%08x%08x",
9530 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9531 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9532 			    p[6], p[7]);
9533 		}
9534 	}
9535 }
9536 
9537 static void
9538 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9539 {
9540 	uint32_t *p;
9541 
9542 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9543 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9544 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9545 
9546 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9547 		if (cfg & F_UPDBGLACAPTPCONLY) {
9548 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9549 			    p[3] & 0xff, p[2], p[1], p[0]);
9550 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9551 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9552 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9553 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9554 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9555 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9556 			    p[6] >> 16);
9557 		} else {
9558 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9559 			    "%08x %08x %08x %08x %08x %08x",
9560 			    (p[9] >> 16) & 0xff,
9561 			    p[9] & 0xffff, p[8] >> 16,
9562 			    p[8] & 0xffff, p[7] >> 16,
9563 			    p[7] & 0xffff, p[6] >> 16,
9564 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9565 		}
9566 	}
9567 }
9568 
9569 static int
9570 sbuf_cim_la(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
9571 {
9572 	uint32_t cfg, *buf;
9573 	int rc;
9574 
9575 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9576 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9577 	    M_ZERO | flags);
9578 	if (buf == NULL)
9579 		return (ENOMEM);
9580 
9581 	mtx_lock(&sc->reg_lock);
9582 	if (hw_off_limits(sc))
9583 		rc = ENXIO;
9584 	else {
9585 		rc = -t4_cim_read_core(sc, 1, coreid, A_UP_UP_DBG_LA_CFG, 1,
9586 		    &cfg);
9587 		if (rc == 0)
9588 			rc = -t4_cim_read_la_core(sc, coreid, buf, NULL);
9589 	}
9590 	mtx_unlock(&sc->reg_lock);
9591 	if (rc == 0) {
9592 		if (chip_id(sc) < CHELSIO_T6)
9593 			sbuf_cim_la4(sc, sb, buf, cfg);
9594 		else
9595 			sbuf_cim_la6(sc, sb, buf, cfg);
9596 	}
9597 	free(buf, M_CXGBE);
9598 	return (rc);
9599 }
9600 
9601 static int
9602 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9603 {
9604 	struct adapter *sc = arg1;
9605 	int coreid = arg2;
9606 	struct sbuf *sb;
9607 	int rc;
9608 
9609 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9610 	if (sb == NULL)
9611 		return (ENOMEM);
9612 
9613 	rc = sbuf_cim_la(sc, coreid, sb, M_WAITOK);
9614 	if (rc == 0)
9615 		rc = sbuf_finish(sb);
9616 	sbuf_delete(sb);
9617 	return (rc);
9618 }
9619 
9620 static void
9621 dump_cim_regs(struct adapter *sc)
9622 {
9623 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9624 	    device_get_nameunit(sc->dev),
9625 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9626 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9627 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9628 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9629 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9630 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9631 	    device_get_nameunit(sc->dev),
9632 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9633 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9634 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9635 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9636 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9637 }
9638 
9639 static void
9640 dump_cimla(struct adapter *sc)
9641 {
9642 	struct sbuf sb;
9643 	int rc;
9644 
9645 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9646 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9647 		    device_get_nameunit(sc->dev));
9648 		return;
9649 	}
9650 	rc = sbuf_cim_la(sc, 0, &sb, M_WAITOK);
9651 	if (rc == 0) {
9652 		rc = sbuf_finish(&sb);
9653 		if (rc == 0) {
9654 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9655 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9656 		}
9657 	}
9658 	sbuf_delete(&sb);
9659 }
9660 
9661 void
9662 t4_os_cim_err(struct adapter *sc)
9663 {
9664 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9665 }
9666 
9667 static int
9668 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9669 {
9670 	struct adapter *sc = arg1;
9671 	u_int i;
9672 	struct sbuf *sb;
9673 	uint32_t *buf, *p;
9674 	int rc;
9675 
9676 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9677 	if (sb == NULL)
9678 		return (ENOMEM);
9679 
9680 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9681 	    M_ZERO | M_WAITOK);
9682 
9683 	rc = 0;
9684 	mtx_lock(&sc->reg_lock);
9685 	if (hw_off_limits(sc))
9686 		rc = ENXIO;
9687 	else
9688 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9689 	mtx_unlock(&sc->reg_lock);
9690 	if (rc)
9691 		goto done;
9692 
9693 	p = buf;
9694 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9695 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9696 		    p[1], p[0]);
9697 	}
9698 
9699 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9700 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9701 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9702 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9703 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9704 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9705 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9706 		    p[0] & 1);
9707 	}
9708 	rc = sbuf_finish(sb);
9709 done:
9710 	sbuf_delete(sb);
9711 	free(buf, M_CXGBE);
9712 	return (rc);
9713 }
9714 
9715 static int
9716 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9717 {
9718 	struct adapter *sc = arg1;
9719 	u_int i;
9720 	struct sbuf *sb;
9721 	uint32_t *buf, *p;
9722 	int rc;
9723 
9724 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9725 	if (sb == NULL)
9726 		return (ENOMEM);
9727 
9728 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9729 	    M_ZERO | M_WAITOK);
9730 
9731 	rc = 0;
9732 	mtx_lock(&sc->reg_lock);
9733 	if (hw_off_limits(sc))
9734 		rc = ENXIO;
9735 	else
9736 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9737 	mtx_unlock(&sc->reg_lock);
9738 	if (rc)
9739 		goto done;
9740 
9741 	p = buf;
9742 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9743 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9744 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9745 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9746 		    p[4], p[3], p[2], p[1], p[0]);
9747 	}
9748 
9749 	sbuf_printf(sb, "\n\nCntl ID               Data");
9750 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9751 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9752 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9753 	}
9754 
9755 	rc = sbuf_finish(sb);
9756 done:
9757 	sbuf_delete(sb);
9758 	free(buf, M_CXGBE);
9759 	return (rc);
9760 }
9761 
9762 static int
9763 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9764 {
9765 	struct adapter *sc = arg1;
9766 	struct sbuf *sb;
9767 	int rc, i;
9768 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9769 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9770 	uint16_t thres[CIM_NUM_IBQ];
9771 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9772 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9773 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9774 	static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
9775 		"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
9776 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
9777 		"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
9778 	};
9779 
9780 	MPASS(chip_id(sc) < CHELSIO_T7);
9781 
9782 	cim_num_obq = sc->chip_params->cim_num_obq;
9783 	if (is_t4(sc)) {
9784 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9785 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9786 	} else {
9787 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9788 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9789 	}
9790 	nq = CIM_NUM_IBQ + cim_num_obq;
9791 
9792 	mtx_lock(&sc->reg_lock);
9793 	if (hw_off_limits(sc))
9794 		rc = ENXIO;
9795 	else {
9796 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9797 		if (rc == 0) {
9798 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9799 			    obq_wr);
9800 			if (rc == 0)
9801 				t4_read_cimq_cfg(sc, base, size, thres);
9802 		}
9803 	}
9804 	mtx_unlock(&sc->reg_lock);
9805 	if (rc)
9806 		return (rc);
9807 
9808 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9809 	if (sb == NULL)
9810 		return (ENOMEM);
9811 
9812 	sbuf_printf(sb,
9813 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9814 
9815 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9816 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9817 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9818 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9819 		    G_QUEREMFLITS(p[2]) * 16);
9820 	for ( ; i < nq; i++, p += 4, wr += 2)
9821 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9822 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9823 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9824 		    G_QUEREMFLITS(p[2]) * 16);
9825 
9826 	rc = sbuf_finish(sb);
9827 	sbuf_delete(sb);
9828 
9829 	return (rc);
9830 }
9831 
9832 static int
9833 sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS)
9834 {
9835 	struct adapter *sc = arg1;
9836 	u_int coreid = arg2;
9837 	struct sbuf *sb;
9838 	int rc, i;
9839 	u_int addr;
9840 	uint16_t base[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9841 	uint16_t size[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9842 	uint16_t thres[CIM_NUM_IBQ_T7];
9843 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T7], *wr = obq_wr;
9844 	uint32_t stat[4 * (CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7)], *p = stat;
9845 	static const char * const qname_ibq_t7[] = {
9846 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "SGE1", "NC-SI",
9847 		"RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5", "IPC6", "IPC7",
9848 	};
9849 	static const char * const qname_obq_t7[] = {
9850 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", "SGE0-RX",
9851 		"RSVD", "RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5",
9852 		"IPC6", "IPC7"
9853 	};
9854 	static const char * const qname_ibq_sec_t7[] = {
9855 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "RSVD", "RSVD",
9856 		"RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",	"RSVD", "RSVD",
9857 	};
9858 	static const char * const qname_obq_sec_t7[] = {
9859 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "RSVD", "SGE0-RX",
9860 		"RSVD", "RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",
9861 		"RSVD", "RSVD",
9862 	};
9863 
9864 	MPASS(chip_id(sc) >= CHELSIO_T7);
9865 
9866 	mtx_lock(&sc->reg_lock);
9867 	if (hw_off_limits(sc))
9868 		rc = ENXIO;
9869 	else {
9870 		rc = -t4_cim_read_core(sc, 1, coreid,
9871 		    A_T7_UP_IBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_IBQ_T7, stat);
9872 		if (rc != 0)
9873 			goto unlock;
9874 
9875 		rc = -t4_cim_read_core(sc, 1, coreid,
9876 		    A_T7_UP_OBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_OBQ_T7,
9877 		    &stat[4 * CIM_NUM_IBQ_T7]);
9878 		if (rc != 0)
9879 			goto unlock;
9880 
9881 		addr = A_T7_UP_OBQ_0_SHADOW_REALADDR;
9882 		for (i = 0; i < CIM_NUM_OBQ_T7 * 2; i++, addr += 8) {
9883 			rc = -t4_cim_read_core(sc, 1, coreid, addr, 1,
9884 			    &obq_wr[i]);
9885 			if (rc != 0)
9886 				goto unlock;
9887 		}
9888 		t4_read_cimq_cfg_core(sc, coreid, base, size, thres);
9889 	}
9890 unlock:
9891 	mtx_unlock(&sc->reg_lock);
9892 	if (rc)
9893 		return (rc);
9894 
9895 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9896 	if (sb == NULL)
9897 		return (ENOMEM);
9898 
9899 	sbuf_printf(sb,
9900 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9901 
9902 	for (i = 0; i < CIM_NUM_IBQ_T7; i++, p += 4) {
9903 		if (!size[i])
9904 			continue;
9905 
9906 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9907 		    coreid == 0 ? qname_ibq_t7[i] : qname_ibq_sec_t7[i],
9908 		    base[i], size[i], thres[i], G_IBQRDADDR(p[0]) & 0xfff,
9909 		    G_IBQWRADDR(p[1]) & 0xfff, G_QUESOPCNT(p[3]),
9910 		    G_QUEEOPCNT(p[3]), G_T7_QUEREMFLITS(p[2]) * 16);
9911 	}
9912 
9913 	for ( ; i < CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7; i++, p += 4, wr += 2) {
9914 		if (!size[i])
9915 			continue;
9916 
9917 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u",
9918 		    coreid == 0 ? qname_obq_t7[i - CIM_NUM_IBQ_T7] :
9919 		    qname_obq_sec_t7[i - CIM_NUM_IBQ_T7],
9920 		    base[i], size[i], G_QUERDADDR(p[0]) & 0xfff,
9921 		    wr[0] << 1, G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9922 		    G_T7_QUEREMFLITS(p[2]) * 16);
9923 	}
9924 
9925 	rc = sbuf_finish(sb);
9926 	sbuf_delete(sb);
9927 	return (rc);
9928 }
9929 
9930 static int
9931 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9932 {
9933 	struct adapter *sc = arg1;
9934 	struct sbuf *sb;
9935 	int rc;
9936 	struct tp_cpl_stats stats;
9937 
9938 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9939 	if (sb == NULL)
9940 		return (ENOMEM);
9941 
9942 	rc = 0;
9943 	mtx_lock(&sc->reg_lock);
9944 	if (hw_off_limits(sc))
9945 		rc = ENXIO;
9946 	else
9947 		t4_tp_get_cpl_stats(sc, &stats, 0);
9948 	mtx_unlock(&sc->reg_lock);
9949 	if (rc)
9950 		goto done;
9951 
9952 	if (sc->chip_params->nchan > 2) {
9953 		sbuf_printf(sb, "                 channel 0  channel 1"
9954 		    "  channel 2  channel 3");
9955 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9956 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9957 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9958 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9959 	} else {
9960 		sbuf_printf(sb, "                 channel 0  channel 1");
9961 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9962 		    stats.req[0], stats.req[1]);
9963 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9964 		    stats.rsp[0], stats.rsp[1]);
9965 	}
9966 
9967 	rc = sbuf_finish(sb);
9968 done:
9969 	sbuf_delete(sb);
9970 	return (rc);
9971 }
9972 
9973 static int
9974 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9975 {
9976 	struct adapter *sc = arg1;
9977 	struct sbuf *sb;
9978 	int rc;
9979 	struct tp_usm_stats stats;
9980 
9981 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9982 	if (sb == NULL)
9983 		return (ENOMEM);
9984 
9985 	rc = 0;
9986 	mtx_lock(&sc->reg_lock);
9987 	if (hw_off_limits(sc))
9988 		rc = ENXIO;
9989 	else
9990 		t4_get_usm_stats(sc, &stats, 1);
9991 	mtx_unlock(&sc->reg_lock);
9992 	if (rc == 0) {
9993 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9994 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9995 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9996 		rc = sbuf_finish(sb);
9997 	}
9998 	sbuf_delete(sb);
9999 
10000 	return (rc);
10001 }
10002 
10003 static int
10004 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
10005 {
10006 	struct adapter *sc = arg1;
10007 	struct sbuf *sb;
10008 	int rc;
10009 	struct tp_tid_stats stats;
10010 
10011 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10012 	if (sb == NULL)
10013 		return (ENOMEM);
10014 
10015 	rc = 0;
10016 	mtx_lock(&sc->reg_lock);
10017 	if (hw_off_limits(sc))
10018 		rc = ENXIO;
10019 	else
10020 		t4_tp_get_tid_stats(sc, &stats, 1);
10021 	mtx_unlock(&sc->reg_lock);
10022 	if (rc == 0) {
10023 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
10024 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
10025 		sbuf_printf(sb, "Active:     %u\n", stats.act);
10026 		sbuf_printf(sb, "Passive:    %u", stats.pas);
10027 		rc = sbuf_finish(sb);
10028 	}
10029 	sbuf_delete(sb);
10030 
10031 	return (rc);
10032 }
10033 
10034 static const char * const devlog_level_strings[] = {
10035 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
10036 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
10037 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
10038 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
10039 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
10040 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
10041 };
10042 
10043 static const char * const devlog_facility_strings[] = {
10044 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
10045 	[FW_DEVLOG_FACILITY_CF]		= "CF",
10046 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
10047 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
10048 	[FW_DEVLOG_FACILITY_RES]	= "RES",
10049 	[FW_DEVLOG_FACILITY_HW]		= "HW",
10050 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
10051 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
10052 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
10053 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
10054 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
10055 	[FW_DEVLOG_FACILITY_VI]		= "VI",
10056 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
10057 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
10058 	[FW_DEVLOG_FACILITY_TM]		= "TM",
10059 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
10060 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
10061 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
10062 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
10063 	[FW_DEVLOG_FACILITY_RI]		= "RI",
10064 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
10065 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
10066 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
10067 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
10068 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
10069 };
10070 
10071 static int
10072 sbuf_devlog(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
10073 {
10074 	int i, j, rc, nentries, first = 0;
10075 	struct devlog_params *dparams = &sc->params.devlog;
10076 	struct fw_devlog_e *buf, *e;
10077 	uint32_t addr, size;
10078 	uint64_t ftstamp = UINT64_MAX;
10079 
10080 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10081 	    ("%s: bad coreid %d\n", __func__, coreid));
10082 
10083 	if (dparams->addr == 0)
10084 		return (ENXIO);
10085 
10086 	size = dparams->size / sc->params.ncores;
10087 	addr = dparams->addr + coreid * size;
10088 
10089 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
10090 	buf = malloc(size, M_CXGBE, M_ZERO | flags);
10091 	if (buf == NULL)
10092 		return (ENOMEM);
10093 
10094 	mtx_lock(&sc->reg_lock);
10095 	if (hw_off_limits(sc))
10096 		rc = ENXIO;
10097 	else
10098 		rc = read_via_memwin(sc, 1, addr, (void *)buf, size);
10099 	mtx_unlock(&sc->reg_lock);
10100 	if (rc != 0)
10101 		goto done;
10102 
10103 	nentries = size / sizeof(struct fw_devlog_e);
10104 	for (i = 0; i < nentries; i++) {
10105 		e = &buf[i];
10106 
10107 		if (e->timestamp == 0)
10108 			break;	/* end */
10109 
10110 		e->timestamp = be64toh(e->timestamp);
10111 		e->seqno = be32toh(e->seqno);
10112 		for (j = 0; j < 8; j++)
10113 			e->params[j] = be32toh(e->params[j]);
10114 
10115 		if (e->timestamp < ftstamp) {
10116 			ftstamp = e->timestamp;
10117 			first = i;
10118 		}
10119 	}
10120 
10121 	if (buf[first].timestamp == 0)
10122 		goto done;	/* nothing in the log */
10123 
10124 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
10125 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
10126 
10127 	i = first;
10128 	do {
10129 		e = &buf[i];
10130 		if (e->timestamp == 0)
10131 			break;	/* end */
10132 
10133 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
10134 		    e->seqno, e->timestamp,
10135 		    (e->level < nitems(devlog_level_strings) ?
10136 			devlog_level_strings[e->level] : "UNKNOWN"),
10137 		    (e->facility < nitems(devlog_facility_strings) ?
10138 			devlog_facility_strings[e->facility] : "UNKNOWN"));
10139 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
10140 		    e->params[2], e->params[3], e->params[4],
10141 		    e->params[5], e->params[6], e->params[7]);
10142 
10143 		if (++i == nentries)
10144 			i = 0;
10145 	} while (i != first);
10146 done:
10147 	free(buf, M_CXGBE);
10148 	return (rc);
10149 }
10150 
10151 static int
10152 sysctl_devlog(SYSCTL_HANDLER_ARGS)
10153 {
10154 	struct adapter *sc = arg1;
10155 	int rc, i, coreid = arg2;
10156 	struct sbuf *sb;
10157 
10158 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10159 	if (sb == NULL)
10160 		return (ENOMEM);
10161 	if (coreid == -1) {
10162 		/* -1 means all cores */
10163 		for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10164 			if (sc->params.ncores > 0)
10165 				sbuf_printf(sb, "=== CIM core %u ===\n", i);
10166 			rc = sbuf_devlog(sc, i, sb, M_WAITOK);
10167 		}
10168 	} else {
10169 		KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10170 		    ("%s: bad coreid %d\n", __func__, coreid));
10171 		rc = sbuf_devlog(sc, coreid, sb, M_WAITOK);
10172 	}
10173 	if (rc == 0)
10174 		rc = sbuf_finish(sb);
10175 	sbuf_delete(sb);
10176 	return (rc);
10177 }
10178 
10179 static void
10180 dump_devlog(struct adapter *sc)
10181 {
10182 	int rc, i;
10183 	struct sbuf sb;
10184 
10185 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
10186 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
10187 		    device_get_nameunit(sc->dev));
10188 		return;
10189 	}
10190 	for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10191 		if (sc->params.ncores > 0)
10192 			sbuf_printf(&sb, "=== CIM core %u ===\n", i);
10193 		rc = sbuf_devlog(sc, i, &sb, M_WAITOK);
10194 	}
10195 	if (rc == 0) {
10196 		sbuf_finish(&sb);
10197 		log(LOG_DEBUG, "%s: device log follows.\n%s",
10198 		    device_get_nameunit(sc->dev), sbuf_data(&sb));
10199 	}
10200 	sbuf_delete(&sb);
10201 }
10202 
10203 static int
10204 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
10205 {
10206 	struct adapter *sc = arg1;
10207 	struct sbuf *sb;
10208 	int rc;
10209 	struct tp_fcoe_stats stats[MAX_NCHAN];
10210 	int i, nchan = sc->chip_params->nchan;
10211 
10212 	rc = 0;
10213 	mtx_lock(&sc->reg_lock);
10214 	if (hw_off_limits(sc))
10215 		rc = ENXIO;
10216 	else {
10217 		for (i = 0; i < nchan; i++)
10218 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
10219 	}
10220 	mtx_unlock(&sc->reg_lock);
10221 	if (rc != 0)
10222 		return (rc);
10223 
10224 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10225 	if (sb == NULL)
10226 		return (ENOMEM);
10227 
10228 	if (nchan > 2) {
10229 		sbuf_printf(sb, "                   channel 0        channel 1"
10230 		    "        channel 2        channel 3");
10231 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
10232 		    stats[0].octets_ddp, stats[1].octets_ddp,
10233 		    stats[2].octets_ddp, stats[3].octets_ddp);
10234 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
10235 		    stats[0].frames_ddp, stats[1].frames_ddp,
10236 		    stats[2].frames_ddp, stats[3].frames_ddp);
10237 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
10238 		    stats[0].frames_drop, stats[1].frames_drop,
10239 		    stats[2].frames_drop, stats[3].frames_drop);
10240 	} else {
10241 		sbuf_printf(sb, "                   channel 0        channel 1");
10242 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
10243 		    stats[0].octets_ddp, stats[1].octets_ddp);
10244 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
10245 		    stats[0].frames_ddp, stats[1].frames_ddp);
10246 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
10247 		    stats[0].frames_drop, stats[1].frames_drop);
10248 	}
10249 
10250 	rc = sbuf_finish(sb);
10251 	sbuf_delete(sb);
10252 
10253 	return (rc);
10254 }
10255 
10256 static int
10257 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
10258 {
10259 	struct adapter *sc = arg1;
10260 	struct sbuf *sb;
10261 	int rc, i;
10262 	unsigned int map, kbps, ipg, mode;
10263 	unsigned int pace_tab[NTX_SCHED];
10264 
10265 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
10266 	if (sb == NULL)
10267 		return (ENOMEM);
10268 
10269 	mtx_lock(&sc->reg_lock);
10270 	if (hw_off_limits(sc)) {
10271 		mtx_unlock(&sc->reg_lock);
10272 		rc = ENXIO;
10273 		goto done;
10274 	}
10275 
10276 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
10277 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
10278 	t4_read_pace_tbl(sc, pace_tab);
10279 	mtx_unlock(&sc->reg_lock);
10280 
10281 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
10282 	    "Class IPG (0.1 ns)   Flow IPG (us)");
10283 
10284 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
10285 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
10286 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
10287 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
10288 		if (kbps)
10289 			sbuf_printf(sb, "%9u     ", kbps);
10290 		else
10291 			sbuf_printf(sb, " disabled     ");
10292 
10293 		if (ipg)
10294 			sbuf_printf(sb, "%13u        ", ipg);
10295 		else
10296 			sbuf_printf(sb, "     disabled        ");
10297 
10298 		if (pace_tab[i])
10299 			sbuf_printf(sb, "%10u", pace_tab[i]);
10300 		else
10301 			sbuf_printf(sb, "  disabled");
10302 	}
10303 	rc = sbuf_finish(sb);
10304 done:
10305 	sbuf_delete(sb);
10306 	return (rc);
10307 }
10308 
10309 static int
10310 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
10311 {
10312 	struct adapter *sc = arg1;
10313 	struct sbuf *sb;
10314 	int rc, i, j;
10315 	uint64_t *p0, *p1;
10316 	struct lb_port_stats s[2];
10317 	static const char *stat_name[] = {
10318 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
10319 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
10320 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
10321 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
10322 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
10323 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
10324 		"BG2FramesTrunc:", "BG3FramesTrunc:"
10325 	};
10326 
10327 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10328 	if (sb == NULL)
10329 		return (ENOMEM);
10330 
10331 	memset(s, 0, sizeof(s));
10332 
10333 	rc = 0;
10334 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
10335 		mtx_lock(&sc->reg_lock);
10336 		if (hw_off_limits(sc))
10337 			rc = ENXIO;
10338 		else {
10339 			t4_get_lb_stats(sc, i, &s[0]);
10340 			t4_get_lb_stats(sc, i + 1, &s[1]);
10341 		}
10342 		mtx_unlock(&sc->reg_lock);
10343 		if (rc != 0)
10344 			break;
10345 
10346 		p0 = &s[0].octets;
10347 		p1 = &s[1].octets;
10348 		sbuf_printf(sb, "%s                       Loopback %u"
10349 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
10350 
10351 		for (j = 0; j < nitems(stat_name); j++)
10352 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
10353 				   *p0++, *p1++);
10354 	}
10355 
10356 	if (rc == 0)
10357 		rc = sbuf_finish(sb);
10358 	sbuf_delete(sb);
10359 
10360 	return (rc);
10361 }
10362 
10363 static int
10364 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
10365 {
10366 	int rc = 0;
10367 	struct port_info *pi = arg1;
10368 	struct link_config *lc = &pi->link_cfg;
10369 	struct sbuf *sb;
10370 
10371 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
10372 	if (sb == NULL)
10373 		return (ENOMEM);
10374 
10375 	if (lc->link_ok || lc->link_down_rc == 255)
10376 		sbuf_printf(sb, "n/a");
10377 	else
10378 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
10379 
10380 	rc = sbuf_finish(sb);
10381 	sbuf_delete(sb);
10382 
10383 	return (rc);
10384 }
10385 
10386 struct mem_desc {
10387 	uint64_t base;
10388 	uint64_t limit;
10389 	u_int idx;
10390 };
10391 
10392 static int
10393 mem_desc_cmp(const void *a, const void *b)
10394 {
10395 	const uint64_t v1 = ((const struct mem_desc *)a)->base;
10396 	const uint64_t v2 = ((const struct mem_desc *)b)->base;
10397 
10398 	if (v1 < v2)
10399 		return (-1);
10400 	else if (v1 > v2)
10401 		return (1);
10402 
10403 	return (0);
10404 }
10405 
10406 static void
10407 mem_region_show(struct sbuf *sb, const char *name, uint64_t from, uint64_t to)
10408 {
10409 	uintmax_t size;
10410 
10411 	if (from == to)
10412 		return;
10413 
10414 	size = to - from + 1;
10415 	if (size == 0)
10416 		return;
10417 
10418 	if (from > UINT32_MAX || to > UINT32_MAX)
10419 		sbuf_printf(sb, "%-18s 0x%012jx-0x%012jx [%ju]\n", name,
10420 		    (uintmax_t)from, (uintmax_t)to, size);
10421 	else
10422 		sbuf_printf(sb, "%-18s 0x%08jx-0x%08jx [%ju]\n", name,
10423 		    (uintmax_t)from, (uintmax_t)to, size);
10424 }
10425 
10426 static int
10427 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
10428 {
10429 	struct adapter *sc = arg1;
10430 	struct sbuf *sb;
10431 	int rc, i, n, nchan;
10432 	uint32_t lo, hi, used, free, alloc;
10433 	static const char *memory[] = {
10434 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
10435 	};
10436 	static const char *region[] = {
10437 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
10438 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
10439 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
10440 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
10441 		"RQUDP region:", "PBL region:", "TXPBL region:",
10442 		"TLSKey region:", "RRQ region:", "NVMe STAG region:",
10443 		"NVMe RQ region:", "NVMe RXPBL region:", "NVMe TPT region:",
10444 		"NVMe TXPBL region:", "DBVFIFO region:", "ULPRX state:",
10445 		"ULPTX state:", "RoCE RRQ region:", "On-chip queues:",
10446 	};
10447 	struct mem_desc avail[4];
10448 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
10449 	struct mem_desc *md;
10450 
10451 	rc = sysctl_wire_old_buffer(req, 0);
10452 	if (rc != 0)
10453 		return (rc);
10454 
10455 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10456 	if (sb == NULL)
10457 		return (ENOMEM);
10458 
10459 	for (i = 0; i < nitems(mem); i++) {
10460 		mem[i].limit = 0;
10461 		mem[i].idx = i;
10462 	}
10463 
10464 	mtx_lock(&sc->reg_lock);
10465 	if (hw_off_limits(sc)) {
10466 		rc = ENXIO;
10467 		goto done;
10468 	}
10469 
10470 	/* Find and sort the populated memory ranges */
10471 	i = 0;
10472 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
10473 	if (lo & F_EDRAM0_ENABLE) {
10474 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
10475 		if (chip_id(sc) >= CHELSIO_T7) {
10476 			avail[i].base = (uint64_t)G_T7_EDRAM0_BASE(hi) << 20;
10477 			avail[i].limit = avail[i].base +
10478 			    (G_T7_EDRAM0_SIZE(hi) << 20);
10479 		} else {
10480 			avail[i].base = (uint64_t)G_EDRAM0_BASE(hi) << 20;
10481 			avail[i].limit = avail[i].base +
10482 			    (G_EDRAM0_SIZE(hi) << 20);
10483 		}
10484 		avail[i].idx = 0;
10485 		i++;
10486 	}
10487 	if (lo & F_EDRAM1_ENABLE) {
10488 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
10489 		if (chip_id(sc) >= CHELSIO_T7) {
10490 			avail[i].base = (uint64_t)G_T7_EDRAM1_BASE(hi) << 20;
10491 			avail[i].limit = avail[i].base +
10492 			    (G_T7_EDRAM1_SIZE(hi) << 20);
10493 		} else {
10494 			avail[i].base = (uint64_t)G_EDRAM1_BASE(hi) << 20;
10495 			avail[i].limit = avail[i].base +
10496 			    (G_EDRAM1_SIZE(hi) << 20);
10497 		}
10498 		avail[i].idx = 1;
10499 		i++;
10500 	}
10501 	if (lo & F_EXT_MEM_ENABLE) {
10502 		switch (chip_id(sc)) {
10503 		case CHELSIO_T4:
10504 		case CHELSIO_T6:
10505 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
10506 			avail[i].base = (uint64_t)G_EXT_MEM_BASE(hi) << 20;
10507 			avail[i].limit = avail[i].base +
10508 			    (G_EXT_MEM_SIZE(hi) << 20);
10509 			avail[i].idx = 2;
10510 			break;
10511 		case CHELSIO_T5:
10512 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10513 			avail[i].base = (uint64_t)G_EXT_MEM0_BASE(hi) << 20;
10514 			avail[i].limit = avail[i].base +
10515 			    (G_EXT_MEM0_SIZE(hi) << 20);
10516 			avail[i].idx = 3;	/* Call it MC0 for T5 */
10517 			break;
10518 		default:
10519 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10520 			avail[i].base = (uint64_t)G_T7_EXT_MEM0_BASE(hi) << 20;
10521 			avail[i].limit = avail[i].base +
10522 			    (G_T7_EXT_MEM0_SIZE(hi) << 20);
10523 			avail[i].idx = 3;	/* Call it MC0 for T7+ */
10524 			break;
10525 		}
10526 		i++;
10527 	}
10528 	if (lo & F_EXT_MEM1_ENABLE && !(lo & F_MC_SPLIT)) {
10529 		/* Only T5 and T7+ have 2 MCs. */
10530 		MPASS(is_t5(sc) || chip_id(sc) >= CHELSIO_T7);
10531 
10532 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10533 		if (chip_id(sc) >= CHELSIO_T7) {
10534 			avail[i].base = (uint64_t)G_T7_EXT_MEM1_BASE(hi) << 20;
10535 			avail[i].limit = avail[i].base +
10536 			    (G_T7_EXT_MEM1_SIZE(hi) << 20);
10537 		} else {
10538 			avail[i].base = (uint64_t)G_EXT_MEM1_BASE(hi) << 20;
10539 			avail[i].limit = avail[i].base +
10540 			    (G_EXT_MEM1_SIZE(hi) << 20);
10541 		}
10542 		avail[i].idx = 4;
10543 		i++;
10544 	}
10545 	if (lo & F_HMA_MUX) {
10546 		/* Only T6+ have HMA. */
10547 		MPASS(chip_id(sc) >= CHELSIO_T6);
10548 
10549 		if (chip_id(sc) >= CHELSIO_T7) {
10550 			hi = t4_read_reg(sc, A_MA_HOST_MEMORY_BAR);
10551 			avail[i].base = (uint64_t)G_HMATARGETBASE(hi) << 20;
10552 			avail[i].limit = avail[i].base +
10553 			    (G_T7_HMA_SIZE(hi) << 20);
10554 		} else {
10555 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10556 			avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
10557 			avail[i].limit = avail[i].base +
10558 			    (G_EXT_MEM1_SIZE(hi) << 20);
10559 		}
10560 		avail[i].idx = 5;
10561 		i++;
10562 	}
10563 	MPASS(i <= nitems(avail));
10564 	if (!i)                                    /* no memory available */
10565 		goto done;
10566 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
10567 
10568 	md = &mem[0];
10569 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
10570 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
10571 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
10572 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10573 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
10574 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
10575 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
10576 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
10577 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
10578 
10579 	/* the next few have explicit upper bounds */
10580 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
10581 	md->limit = md->base - 1 +
10582 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
10583 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
10584 	md++;
10585 
10586 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
10587 	md->limit = md->base - 1 +
10588 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
10589 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
10590 	md++;
10591 
10592 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10593 		if (chip_id(sc) <= CHELSIO_T5)
10594 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
10595 		else
10596 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
10597 		md->limit = 0;
10598 	} else {
10599 		md->base = 0;
10600 		md->idx = nitems(region);  /* hide it */
10601 	}
10602 	md++;
10603 
10604 #define ulp_region(reg) do {\
10605 		const u_int shift = chip_id(sc) >= CHELSIO_T7 ? 4 : 0; \
10606 		md->base = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT) << shift; \
10607 		md->limit = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT) << shift; \
10608 		md->limit += (1 << shift) - 1; \
10609 		md++; \
10610 	} while (0)
10611 
10612 #define	hide_ulp_region() do { \
10613 		md->base = 0; \
10614 		md->idx = nitems(region); \
10615 		md++; \
10616 	} while (0)
10617 
10618 	ulp_region(RX_ISCSI);
10619 	ulp_region(RX_TDDP);
10620 	ulp_region(TX_TPT);
10621 	ulp_region(RX_STAG);
10622 	ulp_region(RX_RQ);
10623 	if (chip_id(sc) < CHELSIO_T7)
10624 		ulp_region(RX_RQUDP);
10625 	else
10626 		hide_ulp_region();
10627 	ulp_region(RX_PBL);
10628 	ulp_region(TX_PBL);
10629 	if (chip_id(sc) >= CHELSIO_T6)
10630 		ulp_region(RX_TLS_KEY);
10631 	else
10632 		hide_ulp_region();
10633 	if (chip_id(sc) >= CHELSIO_T7) {
10634 		ulp_region(RX_RRQ);
10635 		ulp_region(RX_NVME_TCP_STAG);
10636 		ulp_region(RX_NVME_TCP_RQ);
10637 		ulp_region(RX_NVME_TCP_PBL);
10638 		ulp_region(TX_NVME_TCP_TPT);
10639 		ulp_region(TX_NVME_TCP_PBL);
10640 	} else {
10641 		hide_ulp_region();
10642 		hide_ulp_region();
10643 		hide_ulp_region();
10644 		hide_ulp_region();
10645 		hide_ulp_region();
10646 		hide_ulp_region();
10647 	}
10648 #undef ulp_region
10649 #undef hide_ulp_region
10650 
10651 	md->base = 0;
10652 	if (is_t4(sc))
10653 		md->idx = nitems(region);
10654 	else {
10655 		uint32_t size = 0;
10656 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
10657 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
10658 
10659 		if (is_t5(sc)) {
10660 			if (sge_ctrl & F_VFIFO_ENABLE)
10661 				size = fifo_size << 2;
10662 		} else
10663 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
10664 
10665 		if (size) {
10666 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10667 			md->limit = md->base + size - 1;
10668 		} else
10669 			md->idx = nitems(region);
10670 	}
10671 	md++;
10672 
10673 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10674 	md->limit = 0;
10675 	md++;
10676 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10677 	md->limit = 0;
10678 	md++;
10679 
10680 	if (chip_id(sc) >= CHELSIO_T7) {
10681 		t4_tp_pio_read(sc, &lo, 1, A_TP_ROCE_RRQ_BASE, false);
10682 		md->base = lo;
10683 	} else {
10684 		md->base = 0;
10685 		md->idx = nitems(region);
10686 	}
10687 	md++;
10688 
10689 	md->base = sc->vres.ocq.start;
10690 	if (sc->vres.ocq.size)
10691 		md->limit = md->base + sc->vres.ocq.size - 1;
10692 	else
10693 		md->idx = nitems(region);  /* hide it */
10694 	md++;
10695 
10696 	/* add any address-space holes, there can be up to 3 */
10697 	for (n = 0; n < i - 1; n++)
10698 		if (avail[n].limit < avail[n + 1].base)
10699 			(md++)->base = avail[n].limit;
10700 	if (avail[n].limit)
10701 		(md++)->base = avail[n].limit;
10702 
10703 	n = md - mem;
10704 	MPASS(n <= nitems(mem));
10705 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10706 
10707 	for (lo = 0; lo < i; lo++)
10708 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10709 				avail[lo].limit - 1);
10710 
10711 	sbuf_printf(sb, "\n");
10712 	for (i = 0; i < n; i++) {
10713 		if (mem[i].idx >= nitems(region))
10714 			continue;                        /* skip holes */
10715 		if (!mem[i].limit)
10716 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10717 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10718 				mem[i].limit);
10719 	}
10720 
10721 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10722 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10723 	if (hi != lo  - 1) {
10724 		sbuf_printf(sb, "\n");
10725 		mem_region_show(sb, "uP RAM:", lo, hi);
10726 	}
10727 
10728 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10729 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10730 	if (hi != lo  - 1)
10731 		mem_region_show(sb, "uP Extmem2:", lo, hi);
10732 
10733 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10734 	if (chip_id(sc) >= CHELSIO_T7)
10735 		nchan = 1 << G_T7_PMRXNUMCHN(lo);
10736 	else
10737 		nchan = lo & F_PMRXNUMCHN ? 2 : 1;
10738 	for (i = 0, free = 0; i < nchan; i++)
10739 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10740 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10741 		   G_PMRXMAXPAGE(lo), free,
10742 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10, nchan);
10743 
10744 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10745 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10746 	if (chip_id(sc) >= CHELSIO_T7)
10747 		nchan = 1 << G_T7_PMTXNUMCHN(lo);
10748 	else
10749 		nchan = 1 << G_PMTXNUMCHN(lo);
10750 	for (i = 0, free = 0; i < nchan; i++)
10751 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10752 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10753 		   G_PMTXMAXPAGE(lo), free,
10754 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10755 		   hi >= (1 << 20) ? 'M' : 'K', nchan);
10756 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10757 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10758 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10759 
10760 	for (i = 0; i < 4; i++) {
10761 		if (chip_id(sc) > CHELSIO_T5)
10762 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10763 		else
10764 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10765 		if (is_t5(sc)) {
10766 			used = G_T5_USED(lo);
10767 			alloc = G_T5_ALLOC(lo);
10768 		} else {
10769 			used = G_USED(lo);
10770 			alloc = G_ALLOC(lo);
10771 		}
10772 		/* For T6+ these are MAC buffer groups */
10773 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10774 		    i, used, alloc);
10775 	}
10776 	for (i = 0; i < sc->chip_params->nchan; i++) {
10777 		if (chip_id(sc) > CHELSIO_T5)
10778 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10779 		else
10780 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10781 		if (is_t5(sc)) {
10782 			used = G_T5_USED(lo);
10783 			alloc = G_T5_ALLOC(lo);
10784 		} else {
10785 			used = G_USED(lo);
10786 			alloc = G_ALLOC(lo);
10787 		}
10788 		/* For T6+ these are MAC buffer groups */
10789 		sbuf_printf(sb,
10790 		    "\nLoopback %d using %u pages out of %u allocated",
10791 		    i, used, alloc);
10792 	}
10793 done:
10794 	mtx_unlock(&sc->reg_lock);
10795 	if (rc == 0)
10796 		rc = sbuf_finish(sb);
10797 	sbuf_delete(sb);
10798 	return (rc);
10799 }
10800 
10801 static inline void
10802 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10803 {
10804 	*mask = x | y;
10805 	y = htobe64(y);
10806 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10807 }
10808 
10809 static int
10810 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10811 {
10812 	struct adapter *sc = arg1;
10813 	struct sbuf *sb;
10814 	int rc, i;
10815 
10816 	MPASS(chip_id(sc) <= CHELSIO_T5);
10817 
10818 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10819 	if (sb == NULL)
10820 		return (ENOMEM);
10821 
10822 	sbuf_printf(sb,
10823 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10824 	    "  VF              Replication             P0 P1 P2 P3  ML");
10825 	rc = 0;
10826 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10827 		uint64_t tcamx, tcamy, mask;
10828 		uint32_t cls_lo, cls_hi;
10829 		uint8_t addr[ETHER_ADDR_LEN];
10830 
10831 		mtx_lock(&sc->reg_lock);
10832 		if (hw_off_limits(sc))
10833 			rc = ENXIO;
10834 		else {
10835 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10836 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10837 		}
10838 		mtx_unlock(&sc->reg_lock);
10839 		if (rc != 0)
10840 			break;
10841 		if (tcamx & tcamy)
10842 			continue;
10843 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10844 		mtx_lock(&sc->reg_lock);
10845 		if (hw_off_limits(sc))
10846 			rc = ENXIO;
10847 		else {
10848 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10849 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10850 		}
10851 		mtx_unlock(&sc->reg_lock);
10852 		if (rc != 0)
10853 			break;
10854 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10855 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10856 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10857 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10858 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10859 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10860 
10861 		if (cls_lo & F_REPLICATE) {
10862 			struct fw_ldst_cmd ldst_cmd;
10863 
10864 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10865 			ldst_cmd.op_to_addrspace =
10866 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10867 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10868 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10869 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10870 			ldst_cmd.u.mps.rplc.fid_idx =
10871 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10872 				V_FW_LDST_CMD_IDX(i));
10873 
10874 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10875 			    "t4mps");
10876 			if (rc)
10877 				break;
10878 			if (hw_off_limits(sc))
10879 				rc = ENXIO;
10880 			else
10881 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10882 				    sizeof(ldst_cmd), &ldst_cmd);
10883 			end_synchronized_op(sc, 0);
10884 			if (rc != 0)
10885 				break;
10886 			else {
10887 				sbuf_printf(sb, " %08x %08x %08x %08x",
10888 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10889 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10890 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10891 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10892 			}
10893 		} else
10894 			sbuf_printf(sb, "%36s", "");
10895 
10896 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10897 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10898 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10899 	}
10900 
10901 	if (rc)
10902 		(void) sbuf_finish(sb);
10903 	else
10904 		rc = sbuf_finish(sb);
10905 	sbuf_delete(sb);
10906 
10907 	return (rc);
10908 }
10909 
10910 static int
10911 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10912 {
10913 	struct adapter *sc = arg1;
10914 	struct sbuf *sb;
10915 	int rc, i;
10916 
10917 	MPASS(chip_id(sc) == CHELSIO_T6);
10918 
10919 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10920 	if (sb == NULL)
10921 		return (ENOMEM);
10922 
10923 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10924 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10925 	    "                           Replication"
10926 	    "                                    P0 P1 P2 P3  ML");
10927 
10928 	rc = 0;
10929 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10930 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10931 		uint16_t ivlan;
10932 		uint64_t tcamx, tcamy, val, mask;
10933 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10934 		uint8_t addr[ETHER_ADDR_LEN];
10935 
10936 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10937 		if (i < 256)
10938 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10939 		else
10940 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10941 		mtx_lock(&sc->reg_lock);
10942 		if (hw_off_limits(sc))
10943 			rc = ENXIO;
10944 		else {
10945 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10946 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10947 			tcamy = G_DMACH(val) << 32;
10948 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10949 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10950 		}
10951 		mtx_unlock(&sc->reg_lock);
10952 		if (rc != 0)
10953 			break;
10954 
10955 		lookup_type = G_DATALKPTYPE(data2);
10956 		port_num = G_DATAPORTNUM(data2);
10957 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10958 			/* Inner header VNI */
10959 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10960 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10961 			dip_hit = data2 & F_DATADIPHIT;
10962 			vlan_vld = 0;
10963 		} else {
10964 			vniy = 0;
10965 			dip_hit = 0;
10966 			vlan_vld = data2 & F_DATAVIDH2;
10967 			ivlan = G_VIDL(val);
10968 		}
10969 
10970 		ctl |= V_CTLXYBITSEL(1);
10971 		mtx_lock(&sc->reg_lock);
10972 		if (hw_off_limits(sc))
10973 			rc = ENXIO;
10974 		else {
10975 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10976 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10977 			tcamx = G_DMACH(val) << 32;
10978 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10979 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10980 		}
10981 		mtx_unlock(&sc->reg_lock);
10982 		if (rc != 0)
10983 			break;
10984 
10985 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10986 			/* Inner header VNI mask */
10987 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10988 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10989 		} else
10990 			vnix = 0;
10991 
10992 		if (tcamx & tcamy)
10993 			continue;
10994 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10995 
10996 		mtx_lock(&sc->reg_lock);
10997 		if (hw_off_limits(sc))
10998 			rc = ENXIO;
10999 		else {
11000 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11001 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11002 		}
11003 		mtx_unlock(&sc->reg_lock);
11004 		if (rc != 0)
11005 			break;
11006 
11007 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11008 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11009 			    "%012jx %06x %06x    -    -   %3c"
11010 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11011 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11012 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11013 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11014 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11015 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11016 		} else {
11017 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11018 			    "%012jx    -       -   ", i, addr[0], addr[1],
11019 			    addr[2], addr[3], addr[4], addr[5],
11020 			    (uintmax_t)mask);
11021 
11022 			if (vlan_vld)
11023 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11024 			else
11025 				sbuf_printf(sb, "  -    N     ");
11026 
11027 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11028 			    lookup_type ? 'I' : 'O', port_num,
11029 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11030 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11031 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11032 		}
11033 
11034 
11035 		if (cls_lo & F_T6_REPLICATE) {
11036 			struct fw_ldst_cmd ldst_cmd;
11037 
11038 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11039 			ldst_cmd.op_to_addrspace =
11040 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11041 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11042 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11043 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11044 			ldst_cmd.u.mps.rplc.fid_idx =
11045 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11046 				V_FW_LDST_CMD_IDX(i));
11047 
11048 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11049 			    "t6mps");
11050 			if (rc)
11051 				break;
11052 			if (hw_off_limits(sc))
11053 				rc = ENXIO;
11054 			else
11055 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11056 				    sizeof(ldst_cmd), &ldst_cmd);
11057 			end_synchronized_op(sc, 0);
11058 			if (rc != 0)
11059 				break;
11060 			else {
11061 				sbuf_printf(sb, " %08x %08x %08x %08x"
11062 				    " %08x %08x %08x %08x",
11063 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11064 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11065 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11066 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11067 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11068 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11069 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11070 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11071 			}
11072 		} else
11073 			sbuf_printf(sb, "%72s", "");
11074 
11075 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11076 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11077 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11078 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11079 	}
11080 
11081 	if (rc)
11082 		(void) sbuf_finish(sb);
11083 	else
11084 		rc = sbuf_finish(sb);
11085 	sbuf_delete(sb);
11086 
11087 	return (rc);
11088 }
11089 
11090 static int
11091 sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS)
11092 {
11093 	struct adapter *sc = arg1;
11094 	struct sbuf *sb;
11095 	int rc, i;
11096 
11097 	MPASS(chip_id(sc) >= CHELSIO_T7);
11098 
11099 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11100 	if (sb == NULL)
11101 		return (ENOMEM);
11102 
11103 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11104 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11105 	    "                           Replication"
11106 	    "                                    P0 P1 P2 P3  ML");
11107 
11108 	rc = 0;
11109 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11110 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11111 		uint16_t ivlan;
11112 		uint64_t tcamx, tcamy, val, mask;
11113 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11114 		uint8_t addr[ETHER_ADDR_LEN];
11115 
11116 		/* Read tcamy */
11117 		ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11118 		if (chip_rev(sc) == 0) {
11119 			if (i < 256)
11120 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11121 			else
11122 				ctl |= V_CTLTCAMINDEX(i - 256) | V_T7_CTLTCAMSEL(1);
11123 		} else {
11124 #if 0
11125 			ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11126 #endif
11127 			if (i < 512)
11128 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11129 			else if (i < 1024)
11130 				ctl |= V_CTLTCAMINDEX(i - 512) | V_T7_CTLTCAMSEL(1);
11131 			else
11132 				ctl |= V_CTLTCAMINDEX(i - 1024) | V_T7_CTLTCAMSEL(2);
11133 		}
11134 
11135 		mtx_lock(&sc->reg_lock);
11136 		if (hw_off_limits(sc))
11137 			rc = ENXIO;
11138 		else {
11139 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11140 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11141 			tcamy = G_DMACH(val) << 32;
11142 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11143 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11144 		}
11145 		mtx_unlock(&sc->reg_lock);
11146 		if (rc != 0)
11147 			break;
11148 
11149 		lookup_type = G_DATALKPTYPE(data2);
11150 		port_num = G_DATAPORTNUM(data2);
11151 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11152 			/* Inner header VNI */
11153 			vniy = (((data2 & F_DATAVIDH2) |
11154 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11155 			dip_hit = data2 & F_DATADIPHIT;
11156 			vlan_vld = 0;
11157 		} else {
11158 			vniy = 0;
11159 			dip_hit = 0;
11160 			vlan_vld = data2 & F_DATAVIDH2;
11161 			ivlan = G_VIDL(val);
11162 		}
11163 
11164 		ctl |= V_CTLXYBITSEL(1);
11165 		mtx_lock(&sc->reg_lock);
11166 		if (hw_off_limits(sc))
11167 			rc = ENXIO;
11168 		else {
11169 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11170 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11171 			tcamx = G_DMACH(val) << 32;
11172 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11173 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11174 		}
11175 		mtx_unlock(&sc->reg_lock);
11176 		if (rc != 0)
11177 			break;
11178 
11179 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11180 			/* Inner header VNI mask */
11181 			vnix = (((data2 & F_DATAVIDH2) |
11182 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11183 		} else
11184 			vnix = 0;
11185 
11186 		if (tcamx & tcamy)
11187 			continue;
11188 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11189 
11190 		mtx_lock(&sc->reg_lock);
11191 		if (hw_off_limits(sc))
11192 			rc = ENXIO;
11193 		else {
11194 			if (chip_rev(sc) == 0) {
11195 				cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11196 				cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11197 			} else {
11198 				t4_write_reg(sc, A_MPS_CLS_SRAM_H,
11199 				    V_SRAMWRN(0) | V_SRAMINDEX(i));
11200 				cls_lo = t4_read_reg(sc, A_MPS_CLS_SRAM_L);
11201 				cls_hi = t4_read_reg(sc, A_MPS_CLS_SRAM_H);
11202 			}
11203 		}
11204 		mtx_unlock(&sc->reg_lock);
11205 		if (rc != 0)
11206 			break;
11207 
11208 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11209 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11210 			    "%012jx %06x %06x    -    -   %3c"
11211 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11212 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11213 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11214 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11215 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11216 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11217 		} else {
11218 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11219 			    "%012jx    -       -   ", i, addr[0], addr[1],
11220 			    addr[2], addr[3], addr[4], addr[5],
11221 			    (uintmax_t)mask);
11222 
11223 			if (vlan_vld)
11224 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11225 			else
11226 				sbuf_printf(sb, "  -    N     ");
11227 
11228 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11229 			    lookup_type ? 'I' : 'O', port_num,
11230 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11231 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11232 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11233 		}
11234 
11235 		if (cls_lo & F_T6_REPLICATE) {
11236 			struct fw_ldst_cmd ldst_cmd;
11237 
11238 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11239 			ldst_cmd.op_to_addrspace =
11240 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11241 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11242 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11243 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11244 			ldst_cmd.u.mps.rplc.fid_idx =
11245 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11246 				V_FW_LDST_CMD_IDX(i));
11247 
11248 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11249 			    "t6mps");
11250 			if (rc)
11251 				break;
11252 			if (hw_off_limits(sc))
11253 				rc = ENXIO;
11254 			else
11255 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11256 				    sizeof(ldst_cmd), &ldst_cmd);
11257 			end_synchronized_op(sc, 0);
11258 			if (rc != 0)
11259 				break;
11260 			else {
11261 				sbuf_printf(sb, " %08x %08x %08x %08x"
11262 				    " %08x %08x %08x %08x",
11263 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11264 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11265 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11266 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11267 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11268 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11269 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11270 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11271 			}
11272 		} else
11273 			sbuf_printf(sb, "%72s", "");
11274 
11275 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11276 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11277 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11278 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11279 	}
11280 
11281 	if (rc)
11282 		(void) sbuf_finish(sb);
11283 	else
11284 		rc = sbuf_finish(sb);
11285 	sbuf_delete(sb);
11286 
11287 	return (rc);
11288 }
11289 
11290 static int
11291 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
11292 {
11293 	struct adapter *sc = arg1;
11294 	struct sbuf *sb;
11295 	int rc;
11296 	uint16_t mtus[NMTUS];
11297 
11298 	rc = 0;
11299 	mtx_lock(&sc->reg_lock);
11300 	if (hw_off_limits(sc))
11301 		rc = ENXIO;
11302 	else
11303 		t4_read_mtu_tbl(sc, mtus, NULL);
11304 	mtx_unlock(&sc->reg_lock);
11305 	if (rc != 0)
11306 		return (rc);
11307 
11308 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11309 	if (sb == NULL)
11310 		return (ENOMEM);
11311 
11312 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
11313 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
11314 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
11315 	    mtus[14], mtus[15]);
11316 
11317 	rc = sbuf_finish(sb);
11318 	sbuf_delete(sb);
11319 
11320 	return (rc);
11321 }
11322 
11323 static int
11324 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
11325 {
11326 	struct adapter *sc = arg1;
11327 	struct sbuf *sb;
11328 	int rc, i;
11329 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
11330 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
11331 	uint32_t stats[T7_PM_RX_CACHE_NSTATS];
11332 	static const char *tx_stats[MAX_PM_NSTATS] = {
11333 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
11334 		"Tx FIFO wait", NULL, "Tx latency"
11335 	};
11336 	static const char *rx_stats[MAX_PM_NSTATS] = {
11337 		"Read:", "Write bypass:", "Write mem:", "Flush:",
11338 		"Rx FIFO wait", NULL, "Rx latency"
11339 	};
11340 
11341 	rc = 0;
11342 	mtx_lock(&sc->reg_lock);
11343 	if (hw_off_limits(sc))
11344 		rc = ENXIO;
11345 	else {
11346 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
11347 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
11348 		if (chip_id(sc) >= CHELSIO_T7)
11349 			t4_pmrx_cache_get_stats(sc, stats);
11350 	}
11351 	mtx_unlock(&sc->reg_lock);
11352 	if (rc != 0)
11353 		return (rc);
11354 
11355 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11356 	if (sb == NULL)
11357 		return (ENOMEM);
11358 
11359 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
11360 	for (i = 0; i < 4; i++) {
11361 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11362 		    tx_cyc[i]);
11363 	}
11364 
11365 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
11366 	for (i = 0; i < 4; i++) {
11367 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11368 		    rx_cyc[i]);
11369 	}
11370 
11371 	if (chip_id(sc) > CHELSIO_T5) {
11372 		sbuf_printf(sb,
11373 		    "\n              Total wait      Total occupancy");
11374 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11375 		    tx_cyc[i]);
11376 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11377 		    rx_cyc[i]);
11378 
11379 		i += 2;
11380 		MPASS(i < nitems(tx_stats));
11381 
11382 		sbuf_printf(sb,
11383 		    "\n                   Reads           Total wait");
11384 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11385 		    tx_cyc[i]);
11386 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11387 		    rx_cyc[i]);
11388 	}
11389 
11390 	if (chip_id(sc) >= CHELSIO_T7) {
11391 		i = 0;
11392 		sbuf_printf(sb, "\n\nPM RX Cache Stats\n");
11393 		sbuf_printf(sb, "%-40s    %u\n", "ReqWrite", stats[i++]);
11394 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadInv", stats[i++]);
11395 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadNoInv", stats[i++]);
11396 		sbuf_printf(sb, "%-40s    %u\n", "Write Split Request",
11397 			   stats[i++]);
11398 		sbuf_printf(sb, "%-40s    %u\n",
11399 			   "Normal Read Split (Read Invalidate)", stats[i++]);
11400 		sbuf_printf(sb, "%-40s    %u\n",
11401 			   "Feedback Read Split (Read NoInvalidate)",
11402 			   stats[i++]);
11403 		sbuf_printf(sb, "%-40s    %u\n", "Write Hit", stats[i++]);
11404 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit",
11405 			   stats[i++]);
11406 		sbuf_printf(sb, "%-40s    %u\n", "Feedback Read Hit",
11407 			   stats[i++]);
11408 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full Avail",
11409 			   stats[i++]);
11410 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full UnAvail",
11411 			   stats[i++]);
11412 		sbuf_printf(sb, "%-40s    %u\n",
11413 			   "Normal Read Hit Partial Avail",
11414 			   stats[i++]);
11415 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full Avail",
11416 			   stats[i++]);
11417 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full UnAvail",
11418 			   stats[i++]);
11419 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Partial Avail",
11420 			   stats[i++]);
11421 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Full Free",
11422 			   stats[i++]);
11423 		sbuf_printf(sb, "%-40s    %u\n",
11424 			   "Normal Read Part-avail Mul-Regions",
11425 			   stats[i++]);
11426 		sbuf_printf(sb, "%-40s    %u\n",
11427 			   "FB Read Part-avail Mul-Regions",
11428 			   stats[i++]);
11429 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss FL Used",
11430 			   stats[i++]);
11431 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss LRU Used",
11432 			   stats[i++]);
11433 		sbuf_printf(sb, "%-40s    %u\n",
11434 			   "Write Miss LRU-Multiple Evict", stats[i++]);
11435 		sbuf_printf(sb, "%-40s    %u\n",
11436 			   "Write Hit Increasing Islands", stats[i++]);
11437 		sbuf_printf(sb, "%-40s    %u\n",
11438 			   "Normal Read Island Read split", stats[i++]);
11439 		sbuf_printf(sb, "%-40s    %u\n", "Write Overflow Eviction",
11440 			   stats[i++]);
11441 		sbuf_printf(sb, "%-40s    %u", "Read Overflow Eviction",
11442 			   stats[i++]);
11443 	}
11444 
11445 	rc = sbuf_finish(sb);
11446 	sbuf_delete(sb);
11447 
11448 	return (rc);
11449 }
11450 
11451 static int
11452 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
11453 {
11454 	struct adapter *sc = arg1;
11455 	struct sbuf *sb;
11456 	int rc;
11457 	struct tp_rdma_stats stats;
11458 
11459 	rc = 0;
11460 	mtx_lock(&sc->reg_lock);
11461 	if (hw_off_limits(sc))
11462 		rc = ENXIO;
11463 	else
11464 		t4_tp_get_rdma_stats(sc, &stats, 0);
11465 	mtx_unlock(&sc->reg_lock);
11466 	if (rc != 0)
11467 		return (rc);
11468 
11469 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11470 	if (sb == NULL)
11471 		return (ENOMEM);
11472 
11473 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
11474 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
11475 
11476 	rc = sbuf_finish(sb);
11477 	sbuf_delete(sb);
11478 
11479 	return (rc);
11480 }
11481 
11482 static int
11483 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
11484 {
11485 	struct adapter *sc = arg1;
11486 	struct sbuf *sb;
11487 	int rc;
11488 	struct tp_tcp_stats v4, v6;
11489 
11490 	rc = 0;
11491 	mtx_lock(&sc->reg_lock);
11492 	if (hw_off_limits(sc))
11493 		rc = ENXIO;
11494 	else
11495 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
11496 	mtx_unlock(&sc->reg_lock);
11497 	if (rc != 0)
11498 		return (rc);
11499 
11500 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11501 	if (sb == NULL)
11502 		return (ENOMEM);
11503 
11504 	sbuf_printf(sb,
11505 	    "                                IP                 IPv6\n");
11506 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
11507 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
11508 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
11509 	    v4.tcp_in_segs, v6.tcp_in_segs);
11510 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
11511 	    v4.tcp_out_segs, v6.tcp_out_segs);
11512 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
11513 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
11514 
11515 	rc = sbuf_finish(sb);
11516 	sbuf_delete(sb);
11517 
11518 	return (rc);
11519 }
11520 
11521 static int
11522 sysctl_tids(SYSCTL_HANDLER_ARGS)
11523 {
11524 	struct adapter *sc = arg1;
11525 	struct sbuf *sb;
11526 	int rc;
11527 	uint32_t x, y;
11528 	struct tid_info *t = &sc->tids;
11529 
11530 	rc = 0;
11531 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11532 	if (sb == NULL)
11533 		return (ENOMEM);
11534 
11535 	if (t->natids) {
11536 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
11537 		    t->atids_in_use);
11538 	}
11539 
11540 	if (t->nhpftids) {
11541 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
11542 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
11543 	}
11544 
11545 	if (t->ntids) {
11546 		bool hashen = false;
11547 
11548 		mtx_lock(&sc->reg_lock);
11549 		if (hw_off_limits(sc))
11550 			rc = ENXIO;
11551 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
11552 			hashen = true;
11553 			if (chip_id(sc) <= CHELSIO_T5) {
11554 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
11555 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
11556 			} else {
11557 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
11558 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
11559 			}
11560 		}
11561 		mtx_unlock(&sc->reg_lock);
11562 		if (rc != 0)
11563 			goto done;
11564 
11565 		sbuf_printf(sb, "TID range: ");
11566 		if (hashen) {
11567 			if (x)
11568 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
11569 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
11570 		} else {
11571 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
11572 			    t->ntids - 1);
11573 		}
11574 		sbuf_printf(sb, ", in use: %u\n",
11575 		    atomic_load_acq_int(&t->tids_in_use));
11576 	}
11577 
11578 	if (t->nstids) {
11579 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
11580 		    t->stid_base + t->nstids - 1, t->stids_in_use);
11581 	}
11582 
11583 	if (t->nftids) {
11584 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
11585 		    t->ftid_end, t->ftids_in_use);
11586 	}
11587 
11588 	if (t->netids) {
11589 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
11590 		    t->etid_base + t->netids - 1, t->etids_in_use);
11591 	}
11592 
11593 	mtx_lock(&sc->reg_lock);
11594 	if (hw_off_limits(sc))
11595 		rc = ENXIO;
11596 	else {
11597 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
11598 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
11599 	}
11600 	mtx_unlock(&sc->reg_lock);
11601 	if (rc != 0)
11602 		goto done;
11603 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
11604 done:
11605 	if (rc == 0)
11606 		rc = sbuf_finish(sb);
11607 	else
11608 		(void)sbuf_finish(sb);
11609 	sbuf_delete(sb);
11610 
11611 	return (rc);
11612 }
11613 
11614 static int
11615 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
11616 {
11617 	struct adapter *sc = arg1;
11618 	struct sbuf *sb;
11619 	int rc;
11620 	struct tp_err_stats stats;
11621 
11622 	rc = 0;
11623 	mtx_lock(&sc->reg_lock);
11624 	if (hw_off_limits(sc))
11625 		rc = ENXIO;
11626 	else
11627 		t4_tp_get_err_stats(sc, &stats, 0);
11628 	mtx_unlock(&sc->reg_lock);
11629 	if (rc != 0)
11630 		return (rc);
11631 
11632 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11633 	if (sb == NULL)
11634 		return (ENOMEM);
11635 
11636 	if (sc->chip_params->nchan > 2) {
11637 		sbuf_printf(sb, "                 channel 0  channel 1"
11638 		    "  channel 2  channel 3\n");
11639 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
11640 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
11641 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
11642 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
11643 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
11644 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
11645 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
11646 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
11647 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
11648 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
11649 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
11650 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
11651 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
11652 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
11653 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
11654 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
11655 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
11656 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
11657 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
11658 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
11659 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
11660 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
11661 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
11662 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
11663 	} else {
11664 		sbuf_printf(sb, "                 channel 0  channel 1\n");
11665 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
11666 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
11667 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
11668 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
11669 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
11670 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
11671 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
11672 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
11673 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
11674 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
11675 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
11676 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
11677 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
11678 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
11679 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
11680 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
11681 	}
11682 
11683 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
11684 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
11685 
11686 	rc = sbuf_finish(sb);
11687 	sbuf_delete(sb);
11688 
11689 	return (rc);
11690 }
11691 
11692 static int
11693 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
11694 {
11695 	struct adapter *sc = arg1;
11696 	struct sbuf *sb;
11697 	int rc;
11698 	struct tp_tnl_stats stats;
11699 
11700 	rc = 0;
11701 	mtx_lock(&sc->reg_lock);
11702 	if (hw_off_limits(sc))
11703 		rc = ENXIO;
11704 	else
11705 		t4_tp_get_tnl_stats(sc, &stats, 1);
11706 	mtx_unlock(&sc->reg_lock);
11707 	if (rc != 0)
11708 		return (rc);
11709 
11710 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11711 	if (sb == NULL)
11712 		return (ENOMEM);
11713 
11714 	if (sc->chip_params->nchan > 2) {
11715 		sbuf_printf(sb, "           channel 0  channel 1"
11716 		    "  channel 2  channel 3\n");
11717 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
11718 		    stats.out_pkt[0], stats.out_pkt[1],
11719 		    stats.out_pkt[2], stats.out_pkt[3]);
11720 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
11721 		    stats.in_pkt[0], stats.in_pkt[1],
11722 		    stats.in_pkt[2], stats.in_pkt[3]);
11723 	} else {
11724 		sbuf_printf(sb, "           channel 0  channel 1\n");
11725 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
11726 		    stats.out_pkt[0], stats.out_pkt[1]);
11727 		sbuf_printf(sb, "InPkts:   %10u %10u",
11728 		    stats.in_pkt[0], stats.in_pkt[1]);
11729 	}
11730 
11731 	rc = sbuf_finish(sb);
11732 	sbuf_delete(sb);
11733 
11734 	return (rc);
11735 }
11736 
11737 static int
11738 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
11739 {
11740 	struct adapter *sc = arg1;
11741 	struct tp_params *tpp = &sc->params.tp;
11742 	u_int mask;
11743 	int rc;
11744 
11745 	mask = tpp->la_mask >> 16;
11746 	rc = sysctl_handle_int(oidp, &mask, 0, req);
11747 	if (rc != 0 || req->newptr == NULL)
11748 		return (rc);
11749 	if (mask > 0xffff)
11750 		return (EINVAL);
11751 	mtx_lock(&sc->reg_lock);
11752 	if (hw_off_limits(sc))
11753 		rc = ENXIO;
11754 	else {
11755 		tpp->la_mask = mask << 16;
11756 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
11757 		    tpp->la_mask);
11758 	}
11759 	mtx_unlock(&sc->reg_lock);
11760 
11761 	return (rc);
11762 }
11763 
11764 struct field_desc {
11765 	const char *name;
11766 	u_int start;
11767 	u_int width;
11768 };
11769 
11770 static void
11771 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
11772 {
11773 	char buf[32];
11774 	int line_size = 0;
11775 
11776 	while (f->name) {
11777 		uint64_t mask = (1ULL << f->width) - 1;
11778 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
11779 		    ((uintmax_t)v >> f->start) & mask);
11780 
11781 		if (line_size + len >= 79) {
11782 			line_size = 8;
11783 			sbuf_printf(sb, "\n        ");
11784 		}
11785 		sbuf_printf(sb, "%s ", buf);
11786 		line_size += len + 1;
11787 		f++;
11788 	}
11789 	sbuf_printf(sb, "\n");
11790 }
11791 
11792 static const struct field_desc tp_la0[] = {
11793 	{ "RcfOpCodeOut", 60, 4 },
11794 	{ "State", 56, 4 },
11795 	{ "WcfState", 52, 4 },
11796 	{ "RcfOpcSrcOut", 50, 2 },
11797 	{ "CRxError", 49, 1 },
11798 	{ "ERxError", 48, 1 },
11799 	{ "SanityFailed", 47, 1 },
11800 	{ "SpuriousMsg", 46, 1 },
11801 	{ "FlushInputMsg", 45, 1 },
11802 	{ "FlushInputCpl", 44, 1 },
11803 	{ "RssUpBit", 43, 1 },
11804 	{ "RssFilterHit", 42, 1 },
11805 	{ "Tid", 32, 10 },
11806 	{ "InitTcb", 31, 1 },
11807 	{ "LineNumber", 24, 7 },
11808 	{ "Emsg", 23, 1 },
11809 	{ "EdataOut", 22, 1 },
11810 	{ "Cmsg", 21, 1 },
11811 	{ "CdataOut", 20, 1 },
11812 	{ "EreadPdu", 19, 1 },
11813 	{ "CreadPdu", 18, 1 },
11814 	{ "TunnelPkt", 17, 1 },
11815 	{ "RcfPeerFin", 16, 1 },
11816 	{ "RcfReasonOut", 12, 4 },
11817 	{ "TxCchannel", 10, 2 },
11818 	{ "RcfTxChannel", 8, 2 },
11819 	{ "RxEchannel", 6, 2 },
11820 	{ "RcfRxChannel", 5, 1 },
11821 	{ "RcfDataOutSrdy", 4, 1 },
11822 	{ "RxDvld", 3, 1 },
11823 	{ "RxOoDvld", 2, 1 },
11824 	{ "RxCongestion", 1, 1 },
11825 	{ "TxCongestion", 0, 1 },
11826 	{ NULL }
11827 };
11828 
11829 static const struct field_desc tp_la1[] = {
11830 	{ "CplCmdIn", 56, 8 },
11831 	{ "CplCmdOut", 48, 8 },
11832 	{ "ESynOut", 47, 1 },
11833 	{ "EAckOut", 46, 1 },
11834 	{ "EFinOut", 45, 1 },
11835 	{ "ERstOut", 44, 1 },
11836 	{ "SynIn", 43, 1 },
11837 	{ "AckIn", 42, 1 },
11838 	{ "FinIn", 41, 1 },
11839 	{ "RstIn", 40, 1 },
11840 	{ "DataIn", 39, 1 },
11841 	{ "DataInVld", 38, 1 },
11842 	{ "PadIn", 37, 1 },
11843 	{ "RxBufEmpty", 36, 1 },
11844 	{ "RxDdp", 35, 1 },
11845 	{ "RxFbCongestion", 34, 1 },
11846 	{ "TxFbCongestion", 33, 1 },
11847 	{ "TxPktSumSrdy", 32, 1 },
11848 	{ "RcfUlpType", 28, 4 },
11849 	{ "Eread", 27, 1 },
11850 	{ "Ebypass", 26, 1 },
11851 	{ "Esave", 25, 1 },
11852 	{ "Static0", 24, 1 },
11853 	{ "Cread", 23, 1 },
11854 	{ "Cbypass", 22, 1 },
11855 	{ "Csave", 21, 1 },
11856 	{ "CPktOut", 20, 1 },
11857 	{ "RxPagePoolFull", 18, 2 },
11858 	{ "RxLpbkPkt", 17, 1 },
11859 	{ "TxLpbkPkt", 16, 1 },
11860 	{ "RxVfValid", 15, 1 },
11861 	{ "SynLearned", 14, 1 },
11862 	{ "SetDelEntry", 13, 1 },
11863 	{ "SetInvEntry", 12, 1 },
11864 	{ "CpcmdDvld", 11, 1 },
11865 	{ "CpcmdSave", 10, 1 },
11866 	{ "RxPstructsFull", 8, 2 },
11867 	{ "EpcmdDvld", 7, 1 },
11868 	{ "EpcmdFlush", 6, 1 },
11869 	{ "EpcmdTrimPrefix", 5, 1 },
11870 	{ "EpcmdTrimPostfix", 4, 1 },
11871 	{ "ERssIp4Pkt", 3, 1 },
11872 	{ "ERssIp6Pkt", 2, 1 },
11873 	{ "ERssTcpUdpPkt", 1, 1 },
11874 	{ "ERssFceFipPkt", 0, 1 },
11875 	{ NULL }
11876 };
11877 
11878 static const struct field_desc tp_la2[] = {
11879 	{ "CplCmdIn", 56, 8 },
11880 	{ "MpsVfVld", 55, 1 },
11881 	{ "MpsPf", 52, 3 },
11882 	{ "MpsVf", 44, 8 },
11883 	{ "SynIn", 43, 1 },
11884 	{ "AckIn", 42, 1 },
11885 	{ "FinIn", 41, 1 },
11886 	{ "RstIn", 40, 1 },
11887 	{ "DataIn", 39, 1 },
11888 	{ "DataInVld", 38, 1 },
11889 	{ "PadIn", 37, 1 },
11890 	{ "RxBufEmpty", 36, 1 },
11891 	{ "RxDdp", 35, 1 },
11892 	{ "RxFbCongestion", 34, 1 },
11893 	{ "TxFbCongestion", 33, 1 },
11894 	{ "TxPktSumSrdy", 32, 1 },
11895 	{ "RcfUlpType", 28, 4 },
11896 	{ "Eread", 27, 1 },
11897 	{ "Ebypass", 26, 1 },
11898 	{ "Esave", 25, 1 },
11899 	{ "Static0", 24, 1 },
11900 	{ "Cread", 23, 1 },
11901 	{ "Cbypass", 22, 1 },
11902 	{ "Csave", 21, 1 },
11903 	{ "CPktOut", 20, 1 },
11904 	{ "RxPagePoolFull", 18, 2 },
11905 	{ "RxLpbkPkt", 17, 1 },
11906 	{ "TxLpbkPkt", 16, 1 },
11907 	{ "RxVfValid", 15, 1 },
11908 	{ "SynLearned", 14, 1 },
11909 	{ "SetDelEntry", 13, 1 },
11910 	{ "SetInvEntry", 12, 1 },
11911 	{ "CpcmdDvld", 11, 1 },
11912 	{ "CpcmdSave", 10, 1 },
11913 	{ "RxPstructsFull", 8, 2 },
11914 	{ "EpcmdDvld", 7, 1 },
11915 	{ "EpcmdFlush", 6, 1 },
11916 	{ "EpcmdTrimPrefix", 5, 1 },
11917 	{ "EpcmdTrimPostfix", 4, 1 },
11918 	{ "ERssIp4Pkt", 3, 1 },
11919 	{ "ERssIp6Pkt", 2, 1 },
11920 	{ "ERssTcpUdpPkt", 1, 1 },
11921 	{ "ERssFceFipPkt", 0, 1 },
11922 	{ NULL }
11923 };
11924 
11925 static void
11926 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
11927 {
11928 
11929 	field_desc_show(sb, *p, tp_la0);
11930 }
11931 
11932 static void
11933 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
11934 {
11935 
11936 	if (idx)
11937 		sbuf_printf(sb, "\n");
11938 	field_desc_show(sb, p[0], tp_la0);
11939 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11940 		field_desc_show(sb, p[1], tp_la0);
11941 }
11942 
11943 static void
11944 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11945 {
11946 
11947 	if (idx)
11948 		sbuf_printf(sb, "\n");
11949 	field_desc_show(sb, p[0], tp_la0);
11950 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11951 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11952 }
11953 
11954 static int
11955 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11956 {
11957 	struct adapter *sc = arg1;
11958 	struct sbuf *sb;
11959 	uint64_t *buf, *p;
11960 	int rc;
11961 	u_int i, inc;
11962 	void (*show_func)(struct sbuf *, uint64_t *, int);
11963 
11964 	rc = 0;
11965 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11966 	if (sb == NULL)
11967 		return (ENOMEM);
11968 
11969 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11970 
11971 	mtx_lock(&sc->reg_lock);
11972 	if (hw_off_limits(sc))
11973 		rc = ENXIO;
11974 	else {
11975 		t4_tp_read_la(sc, buf, NULL);
11976 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11977 		case 2:
11978 			inc = 2;
11979 			show_func = tp_la_show2;
11980 			break;
11981 		case 3:
11982 			inc = 2;
11983 			show_func = tp_la_show3;
11984 			break;
11985 		default:
11986 			inc = 1;
11987 			show_func = tp_la_show;
11988 		}
11989 	}
11990 	mtx_unlock(&sc->reg_lock);
11991 	if (rc != 0)
11992 		goto done;
11993 
11994 	p = buf;
11995 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11996 		(*show_func)(sb, p, i);
11997 	rc = sbuf_finish(sb);
11998 done:
11999 	sbuf_delete(sb);
12000 	free(buf, M_CXGBE);
12001 	return (rc);
12002 }
12003 
12004 static int
12005 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
12006 {
12007 	struct adapter *sc = arg1;
12008 	struct sbuf *sb;
12009 	int rc;
12010 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
12011 
12012 	rc = 0;
12013 	mtx_lock(&sc->reg_lock);
12014 	if (hw_off_limits(sc))
12015 		rc = ENXIO;
12016 	else
12017 		t4_get_chan_txrate(sc, nrate, orate);
12018 	mtx_unlock(&sc->reg_lock);
12019 	if (rc != 0)
12020 		return (rc);
12021 
12022 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
12023 	if (sb == NULL)
12024 		return (ENOMEM);
12025 
12026 	if (sc->chip_params->nchan > 2) {
12027 		sbuf_printf(sb, "              channel 0   channel 1"
12028 		    "   channel 2   channel 3\n");
12029 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
12030 		    nrate[0], nrate[1], nrate[2], nrate[3]);
12031 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
12032 		    orate[0], orate[1], orate[2], orate[3]);
12033 	} else {
12034 		sbuf_printf(sb, "              channel 0   channel 1\n");
12035 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
12036 		    nrate[0], nrate[1]);
12037 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
12038 		    orate[0], orate[1]);
12039 	}
12040 
12041 	rc = sbuf_finish(sb);
12042 	sbuf_delete(sb);
12043 
12044 	return (rc);
12045 }
12046 
12047 static int
12048 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
12049 {
12050 	struct adapter *sc = arg1;
12051 	struct sbuf *sb;
12052 	uint32_t *buf, *p;
12053 	int rc, i;
12054 
12055 	rc = 0;
12056 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12057 	if (sb == NULL)
12058 		return (ENOMEM);
12059 
12060 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
12061 	    M_ZERO | M_WAITOK);
12062 
12063 	mtx_lock(&sc->reg_lock);
12064 	if (hw_off_limits(sc))
12065 		rc = ENXIO;
12066 	else
12067 		t4_ulprx_read_la(sc, buf);
12068 	mtx_unlock(&sc->reg_lock);
12069 	if (rc != 0)
12070 		goto done;
12071 
12072 	p = buf;
12073 	sbuf_printf(sb, "      Pcmd        Type   Message"
12074 	    "                Data");
12075 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
12076 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
12077 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
12078 	}
12079 	rc = sbuf_finish(sb);
12080 done:
12081 	sbuf_delete(sb);
12082 	free(buf, M_CXGBE);
12083 	return (rc);
12084 }
12085 
12086 static int
12087 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
12088 {
12089 	struct adapter *sc = arg1;
12090 	struct sbuf *sb;
12091 	int rc;
12092 	uint32_t cfg, s1, s2;
12093 
12094 	MPASS(chip_id(sc) >= CHELSIO_T5);
12095 
12096 	rc = 0;
12097 	mtx_lock(&sc->reg_lock);
12098 	if (hw_off_limits(sc))
12099 		rc = ENXIO;
12100 	else {
12101 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
12102 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
12103 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
12104 	}
12105 	mtx_unlock(&sc->reg_lock);
12106 	if (rc != 0)
12107 		return (rc);
12108 
12109 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12110 	if (sb == NULL)
12111 		return (ENOMEM);
12112 
12113 	if (G_STATSOURCE_T5(cfg) == 7) {
12114 		int mode;
12115 
12116 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
12117 		if (mode == 0)
12118 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
12119 		else if (mode == 1)
12120 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
12121 		else
12122 			sbuf_printf(sb, "unknown mode %d", mode);
12123 	}
12124 	rc = sbuf_finish(sb);
12125 	sbuf_delete(sb);
12126 
12127 	return (rc);
12128 }
12129 
12130 static int
12131 sysctl_cpus(SYSCTL_HANDLER_ARGS)
12132 {
12133 	struct adapter *sc = arg1;
12134 	enum cpu_sets op = arg2;
12135 	cpuset_t cpuset;
12136 	struct sbuf *sb;
12137 	int i, rc;
12138 
12139 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
12140 
12141 	CPU_ZERO(&cpuset);
12142 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
12143 	if (rc != 0)
12144 		return (rc);
12145 
12146 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12147 	if (sb == NULL)
12148 		return (ENOMEM);
12149 
12150 	CPU_FOREACH(i)
12151 		sbuf_printf(sb, "%d ", i);
12152 	rc = sbuf_finish(sb);
12153 	sbuf_delete(sb);
12154 
12155 	return (rc);
12156 }
12157 
12158 static int
12159 sysctl_reset(SYSCTL_HANDLER_ARGS)
12160 {
12161 	struct adapter *sc = arg1;
12162 	u_int val;
12163 	int rc;
12164 
12165 	val = atomic_load_int(&sc->num_resets);
12166 	rc = sysctl_handle_int(oidp, &val, 0, req);
12167 	if (rc != 0 || req->newptr == NULL)
12168 		return (rc);
12169 
12170 	if (val == 0) {
12171 		/* Zero out the counter that tracks reset. */
12172 		atomic_store_int(&sc->num_resets, 0);
12173 		return (0);
12174 	}
12175 
12176 	if (val != 1)
12177 		return (EINVAL);	/* 0 or 1 are the only legal values */
12178 
12179 	if (hw_off_limits(sc))		/* harmless race */
12180 		return (EALREADY);
12181 
12182 	taskqueue_enqueue(reset_tq, &sc->reset_task);
12183 	return (0);
12184 }
12185 
12186 #ifdef TCP_OFFLOAD
12187 static int
12188 sysctl_tls(SYSCTL_HANDLER_ARGS)
12189 {
12190 	struct adapter *sc = arg1;
12191 	int i, j, v, rc;
12192 	struct vi_info *vi;
12193 
12194 	v = sc->tt.tls;
12195 	rc = sysctl_handle_int(oidp, &v, 0, req);
12196 	if (rc != 0 || req->newptr == NULL)
12197 		return (rc);
12198 
12199 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
12200 		return (ENOTSUP);
12201 
12202 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
12203 	if (rc)
12204 		return (rc);
12205 	if (hw_off_limits(sc))
12206 		rc = ENXIO;
12207 	else {
12208 		sc->tt.tls = !!v;
12209 		for_each_port(sc, i) {
12210 			for_each_vi(sc->port[i], j, vi) {
12211 				if (vi->flags & VI_INIT_DONE)
12212 					t4_update_fl_bufsize(vi->ifp);
12213 			}
12214 		}
12215 	}
12216 	end_synchronized_op(sc, 0);
12217 
12218 	return (rc);
12219 
12220 }
12221 
12222 static void
12223 unit_conv(char *buf, size_t len, u_int val, u_int factor)
12224 {
12225 	u_int rem = val % factor;
12226 
12227 	if (rem == 0)
12228 		snprintf(buf, len, "%u", val / factor);
12229 	else {
12230 		while (rem % 10 == 0)
12231 			rem /= 10;
12232 		snprintf(buf, len, "%u.%u", val / factor, rem);
12233 	}
12234 }
12235 
12236 static int
12237 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
12238 {
12239 	struct adapter *sc = arg1;
12240 	char buf[16];
12241 	u_int res, re;
12242 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12243 
12244 	mtx_lock(&sc->reg_lock);
12245 	if (hw_off_limits(sc))
12246 		res = (u_int)-1;
12247 	else
12248 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
12249 	mtx_unlock(&sc->reg_lock);
12250 	if (res == (u_int)-1)
12251 		return (ENXIO);
12252 
12253 	switch (arg2) {
12254 	case 0:
12255 		/* timer_tick */
12256 		re = G_TIMERRESOLUTION(res);
12257 		break;
12258 	case 1:
12259 		/* TCP timestamp tick */
12260 		re = G_TIMESTAMPRESOLUTION(res);
12261 		break;
12262 	case 2:
12263 		/* DACK tick */
12264 		re = G_DELAYEDACKRESOLUTION(res);
12265 		break;
12266 	default:
12267 		return (EDOOFUS);
12268 	}
12269 
12270 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
12271 
12272 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
12273 }
12274 
12275 static int
12276 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
12277 {
12278 	struct adapter *sc = arg1;
12279 	int rc;
12280 	u_int dack_tmr, dack_re, v;
12281 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12282 
12283 	mtx_lock(&sc->reg_lock);
12284 	if (hw_off_limits(sc))
12285 		rc = ENXIO;
12286 	else {
12287 		rc = 0;
12288 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
12289 		    A_TP_TIMER_RESOLUTION));
12290 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
12291 	}
12292 	mtx_unlock(&sc->reg_lock);
12293 	if (rc != 0)
12294 		return (rc);
12295 
12296 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
12297 
12298 	return (sysctl_handle_int(oidp, &v, 0, req));
12299 }
12300 
12301 static int
12302 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
12303 {
12304 	struct adapter *sc = arg1;
12305 	int rc, reg = arg2;
12306 	u_int tre;
12307 	u_long tp_tick_us, v;
12308 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12309 
12310 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
12311 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
12312 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
12313 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
12314 
12315 	mtx_lock(&sc->reg_lock);
12316 	if (hw_off_limits(sc))
12317 		rc = ENXIO;
12318 	else {
12319 		rc = 0;
12320 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
12321 		tp_tick_us = (cclk_ps << tre) / 1000000;
12322 		if (reg == A_TP_INIT_SRTT)
12323 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
12324 		else
12325 			v = tp_tick_us * t4_read_reg(sc, reg);
12326 	}
12327 	mtx_unlock(&sc->reg_lock);
12328 	if (rc != 0)
12329 		return (rc);
12330 	else
12331 		return (sysctl_handle_long(oidp, &v, 0, req));
12332 }
12333 
12334 /*
12335  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
12336  * passed to this function.
12337  */
12338 static int
12339 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
12340 {
12341 	struct adapter *sc = arg1;
12342 	int rc, idx = arg2;
12343 	u_int v;
12344 
12345 	MPASS(idx >= 0 && idx <= 24);
12346 
12347 	mtx_lock(&sc->reg_lock);
12348 	if (hw_off_limits(sc))
12349 		rc = ENXIO;
12350 	else {
12351 		rc = 0;
12352 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
12353 	}
12354 	mtx_unlock(&sc->reg_lock);
12355 	if (rc != 0)
12356 		return (rc);
12357 	else
12358 		return (sysctl_handle_int(oidp, &v, 0, req));
12359 }
12360 
12361 static int
12362 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
12363 {
12364 	struct adapter *sc = arg1;
12365 	int rc, idx = arg2;
12366 	u_int shift, v, r;
12367 
12368 	MPASS(idx >= 0 && idx < 16);
12369 
12370 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
12371 	shift = (idx & 3) << 3;
12372 	mtx_lock(&sc->reg_lock);
12373 	if (hw_off_limits(sc))
12374 		rc = ENXIO;
12375 	else {
12376 		rc = 0;
12377 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
12378 	}
12379 	mtx_unlock(&sc->reg_lock);
12380 	if (rc != 0)
12381 		return (rc);
12382 	else
12383 		return (sysctl_handle_int(oidp, &v, 0, req));
12384 }
12385 
12386 static int
12387 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
12388 {
12389 	struct vi_info *vi = arg1;
12390 	struct adapter *sc = vi->adapter;
12391 	int idx, rc, i;
12392 	struct sge_ofld_rxq *ofld_rxq;
12393 	uint8_t v;
12394 
12395 	idx = vi->ofld_tmr_idx;
12396 
12397 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12398 	if (rc != 0 || req->newptr == NULL)
12399 		return (rc);
12400 
12401 	if (idx < 0 || idx >= SGE_NTIMERS)
12402 		return (EINVAL);
12403 
12404 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12405 	    "t4otmr");
12406 	if (rc)
12407 		return (rc);
12408 
12409 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
12410 	for_each_ofld_rxq(vi, i, ofld_rxq) {
12411 #ifdef atomic_store_rel_8
12412 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
12413 #else
12414 		ofld_rxq->iq.intr_params = v;
12415 #endif
12416 	}
12417 	vi->ofld_tmr_idx = idx;
12418 
12419 	end_synchronized_op(sc, LOCK_HELD);
12420 	return (0);
12421 }
12422 
12423 static int
12424 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
12425 {
12426 	struct vi_info *vi = arg1;
12427 	struct adapter *sc = vi->adapter;
12428 	int idx, rc;
12429 
12430 	idx = vi->ofld_pktc_idx;
12431 
12432 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12433 	if (rc != 0 || req->newptr == NULL)
12434 		return (rc);
12435 
12436 	if (idx < -1 || idx >= SGE_NCOUNTERS)
12437 		return (EINVAL);
12438 
12439 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12440 	    "t4opktc");
12441 	if (rc)
12442 		return (rc);
12443 
12444 	if (vi->flags & VI_INIT_DONE)
12445 		rc = EBUSY; /* cannot be changed once the queues are created */
12446 	else
12447 		vi->ofld_pktc_idx = idx;
12448 
12449 	end_synchronized_op(sc, LOCK_HELD);
12450 	return (rc);
12451 }
12452 #endif
12453 
12454 static int
12455 get_sge_context(struct adapter *sc, int mem_id, uint32_t cid, int len,
12456     uint32_t *data)
12457 {
12458 	int rc;
12459 
12460 	if (len < sc->chip_params->sge_ctxt_size)
12461 		return (ENOBUFS);
12462 	if (cid > M_CTXTQID)
12463 		return (EINVAL);
12464 	if (mem_id != CTXT_EGRESS && mem_id != CTXT_INGRESS &&
12465 	    mem_id != CTXT_FLM && mem_id != CTXT_CNM)
12466 		return (EINVAL);
12467 
12468 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
12469 	if (rc)
12470 		return (rc);
12471 
12472 	if (hw_off_limits(sc)) {
12473 		rc = ENXIO;
12474 		goto done;
12475 	}
12476 
12477 	if (sc->flags & FW_OK) {
12478 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cid, mem_id, data);
12479 		if (rc == 0)
12480 			goto done;
12481 	}
12482 
12483 	/*
12484 	 * Read via firmware failed or wasn't even attempted.  Read directly via
12485 	 * the backdoor.
12486 	 */
12487 	rc = -t4_sge_ctxt_rd_bd(sc, cid, mem_id, data);
12488 done:
12489 	end_synchronized_op(sc, 0);
12490 	return (rc);
12491 }
12492 
12493 static int
12494 load_fw(struct adapter *sc, struct t4_data *fw)
12495 {
12496 	int rc;
12497 	uint8_t *fw_data;
12498 
12499 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
12500 	if (rc)
12501 		return (rc);
12502 
12503 	if (hw_off_limits(sc)) {
12504 		rc = ENXIO;
12505 		goto done;
12506 	}
12507 
12508 	/*
12509 	 * The firmware, with the sole exception of the memory parity error
12510 	 * handler, runs from memory and not flash.  It is almost always safe to
12511 	 * install a new firmware on a running system.  Just set bit 1 in
12512 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
12513 	 */
12514 	if (sc->flags & FULL_INIT_DONE &&
12515 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
12516 		rc = EBUSY;
12517 		goto done;
12518 	}
12519 
12520 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
12521 
12522 	rc = copyin(fw->data, fw_data, fw->len);
12523 	if (rc == 0)
12524 		rc = -t4_load_fw(sc, fw_data, fw->len);
12525 
12526 	free(fw_data, M_CXGBE);
12527 done:
12528 	end_synchronized_op(sc, 0);
12529 	return (rc);
12530 }
12531 
12532 static int
12533 load_cfg(struct adapter *sc, struct t4_data *cfg)
12534 {
12535 	int rc;
12536 	uint8_t *cfg_data = NULL;
12537 
12538 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12539 	if (rc)
12540 		return (rc);
12541 
12542 	if (hw_off_limits(sc)) {
12543 		rc = ENXIO;
12544 		goto done;
12545 	}
12546 
12547 	if (cfg->len == 0) {
12548 		/* clear */
12549 		rc = -t4_load_cfg(sc, NULL, 0);
12550 		goto done;
12551 	}
12552 
12553 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
12554 
12555 	rc = copyin(cfg->data, cfg_data, cfg->len);
12556 	if (rc == 0)
12557 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
12558 
12559 	free(cfg_data, M_CXGBE);
12560 done:
12561 	end_synchronized_op(sc, 0);
12562 	return (rc);
12563 }
12564 
12565 static int
12566 load_boot(struct adapter *sc, struct t4_bootrom *br)
12567 {
12568 	int rc;
12569 	uint8_t *br_data = NULL;
12570 	u_int offset;
12571 
12572 	if (br->len > 1024 * 1024)
12573 		return (EFBIG);
12574 
12575 	if (br->pf_offset == 0) {
12576 		/* pfidx */
12577 		if (br->pfidx_addr > 7)
12578 			return (EINVAL);
12579 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
12580 		    A_PCIE_PF_EXPROM_OFST)));
12581 	} else if (br->pf_offset == 1) {
12582 		/* offset */
12583 		offset = G_OFFSET(br->pfidx_addr);
12584 	} else {
12585 		return (EINVAL);
12586 	}
12587 
12588 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
12589 	if (rc)
12590 		return (rc);
12591 
12592 	if (hw_off_limits(sc)) {
12593 		rc = ENXIO;
12594 		goto done;
12595 	}
12596 
12597 	if (br->len == 0) {
12598 		/* clear */
12599 		rc = -t4_load_boot(sc, NULL, offset, 0);
12600 		goto done;
12601 	}
12602 
12603 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
12604 
12605 	rc = copyin(br->data, br_data, br->len);
12606 	if (rc == 0)
12607 		rc = -t4_load_boot(sc, br_data, offset, br->len);
12608 
12609 	free(br_data, M_CXGBE);
12610 done:
12611 	end_synchronized_op(sc, 0);
12612 	return (rc);
12613 }
12614 
12615 static int
12616 load_bootcfg(struct adapter *sc, struct t4_data *bc)
12617 {
12618 	int rc;
12619 	uint8_t *bc_data = NULL;
12620 
12621 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12622 	if (rc)
12623 		return (rc);
12624 
12625 	if (hw_off_limits(sc)) {
12626 		rc = ENXIO;
12627 		goto done;
12628 	}
12629 
12630 	if (bc->len == 0) {
12631 		/* clear */
12632 		rc = -t4_load_bootcfg(sc, NULL, 0);
12633 		goto done;
12634 	}
12635 
12636 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
12637 
12638 	rc = copyin(bc->data, bc_data, bc->len);
12639 	if (rc == 0)
12640 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
12641 
12642 	free(bc_data, M_CXGBE);
12643 done:
12644 	end_synchronized_op(sc, 0);
12645 	return (rc);
12646 }
12647 
12648 static int
12649 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
12650 {
12651 	int rc;
12652 	struct cudbg_init *cudbg;
12653 	void *handle, *buf;
12654 
12655 	/* buf is large, don't block if no memory is available */
12656 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
12657 	if (buf == NULL)
12658 		return (ENOMEM);
12659 
12660 	handle = cudbg_alloc_handle();
12661 	if (handle == NULL) {
12662 		rc = ENOMEM;
12663 		goto done;
12664 	}
12665 
12666 	cudbg = cudbg_get_init(handle);
12667 	cudbg->adap = sc;
12668 	cudbg->print = (cudbg_print_cb)printf;
12669 
12670 #ifndef notyet
12671 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
12672 	    __func__, dump->wr_flash, dump->len, dump->data);
12673 #endif
12674 
12675 	if (dump->wr_flash)
12676 		cudbg->use_flash = 1;
12677 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
12678 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
12679 
12680 	rc = cudbg_collect(handle, buf, &dump->len);
12681 	if (rc != 0)
12682 		goto done;
12683 
12684 	rc = copyout(buf, dump->data, dump->len);
12685 done:
12686 	cudbg_free_handle(handle);
12687 	free(buf, M_CXGBE);
12688 	return (rc);
12689 }
12690 
12691 static void
12692 free_offload_policy(struct t4_offload_policy *op)
12693 {
12694 	struct offload_rule *r;
12695 	int i;
12696 
12697 	if (op == NULL)
12698 		return;
12699 
12700 	r = &op->rule[0];
12701 	for (i = 0; i < op->nrules; i++, r++) {
12702 		free(r->bpf_prog.bf_insns, M_CXGBE);
12703 	}
12704 	free(op->rule, M_CXGBE);
12705 	free(op, M_CXGBE);
12706 }
12707 
12708 static int
12709 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
12710 {
12711 	int i, rc, len;
12712 	struct t4_offload_policy *op, *old;
12713 	struct bpf_program *bf;
12714 	const struct offload_settings *s;
12715 	struct offload_rule *r;
12716 	void *u;
12717 
12718 	if (!is_offload(sc))
12719 		return (ENODEV);
12720 
12721 	if (uop->nrules == 0) {
12722 		/* Delete installed policies. */
12723 		op = NULL;
12724 		goto set_policy;
12725 	} else if (uop->nrules > 256) { /* arbitrary */
12726 		return (E2BIG);
12727 	}
12728 
12729 	/* Copy userspace offload policy to kernel */
12730 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
12731 	op->nrules = uop->nrules;
12732 	len = op->nrules * sizeof(struct offload_rule);
12733 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12734 	rc = copyin(uop->rule, op->rule, len);
12735 	if (rc) {
12736 		free(op->rule, M_CXGBE);
12737 		free(op, M_CXGBE);
12738 		return (rc);
12739 	}
12740 
12741 	r = &op->rule[0];
12742 	for (i = 0; i < op->nrules; i++, r++) {
12743 
12744 		/* Validate open_type */
12745 		if (r->open_type != OPEN_TYPE_LISTEN &&
12746 		    r->open_type != OPEN_TYPE_ACTIVE &&
12747 		    r->open_type != OPEN_TYPE_PASSIVE &&
12748 		    r->open_type != OPEN_TYPE_DONTCARE) {
12749 error:
12750 			/*
12751 			 * Rules 0 to i have malloc'd filters that need to be
12752 			 * freed.  Rules i+1 to nrules have userspace pointers
12753 			 * and should be left alone.
12754 			 */
12755 			op->nrules = i;
12756 			free_offload_policy(op);
12757 			return (rc);
12758 		}
12759 
12760 		/* Validate settings */
12761 		s = &r->settings;
12762 		if ((s->offload != 0 && s->offload != 1) ||
12763 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
12764 		    s->sched_class < -1 ||
12765 		    s->sched_class >= sc->params.nsched_cls) {
12766 			rc = EINVAL;
12767 			goto error;
12768 		}
12769 
12770 		bf = &r->bpf_prog;
12771 		u = bf->bf_insns;	/* userspace ptr */
12772 		bf->bf_insns = NULL;
12773 		if (bf->bf_len == 0) {
12774 			/* legal, matches everything */
12775 			continue;
12776 		}
12777 		len = bf->bf_len * sizeof(*bf->bf_insns);
12778 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12779 		rc = copyin(u, bf->bf_insns, len);
12780 		if (rc != 0)
12781 			goto error;
12782 
12783 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
12784 			rc = EINVAL;
12785 			goto error;
12786 		}
12787 	}
12788 set_policy:
12789 	rw_wlock(&sc->policy_lock);
12790 	old = sc->policy;
12791 	sc->policy = op;
12792 	rw_wunlock(&sc->policy_lock);
12793 	free_offload_policy(old);
12794 
12795 	return (0);
12796 }
12797 
12798 #define MAX_READ_BUF_SIZE (128 * 1024)
12799 static int
12800 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
12801 {
12802 	uint32_t addr, remaining, n;
12803 	uint32_t *buf;
12804 	int rc;
12805 	uint8_t *dst;
12806 
12807 	mtx_lock(&sc->reg_lock);
12808 	if (hw_off_limits(sc))
12809 		rc = ENXIO;
12810 	else
12811 		rc = validate_mem_range(sc, mr->addr, mr->len);
12812 	mtx_unlock(&sc->reg_lock);
12813 	if (rc != 0)
12814 		return (rc);
12815 
12816 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
12817 	addr = mr->addr;
12818 	remaining = mr->len;
12819 	dst = (void *)mr->data;
12820 
12821 	while (remaining) {
12822 		n = min(remaining, MAX_READ_BUF_SIZE);
12823 		mtx_lock(&sc->reg_lock);
12824 		if (hw_off_limits(sc))
12825 			rc = ENXIO;
12826 		else
12827 			read_via_memwin(sc, 2, addr, buf, n);
12828 		mtx_unlock(&sc->reg_lock);
12829 		if (rc != 0)
12830 			break;
12831 
12832 		rc = copyout(buf, dst, n);
12833 		if (rc != 0)
12834 			break;
12835 
12836 		dst += n;
12837 		remaining -= n;
12838 		addr += n;
12839 	}
12840 
12841 	free(buf, M_CXGBE);
12842 	return (rc);
12843 }
12844 #undef MAX_READ_BUF_SIZE
12845 
12846 static int
12847 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
12848 {
12849 	int rc;
12850 
12851 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
12852 		return (EINVAL);
12853 
12854 	if (i2cd->len > sizeof(i2cd->data))
12855 		return (EFBIG);
12856 
12857 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
12858 	if (rc)
12859 		return (rc);
12860 	if (hw_off_limits(sc))
12861 		rc = ENXIO;
12862 	else
12863 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
12864 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
12865 	end_synchronized_op(sc, 0);
12866 
12867 	return (rc);
12868 }
12869 
12870 static int
12871 clear_stats(struct adapter *sc, u_int port_id)
12872 {
12873 	int i, v, chan_map;
12874 	struct port_info *pi;
12875 	struct vi_info *vi;
12876 	struct sge_rxq *rxq;
12877 	struct sge_txq *txq;
12878 	struct sge_wrq *wrq;
12879 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12880 	struct sge_ofld_txq *ofld_txq;
12881 #endif
12882 #ifdef TCP_OFFLOAD
12883 	struct sge_ofld_rxq *ofld_rxq;
12884 #endif
12885 
12886 	if (port_id >= sc->params.nports)
12887 		return (EINVAL);
12888 	pi = sc->port[port_id];
12889 	if (pi == NULL)
12890 		return (EIO);
12891 
12892 	mtx_lock(&sc->reg_lock);
12893 	if (!hw_off_limits(sc)) {
12894 		/* MAC stats */
12895 		t4_clr_port_stats(sc, pi->hw_port);
12896 		if (is_t6(sc)) {
12897 			if (pi->fcs_reg != -1)
12898 				pi->fcs_base = t4_read_reg64(sc,
12899 				    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
12900 			else
12901 				pi->stats.rx_fcs_err = 0;
12902 		}
12903 		for_each_vi(pi, v, vi) {
12904 			if (vi->flags & VI_INIT_DONE)
12905 				t4_clr_vi_stats(sc, vi->vin);
12906 		}
12907 		chan_map = pi->rx_e_chan_map;
12908 		v = 0;	/* reuse */
12909 		while (chan_map) {
12910 			i = ffs(chan_map) - 1;
12911 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
12912 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
12913 			chan_map &= ~(1 << i);
12914 		}
12915 	}
12916 	mtx_unlock(&sc->reg_lock);
12917 	pi->tx_parse_error = 0;
12918 	pi->tnl_cong_drops = 0;
12919 
12920 	/*
12921 	 * Since this command accepts a port, clear stats for
12922 	 * all VIs on this port.
12923 	 */
12924 	for_each_vi(pi, v, vi) {
12925 		if (vi->flags & VI_INIT_DONE) {
12926 
12927 			for_each_rxq(vi, i, rxq) {
12928 #if defined(INET) || defined(INET6)
12929 				rxq->lro.lro_queued = 0;
12930 				rxq->lro.lro_flushed = 0;
12931 #endif
12932 				rxq->rxcsum = 0;
12933 				rxq->vlan_extraction = 0;
12934 				rxq->vxlan_rxcsum = 0;
12935 
12936 				rxq->fl.cl_allocated = 0;
12937 				rxq->fl.cl_recycled = 0;
12938 				rxq->fl.cl_fast_recycled = 0;
12939 			}
12940 
12941 			for_each_txq(vi, i, txq) {
12942 				txq->txcsum = 0;
12943 				txq->tso_wrs = 0;
12944 				txq->vlan_insertion = 0;
12945 				txq->imm_wrs = 0;
12946 				txq->sgl_wrs = 0;
12947 				txq->txpkt_wrs = 0;
12948 				txq->txpkts0_wrs = 0;
12949 				txq->txpkts1_wrs = 0;
12950 				txq->txpkts0_pkts = 0;
12951 				txq->txpkts1_pkts = 0;
12952 				txq->txpkts_flush = 0;
12953 				txq->raw_wrs = 0;
12954 				txq->vxlan_tso_wrs = 0;
12955 				txq->vxlan_txcsum = 0;
12956 				txq->kern_tls_records = 0;
12957 				txq->kern_tls_short = 0;
12958 				txq->kern_tls_partial = 0;
12959 				txq->kern_tls_full = 0;
12960 				txq->kern_tls_octets = 0;
12961 				txq->kern_tls_waste = 0;
12962 				txq->kern_tls_header = 0;
12963 				txq->kern_tls_fin_short = 0;
12964 				txq->kern_tls_cbc = 0;
12965 				txq->kern_tls_gcm = 0;
12966 				if (is_t6(sc)) {
12967 					txq->kern_tls_options = 0;
12968 					txq->kern_tls_fin = 0;
12969 				} else {
12970 					txq->kern_tls_ghash_received = 0;
12971 					txq->kern_tls_ghash_requested = 0;
12972 					txq->kern_tls_lso = 0;
12973 					txq->kern_tls_partial_ghash = 0;
12974 					txq->kern_tls_splitmode = 0;
12975 					txq->kern_tls_trailer = 0;
12976 				}
12977 				mp_ring_reset_stats(txq->r);
12978 			}
12979 
12980 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12981 			for_each_ofld_txq(vi, i, ofld_txq) {
12982 				ofld_txq->wrq.tx_wrs_direct = 0;
12983 				ofld_txq->wrq.tx_wrs_copied = 0;
12984 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12985 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12986 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12987 				counter_u64_zero(ofld_txq->tx_aio_jobs);
12988 				counter_u64_zero(ofld_txq->tx_aio_octets);
12989 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12990 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12991 			}
12992 #endif
12993 #ifdef TCP_OFFLOAD
12994 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12995 				ofld_rxq->fl.cl_allocated = 0;
12996 				ofld_rxq->fl.cl_recycled = 0;
12997 				ofld_rxq->fl.cl_fast_recycled = 0;
12998 				counter_u64_zero(
12999 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
13000 				counter_u64_zero(
13001 				    ofld_rxq->rx_iscsi_ddp_setup_error);
13002 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
13003 				ofld_rxq->rx_iscsi_ddp_octets = 0;
13004 				ofld_rxq->rx_iscsi_fl_pdus = 0;
13005 				ofld_rxq->rx_iscsi_fl_octets = 0;
13006 				ofld_rxq->rx_aio_ddp_jobs = 0;
13007 				ofld_rxq->rx_aio_ddp_octets = 0;
13008 				ofld_rxq->rx_toe_tls_records = 0;
13009 				ofld_rxq->rx_toe_tls_octets = 0;
13010 				ofld_rxq->rx_toe_ddp_octets = 0;
13011 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
13012 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
13013 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
13014 			}
13015 #endif
13016 
13017 			if (IS_MAIN_VI(vi)) {
13018 				wrq = &sc->sge.ctrlq[pi->port_id];
13019 				wrq->tx_wrs_direct = 0;
13020 				wrq->tx_wrs_copied = 0;
13021 			}
13022 		}
13023 	}
13024 
13025 	return (0);
13026 }
13027 
13028 static int
13029 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13030 {
13031 #ifdef INET6
13032 	struct in6_addr in6;
13033 
13034 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13035 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
13036 		return (0);
13037 	else
13038 		return (EIO);
13039 #else
13040 	return (ENOTSUP);
13041 #endif
13042 }
13043 
13044 static int
13045 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13046 {
13047 #ifdef INET6
13048 	struct in6_addr in6;
13049 
13050 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13051 	return (t4_release_clip_addr(sc, &in6));
13052 #else
13053 	return (ENOTSUP);
13054 #endif
13055 }
13056 
13057 int
13058 t4_os_find_pci_capability(struct adapter *sc, int cap)
13059 {
13060 	int i;
13061 
13062 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
13063 }
13064 
13065 void
13066 t4_os_portmod_changed(struct port_info *pi)
13067 {
13068 	struct adapter *sc = pi->adapter;
13069 	struct vi_info *vi;
13070 	if_t ifp;
13071 	static const char *mod_str[] = {
13072 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM",
13073 		"LR_SIMPLEX", "DR"
13074 	};
13075 
13076 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
13077 	    ("%s: port_type %u", __func__, pi->port_type));
13078 
13079 	vi = &pi->vi[0];
13080 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
13081 		PORT_LOCK(pi);
13082 		build_medialist(pi);
13083 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
13084 			fixup_link_config(pi);
13085 			apply_link_config(pi);
13086 		}
13087 		PORT_UNLOCK(pi);
13088 		end_synchronized_op(sc, LOCK_HELD);
13089 	}
13090 
13091 	ifp = vi->ifp;
13092 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
13093 		if_printf(ifp, "transceiver unplugged.\n");
13094 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
13095 		if_printf(ifp, "unknown transceiver inserted.\n");
13096 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
13097 		if_printf(ifp, "unsupported transceiver inserted.\n");
13098 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
13099 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
13100 		    port_top_speed(pi), mod_str[pi->mod_type]);
13101 	} else {
13102 		if_printf(ifp, "transceiver (type %d) inserted.\n",
13103 		    pi->mod_type);
13104 	}
13105 }
13106 
13107 void
13108 t4_os_link_changed(struct port_info *pi)
13109 {
13110 	struct vi_info *vi;
13111 	if_t ifp;
13112 	struct link_config *lc = &pi->link_cfg;
13113 	struct adapter *sc = pi->adapter;
13114 	int v;
13115 
13116 	PORT_LOCK_ASSERT_OWNED(pi);
13117 
13118 	if (is_t6(sc)) {
13119 		if (lc->link_ok) {
13120 			if (lc->speed > 25000 ||
13121 			    (lc->speed == 25000 && lc->fec == FEC_RS))
13122 				pi->fcs_reg = A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS;
13123 			else
13124 				pi->fcs_reg = A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS;
13125 			pi->fcs_base = t4_read_reg64(sc,
13126 			    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13127 			pi->stats.rx_fcs_err = 0;
13128 		} else {
13129 			pi->fcs_reg = -1;
13130 		}
13131 	} else {
13132 		MPASS(pi->fcs_reg != -1);
13133 		MPASS(pi->fcs_base == 0);
13134 	}
13135 
13136 	for_each_vi(pi, v, vi) {
13137 		ifp = vi->ifp;
13138 		if (ifp == NULL || IS_DETACHING(vi))
13139 			continue;
13140 
13141 		if (lc->link_ok) {
13142 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
13143 			if_link_state_change(ifp, LINK_STATE_UP);
13144 		} else {
13145 			if_link_state_change(ifp, LINK_STATE_DOWN);
13146 		}
13147 	}
13148 }
13149 
13150 void
13151 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
13152 {
13153 	struct adapter *sc;
13154 
13155 	sx_slock(&t4_list_lock);
13156 	SLIST_FOREACH(sc, &t4_list, link) {
13157 		/*
13158 		 * func should not make any assumptions about what state sc is
13159 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
13160 		 */
13161 		func(sc, arg);
13162 	}
13163 	sx_sunlock(&t4_list_lock);
13164 }
13165 
13166 static int
13167 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
13168     struct thread *td)
13169 {
13170 	int rc;
13171 	struct adapter *sc = dev->si_drv1;
13172 
13173 	rc = priv_check(td, PRIV_DRIVER);
13174 	if (rc != 0)
13175 		return (rc);
13176 
13177 	switch (cmd) {
13178 	case CHELSIO_T4_GETREG: {
13179 		struct t4_reg *edata = (struct t4_reg *)data;
13180 
13181 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13182 			return (EFAULT);
13183 
13184 		mtx_lock(&sc->reg_lock);
13185 		if (hw_off_limits(sc))
13186 			rc = ENXIO;
13187 		else if (edata->size == 4)
13188 			edata->val = t4_read_reg(sc, edata->addr);
13189 		else if (edata->size == 8)
13190 			edata->val = t4_read_reg64(sc, edata->addr);
13191 		else
13192 			rc = EINVAL;
13193 		mtx_unlock(&sc->reg_lock);
13194 
13195 		break;
13196 	}
13197 	case CHELSIO_T4_SETREG: {
13198 		struct t4_reg *edata = (struct t4_reg *)data;
13199 
13200 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13201 			return (EFAULT);
13202 
13203 		mtx_lock(&sc->reg_lock);
13204 		if (hw_off_limits(sc))
13205 			rc = ENXIO;
13206 		else if (edata->size == 4) {
13207 			if (edata->val & 0xffffffff00000000)
13208 				rc = EINVAL;
13209 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
13210 		} else if (edata->size == 8)
13211 			t4_write_reg64(sc, edata->addr, edata->val);
13212 		else
13213 			rc = EINVAL;
13214 		mtx_unlock(&sc->reg_lock);
13215 
13216 		break;
13217 	}
13218 	case CHELSIO_T4_REGDUMP: {
13219 		struct t4_regdump *regs = (struct t4_regdump *)data;
13220 		int reglen = t4_get_regs_len(sc);
13221 		uint8_t *buf;
13222 
13223 		if (regs->len < reglen) {
13224 			regs->len = reglen; /* hint to the caller */
13225 			return (ENOBUFS);
13226 		}
13227 
13228 		regs->len = reglen;
13229 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
13230 		mtx_lock(&sc->reg_lock);
13231 		if (hw_off_limits(sc))
13232 			rc = ENXIO;
13233 		else
13234 			get_regs(sc, regs, buf);
13235 		mtx_unlock(&sc->reg_lock);
13236 		if (rc == 0)
13237 			rc = copyout(buf, regs->data, reglen);
13238 		free(buf, M_CXGBE);
13239 		break;
13240 	}
13241 	case CHELSIO_T4_GET_FILTER_MODE:
13242 		rc = get_filter_mode(sc, (uint32_t *)data);
13243 		break;
13244 	case CHELSIO_T4_SET_FILTER_MODE:
13245 		rc = set_filter_mode(sc, *(uint32_t *)data);
13246 		break;
13247 	case CHELSIO_T4_SET_FILTER_MASK:
13248 		rc = set_filter_mask(sc, *(uint32_t *)data);
13249 		break;
13250 	case CHELSIO_T4_GET_FILTER:
13251 		rc = get_filter(sc, (struct t4_filter *)data);
13252 		break;
13253 	case CHELSIO_T4_SET_FILTER:
13254 		rc = set_filter(sc, (struct t4_filter *)data);
13255 		break;
13256 	case CHELSIO_T4_DEL_FILTER:
13257 		rc = del_filter(sc, (struct t4_filter *)data);
13258 		break;
13259 	case CHELSIO_T4_GET_SGE_CONTEXT: {
13260 		struct t4_sge_context *ctxt = (struct t4_sge_context *)data;
13261 
13262 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13263 		    sizeof(ctxt->data), &ctxt->data[0]);
13264 		break;
13265 	}
13266 	case CHELSIO_T4_LOAD_FW:
13267 		rc = load_fw(sc, (struct t4_data *)data);
13268 		break;
13269 	case CHELSIO_T4_GET_MEM:
13270 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
13271 		break;
13272 	case CHELSIO_T4_GET_I2C:
13273 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
13274 		break;
13275 	case CHELSIO_T4_CLEAR_STATS:
13276 		rc = clear_stats(sc, *(uint32_t *)data);
13277 		break;
13278 	case CHELSIO_T4_SCHED_CLASS:
13279 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
13280 		break;
13281 	case CHELSIO_T4_SCHED_QUEUE:
13282 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
13283 		break;
13284 	case CHELSIO_T4_GET_TRACER:
13285 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
13286 		break;
13287 	case CHELSIO_T4_SET_TRACER:
13288 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
13289 		break;
13290 	case CHELSIO_T4_LOAD_CFG:
13291 		rc = load_cfg(sc, (struct t4_data *)data);
13292 		break;
13293 	case CHELSIO_T4_LOAD_BOOT:
13294 		rc = load_boot(sc, (struct t4_bootrom *)data);
13295 		break;
13296 	case CHELSIO_T4_LOAD_BOOTCFG:
13297 		rc = load_bootcfg(sc, (struct t4_data *)data);
13298 		break;
13299 	case CHELSIO_T4_CUDBG_DUMP:
13300 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
13301 		break;
13302 	case CHELSIO_T4_SET_OFLD_POLICY:
13303 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
13304 		break;
13305 	case CHELSIO_T4_HOLD_CLIP_ADDR:
13306 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
13307 		break;
13308 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
13309 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
13310 		break;
13311 	case CHELSIO_T4_GET_SGE_CTXT: {
13312 		struct t4_sge_ctxt *ctxt = (struct t4_sge_ctxt *)data;
13313 
13314 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13315 		    sizeof(ctxt->data), &ctxt->data[0]);
13316 		break;
13317 	}
13318 	default:
13319 		rc = ENOTTY;
13320 	}
13321 
13322 	return (rc);
13323 }
13324 
13325 #ifdef TCP_OFFLOAD
13326 int
13327 toe_capability(struct vi_info *vi, bool enable)
13328 {
13329 	int rc;
13330 	struct port_info *pi = vi->pi;
13331 	struct adapter *sc = pi->adapter;
13332 
13333 	ASSERT_SYNCHRONIZED_OP(sc);
13334 
13335 	if (!is_offload(sc))
13336 		return (ENODEV);
13337 	if (!hw_all_ok(sc))
13338 		return (ENXIO);
13339 
13340 	if (enable) {
13341 #ifdef KERN_TLS
13342 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
13343 			int i, j, n;
13344 			struct port_info *p;
13345 			struct vi_info *v;
13346 
13347 			/*
13348 			 * Reconfigure hardware for TOE if TXTLS is not enabled
13349 			 * on any ifnet.
13350 			 */
13351 			n = 0;
13352 			for_each_port(sc, i) {
13353 				p = sc->port[i];
13354 				for_each_vi(p, j, v) {
13355 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
13356 						CH_WARN(sc,
13357 						    "%s has NIC TLS enabled.\n",
13358 						    device_get_nameunit(v->dev));
13359 						n++;
13360 					}
13361 				}
13362 			}
13363 			if (n > 0) {
13364 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
13365 				    "associated with this adapter before "
13366 				    "trying to enable TOE.\n");
13367 				return (EAGAIN);
13368 			}
13369 			rc = t6_config_kern_tls(sc, false);
13370 			if (rc)
13371 				return (rc);
13372 		}
13373 #endif
13374 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
13375 			/* TOE is already enabled. */
13376 			return (0);
13377 		}
13378 
13379 		/*
13380 		 * We need the port's queues around so that we're able to send
13381 		 * and receive CPLs to/from the TOE even if the ifnet for this
13382 		 * port has never been UP'd administratively.
13383 		 */
13384 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
13385 			return (rc);
13386 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
13387 		    ((rc = vi_init(&pi->vi[0])) != 0))
13388 			return (rc);
13389 
13390 		if (isset(&sc->offload_map, pi->port_id)) {
13391 			/* TOE is enabled on another VI of this port. */
13392 			MPASS(pi->uld_vis > 0);
13393 			pi->uld_vis++;
13394 			return (0);
13395 		}
13396 
13397 		if (!uld_active(sc, ULD_TOM)) {
13398 			rc = t4_activate_uld(sc, ULD_TOM);
13399 			if (rc == EAGAIN) {
13400 				log(LOG_WARNING,
13401 				    "You must kldload t4_tom.ko before trying "
13402 				    "to enable TOE on a cxgbe interface.\n");
13403 			}
13404 			if (rc != 0)
13405 				return (rc);
13406 			KASSERT(sc->tom_softc != NULL,
13407 			    ("%s: TOM activated but softc NULL", __func__));
13408 			KASSERT(uld_active(sc, ULD_TOM),
13409 			    ("%s: TOM activated but flag not set", __func__));
13410 		}
13411 
13412 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
13413 		if (!uld_active(sc, ULD_IWARP))
13414 			(void) t4_activate_uld(sc, ULD_IWARP);
13415 		if (!uld_active(sc, ULD_ISCSI))
13416 			(void) t4_activate_uld(sc, ULD_ISCSI);
13417 
13418 		if (pi->uld_vis++ == 0)
13419 			setbit(&sc->offload_map, pi->port_id);
13420 	} else {
13421 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
13422 			/* TOE is already disabled. */
13423 			return (0);
13424 		}
13425 		MPASS(isset(&sc->offload_map, pi->port_id));
13426 		MPASS(pi->uld_vis > 0);
13427 		if (--pi->uld_vis == 0)
13428 			clrbit(&sc->offload_map, pi->port_id);
13429 	}
13430 
13431 	return (0);
13432 }
13433 
13434 /*
13435  * Add an upper layer driver to the global list.
13436  */
13437 int
13438 t4_register_uld(struct uld_info *ui, int id)
13439 {
13440 	int rc;
13441 
13442 	if (id < 0 || id > ULD_MAX)
13443 		return (EINVAL);
13444 	sx_xlock(&t4_uld_list_lock);
13445 	if (t4_uld_list[id] != NULL)
13446 		rc = EEXIST;
13447 	else {
13448 		t4_uld_list[id] = ui;
13449 		rc = 0;
13450 	}
13451 	sx_xunlock(&t4_uld_list_lock);
13452 	return (rc);
13453 }
13454 
13455 int
13456 t4_unregister_uld(struct uld_info *ui, int id)
13457 {
13458 
13459 	if (id < 0 || id > ULD_MAX)
13460 		return (EINVAL);
13461 	sx_xlock(&t4_uld_list_lock);
13462 	MPASS(t4_uld_list[id] == ui);
13463 	t4_uld_list[id] = NULL;
13464 	sx_xunlock(&t4_uld_list_lock);
13465 	return (0);
13466 }
13467 
13468 int
13469 t4_activate_uld(struct adapter *sc, int id)
13470 {
13471 	int rc;
13472 
13473 	ASSERT_SYNCHRONIZED_OP(sc);
13474 
13475 	if (id < 0 || id > ULD_MAX)
13476 		return (EINVAL);
13477 
13478 	/* Adapter needs to be initialized before any ULD can be activated. */
13479 	if (!(sc->flags & FULL_INIT_DONE)) {
13480 		rc = adapter_init(sc);
13481 		if (rc != 0)
13482 			return (rc);
13483 	}
13484 
13485 	sx_slock(&t4_uld_list_lock);
13486 	if (t4_uld_list[id] == NULL)
13487 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
13488 	else {
13489 		rc = t4_uld_list[id]->uld_activate(sc);
13490 		if (rc == 0)
13491 			setbit(&sc->active_ulds, id);
13492 	}
13493 	sx_sunlock(&t4_uld_list_lock);
13494 
13495 	return (rc);
13496 }
13497 
13498 int
13499 t4_deactivate_uld(struct adapter *sc, int id)
13500 {
13501 	int rc;
13502 
13503 	ASSERT_SYNCHRONIZED_OP(sc);
13504 
13505 	if (id < 0 || id > ULD_MAX)
13506 		return (EINVAL);
13507 
13508 	sx_slock(&t4_uld_list_lock);
13509 	if (t4_uld_list[id] == NULL)
13510 		rc = ENXIO;
13511 	else {
13512 		rc = t4_uld_list[id]->uld_deactivate(sc);
13513 		if (rc == 0)
13514 			clrbit(&sc->active_ulds, id);
13515 	}
13516 	sx_sunlock(&t4_uld_list_lock);
13517 
13518 	return (rc);
13519 }
13520 
13521 static int
13522 deactivate_all_uld(struct adapter *sc)
13523 {
13524 	int i, rc;
13525 
13526 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
13527 	if (rc != 0)
13528 		return (ENXIO);
13529 	sx_slock(&t4_uld_list_lock);
13530 	for (i = 0; i <= ULD_MAX; i++) {
13531 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
13532 			continue;
13533 		rc = t4_uld_list[i]->uld_deactivate(sc);
13534 		if (rc != 0)
13535 			break;
13536 		clrbit(&sc->active_ulds, i);
13537 	}
13538 	sx_sunlock(&t4_uld_list_lock);
13539 	end_synchronized_op(sc, 0);
13540 
13541 	return (rc);
13542 }
13543 
13544 static void
13545 stop_all_uld(struct adapter *sc)
13546 {
13547 	int i;
13548 
13549 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
13550 		return;
13551 	sx_slock(&t4_uld_list_lock);
13552 	for (i = 0; i <= ULD_MAX; i++) {
13553 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13554 		    t4_uld_list[i]->uld_stop == NULL)
13555 			continue;
13556 		(void) t4_uld_list[i]->uld_stop(sc);
13557 	}
13558 	sx_sunlock(&t4_uld_list_lock);
13559 	end_synchronized_op(sc, 0);
13560 }
13561 
13562 static void
13563 restart_all_uld(struct adapter *sc)
13564 {
13565 	int i;
13566 
13567 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
13568 		return;
13569 	sx_slock(&t4_uld_list_lock);
13570 	for (i = 0; i <= ULD_MAX; i++) {
13571 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13572 		    t4_uld_list[i]->uld_restart == NULL)
13573 			continue;
13574 		(void) t4_uld_list[i]->uld_restart(sc);
13575 	}
13576 	sx_sunlock(&t4_uld_list_lock);
13577 	end_synchronized_op(sc, 0);
13578 }
13579 
13580 int
13581 uld_active(struct adapter *sc, int id)
13582 {
13583 
13584 	MPASS(id >= 0 && id <= ULD_MAX);
13585 
13586 	return (isset(&sc->active_ulds, id));
13587 }
13588 #endif
13589 
13590 #ifdef KERN_TLS
13591 static int
13592 ktls_capability(struct adapter *sc, bool enable)
13593 {
13594 	ASSERT_SYNCHRONIZED_OP(sc);
13595 
13596 	if (!is_ktls(sc))
13597 		return (ENODEV);
13598 	if (!is_t6(sc))
13599 		return (0);
13600 	if (!hw_all_ok(sc))
13601 		return (ENXIO);
13602 
13603 	if (enable) {
13604 		if (sc->flags & KERN_TLS_ON)
13605 			return (0);	/* already on */
13606 		if (sc->offload_map != 0) {
13607 			CH_WARN(sc,
13608 			    "Disable TOE on all interfaces associated with "
13609 			    "this adapter before trying to enable NIC TLS.\n");
13610 			return (EAGAIN);
13611 		}
13612 		return (t6_config_kern_tls(sc, true));
13613 	} else {
13614 		/*
13615 		 * Nothing to do for disable.  If TOE is enabled sometime later
13616 		 * then toe_capability will reconfigure the hardware.
13617 		 */
13618 		return (0);
13619 	}
13620 }
13621 #endif
13622 
13623 /*
13624  * t  = ptr to tunable.
13625  * nc = number of CPUs.
13626  * c  = compiled in default for that tunable.
13627  */
13628 static void
13629 calculate_nqueues(int *t, int nc, const int c)
13630 {
13631 	int nq;
13632 
13633 	if (*t > 0)
13634 		return;
13635 	nq = *t < 0 ? -*t : c;
13636 	*t = min(nc, nq);
13637 }
13638 
13639 /*
13640  * Come up with reasonable defaults for some of the tunables, provided they're
13641  * not set by the user (in which case we'll use the values as is).
13642  */
13643 static void
13644 tweak_tunables(void)
13645 {
13646 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
13647 
13648 	if (t4_ntxq < 1) {
13649 #ifdef RSS
13650 		t4_ntxq = rss_getnumbuckets();
13651 #else
13652 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
13653 #endif
13654 	}
13655 
13656 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
13657 
13658 	if (t4_nrxq < 1) {
13659 #ifdef RSS
13660 		t4_nrxq = rss_getnumbuckets();
13661 #else
13662 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
13663 #endif
13664 	}
13665 
13666 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
13667 
13668 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13669 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
13670 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
13671 #endif
13672 #ifdef TCP_OFFLOAD
13673 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
13674 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
13675 #endif
13676 
13677 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
13678 	if (t4_toecaps_allowed == -1)
13679 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
13680 #else
13681 	if (t4_toecaps_allowed == -1)
13682 		t4_toecaps_allowed = 0;
13683 #endif
13684 
13685 #ifdef TCP_OFFLOAD
13686 	if (t4_rdmacaps_allowed == -1) {
13687 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
13688 		    FW_CAPS_CONFIG_RDMA_RDMAC;
13689 	}
13690 
13691 	if (t4_iscsicaps_allowed == -1) {
13692 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
13693 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
13694 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
13695 	}
13696 
13697 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
13698 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
13699 
13700 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
13701 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
13702 #else
13703 	if (t4_rdmacaps_allowed == -1)
13704 		t4_rdmacaps_allowed = 0;
13705 
13706 	if (t4_iscsicaps_allowed == -1)
13707 		t4_iscsicaps_allowed = 0;
13708 #endif
13709 
13710 #ifdef DEV_NETMAP
13711 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
13712 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
13713 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
13714 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
13715 #endif
13716 
13717 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
13718 		t4_tmr_idx = TMR_IDX;
13719 
13720 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
13721 		t4_pktc_idx = PKTC_IDX;
13722 
13723 	if (t4_qsize_txq < 128)
13724 		t4_qsize_txq = 128;
13725 
13726 	if (t4_qsize_rxq < 128)
13727 		t4_qsize_rxq = 128;
13728 	while (t4_qsize_rxq & 7)
13729 		t4_qsize_rxq++;
13730 
13731 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
13732 
13733 	/*
13734 	 * Number of VIs to create per-port.  The first VI is the "main" regular
13735 	 * VI for the port.  The rest are additional virtual interfaces on the
13736 	 * same physical port.  Note that the main VI does not have native
13737 	 * netmap support but the extra VIs do.
13738 	 *
13739 	 * Limit the number of VIs per port to the number of available
13740 	 * MAC addresses per port.
13741 	 */
13742 	if (t4_num_vis < 1)
13743 		t4_num_vis = 1;
13744 	if (t4_num_vis > nitems(vi_mac_funcs)) {
13745 		t4_num_vis = nitems(vi_mac_funcs);
13746 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
13747 	}
13748 
13749 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
13750 		pcie_relaxed_ordering = 1;
13751 #if defined(__i386__) || defined(__amd64__)
13752 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
13753 			pcie_relaxed_ordering = 0;
13754 #endif
13755 	}
13756 }
13757 
13758 #ifdef DDB
13759 static void
13760 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
13761 {
13762 	uint32_t base, j, off, pf, reg, save, win_pos;
13763 
13764 	reg = chip_id(sc) > CHELSIO_T6 ?
13765 	    PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, 2) :
13766 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
13767 	save = t4_read_reg(sc, reg);
13768 	base = sc->memwin[2].mw_base;
13769 
13770 	if (is_t4(sc)) {
13771 		pf = 0;
13772 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
13773 	} else {
13774 		pf = V_PFNUM(sc->pf);
13775 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
13776 	}
13777 	off = addr - win_pos;
13778 	if (chip_id(sc) > CHELSIO_T6)
13779 		win_pos >>= X_T7_MEMOFST_SHIFT;
13780 	t4_write_reg(sc, reg, win_pos | pf);
13781 	t4_read_reg(sc, reg);
13782 
13783 	while (len > 0 && !db_pager_quit) {
13784 		uint32_t buf[8];
13785 		for (j = 0; j < 8; j++, off += 4)
13786 			buf[j] = htonl(t4_read_reg(sc, base + off));
13787 
13788 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
13789 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
13790 		    buf[7]);
13791 		if (len <= sizeof(buf))
13792 			len = 0;
13793 		else
13794 			len -= sizeof(buf);
13795 	}
13796 
13797 	t4_write_reg(sc, reg, save);
13798 	t4_read_reg(sc, reg);
13799 }
13800 
13801 static void
13802 t4_dump_tcb(struct adapter *sc, int tid)
13803 {
13804 	uint32_t tcb_addr;
13805 
13806 	/* Dump TCB for the tid */
13807 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
13808 	tcb_addr += tid * TCB_SIZE;
13809 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
13810 }
13811 
13812 static void
13813 t4_dump_devlog(struct adapter *sc)
13814 {
13815 	struct devlog_params *dparams = &sc->params.devlog;
13816 	struct fw_devlog_e e;
13817 	int i, first, j, m, nentries, rc;
13818 	uint64_t ftstamp = UINT64_MAX;
13819 
13820 	if (dparams->start == 0) {
13821 		db_printf("devlog params not valid\n");
13822 		return;
13823 	}
13824 
13825 	nentries = dparams->size / sizeof(struct fw_devlog_e);
13826 	m = fwmtype_to_hwmtype(dparams->memtype);
13827 
13828 	/* Find the first entry. */
13829 	first = -1;
13830 	for (i = 0; i < nentries && !db_pager_quit; i++) {
13831 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13832 		    sizeof(e), (void *)&e);
13833 		if (rc != 0)
13834 			break;
13835 
13836 		if (e.timestamp == 0)
13837 			break;
13838 
13839 		e.timestamp = be64toh(e.timestamp);
13840 		if (e.timestamp < ftstamp) {
13841 			ftstamp = e.timestamp;
13842 			first = i;
13843 		}
13844 	}
13845 
13846 	if (first == -1)
13847 		return;
13848 
13849 	i = first;
13850 	do {
13851 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
13852 		    sizeof(e), (void *)&e);
13853 		if (rc != 0)
13854 			return;
13855 
13856 		if (e.timestamp == 0)
13857 			return;
13858 
13859 		e.timestamp = be64toh(e.timestamp);
13860 		e.seqno = be32toh(e.seqno);
13861 		for (j = 0; j < 8; j++)
13862 			e.params[j] = be32toh(e.params[j]);
13863 
13864 		db_printf("%10d  %15ju  %8s  %8s  ",
13865 		    e.seqno, e.timestamp,
13866 		    (e.level < nitems(devlog_level_strings) ?
13867 			devlog_level_strings[e.level] : "UNKNOWN"),
13868 		    (e.facility < nitems(devlog_facility_strings) ?
13869 			devlog_facility_strings[e.facility] : "UNKNOWN"));
13870 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
13871 		    e.params[3], e.params[4], e.params[5], e.params[6],
13872 		    e.params[7]);
13873 
13874 		if (++i == nentries)
13875 			i = 0;
13876 	} while (i != first && !db_pager_quit);
13877 }
13878 
13879 static DB_DEFINE_TABLE(show, t4, show_t4);
13880 
13881 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
13882 {
13883 	device_t dev;
13884 	int t;
13885 	bool valid;
13886 
13887 	valid = false;
13888 	t = db_read_token();
13889 	if (t == tIDENT) {
13890 		dev = device_lookup_by_name(db_tok_string);
13891 		valid = true;
13892 	}
13893 	db_skip_to_eol();
13894 	if (!valid) {
13895 		db_printf("usage: show t4 devlog <nexus>\n");
13896 		return;
13897 	}
13898 
13899 	if (dev == NULL) {
13900 		db_printf("device not found\n");
13901 		return;
13902 	}
13903 
13904 	t4_dump_devlog(device_get_softc(dev));
13905 }
13906 
13907 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
13908 {
13909 	device_t dev;
13910 	int radix, tid, t;
13911 	bool valid;
13912 
13913 	valid = false;
13914 	radix = db_radix;
13915 	db_radix = 10;
13916 	t = db_read_token();
13917 	if (t == tIDENT) {
13918 		dev = device_lookup_by_name(db_tok_string);
13919 		t = db_read_token();
13920 		if (t == tNUMBER) {
13921 			tid = db_tok_number;
13922 			valid = true;
13923 		}
13924 	}
13925 	db_radix = radix;
13926 	db_skip_to_eol();
13927 	if (!valid) {
13928 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13929 		return;
13930 	}
13931 
13932 	if (dev == NULL) {
13933 		db_printf("device not found\n");
13934 		return;
13935 	}
13936 	if (tid < 0) {
13937 		db_printf("invalid tid\n");
13938 		return;
13939 	}
13940 
13941 	t4_dump_tcb(device_get_softc(dev), tid);
13942 }
13943 
13944 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
13945 {
13946 	device_t dev;
13947 	int radix, t;
13948 	bool valid;
13949 
13950 	valid = false;
13951 	radix = db_radix;
13952 	db_radix = 10;
13953 	t = db_read_token();
13954 	if (t == tIDENT) {
13955 		dev = device_lookup_by_name(db_tok_string);
13956 		t = db_read_token();
13957 		if (t == tNUMBER) {
13958 			addr = db_tok_number;
13959 			t = db_read_token();
13960 			if (t == tNUMBER) {
13961 				count = db_tok_number;
13962 				valid = true;
13963 			}
13964 		}
13965 	}
13966 	db_radix = radix;
13967 	db_skip_to_eol();
13968 	if (!valid) {
13969 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
13970 		return;
13971 	}
13972 
13973 	if (dev == NULL) {
13974 		db_printf("device not found\n");
13975 		return;
13976 	}
13977 	if (addr < 0) {
13978 		db_printf("invalid address\n");
13979 		return;
13980 	}
13981 	if (count <= 0) {
13982 		db_printf("invalid length\n");
13983 		return;
13984 	}
13985 
13986 	t4_dump_mem(device_get_softc(dev), addr, count);
13987 }
13988 #endif
13989 
13990 static eventhandler_tag vxlan_start_evtag;
13991 static eventhandler_tag vxlan_stop_evtag;
13992 
13993 struct vxlan_evargs {
13994 	if_t ifp;
13995 	uint16_t port;
13996 };
13997 
13998 static void
13999 enable_vxlan_rx(struct adapter *sc)
14000 {
14001 	int i, rc;
14002 	struct port_info *pi;
14003 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
14004 
14005 	ASSERT_SYNCHRONIZED_OP(sc);
14006 
14007 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
14008 	    F_VXLAN_EN);
14009 	for_each_port(sc, i) {
14010 		pi = sc->port[i];
14011 		if (pi->vxlan_tcam_entry == true)
14012 			continue;
14013 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
14014 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
14015 		    true);
14016 		if (rc < 0) {
14017 			rc = -rc;
14018 			CH_ERR(&pi->vi[0],
14019 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
14020 		} else {
14021 			MPASS(rc == sc->rawf_base + pi->port_id);
14022 			pi->vxlan_tcam_entry = true;
14023 		}
14024 	}
14025 }
14026 
14027 static void
14028 t4_vxlan_start(struct adapter *sc, void *arg)
14029 {
14030 	struct vxlan_evargs *v = arg;
14031 
14032 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14033 		return;
14034 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
14035 		return;
14036 
14037 	if (sc->vxlan_refcount == 0) {
14038 		sc->vxlan_port = v->port;
14039 		sc->vxlan_refcount = 1;
14040 		if (!hw_off_limits(sc))
14041 			enable_vxlan_rx(sc);
14042 	} else if (sc->vxlan_port == v->port) {
14043 		sc->vxlan_refcount++;
14044 	} else {
14045 		CH_ERR(sc, "VXLAN already configured on port  %d; "
14046 		    "ignoring attempt to configure it on port %d\n",
14047 		    sc->vxlan_port, v->port);
14048 	}
14049 	end_synchronized_op(sc, 0);
14050 }
14051 
14052 static void
14053 t4_vxlan_stop(struct adapter *sc, void *arg)
14054 {
14055 	struct vxlan_evargs *v = arg;
14056 
14057 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14058 		return;
14059 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
14060 		return;
14061 
14062 	/*
14063 	 * VXLANs may have been configured before the driver was loaded so we
14064 	 * may see more stops than starts.  This is not handled cleanly but at
14065 	 * least we keep the refcount sane.
14066 	 */
14067 	if (sc->vxlan_port != v->port)
14068 		goto done;
14069 	if (sc->vxlan_refcount == 0) {
14070 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
14071 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
14072 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
14073 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
14074 done:
14075 	end_synchronized_op(sc, 0);
14076 }
14077 
14078 static void
14079 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
14080     sa_family_t family, u_int port)
14081 {
14082 	struct vxlan_evargs v;
14083 
14084 	MPASS(family == AF_INET || family == AF_INET6);
14085 	v.ifp = ifp;
14086 	v.port = port;
14087 
14088 	t4_iterate(t4_vxlan_start, &v);
14089 }
14090 
14091 static void
14092 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
14093     u_int port)
14094 {
14095 	struct vxlan_evargs v;
14096 
14097 	MPASS(family == AF_INET || family == AF_INET6);
14098 	v.ifp = ifp;
14099 	v.port = port;
14100 
14101 	t4_iterate(t4_vxlan_stop, &v);
14102 }
14103 
14104 
14105 static struct sx mlu;	/* mod load unload */
14106 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
14107 
14108 static int
14109 mod_event(module_t mod, int cmd, void *arg)
14110 {
14111 	int rc = 0;
14112 	static int loaded = 0;
14113 
14114 	switch (cmd) {
14115 	case MOD_LOAD:
14116 		sx_xlock(&mlu);
14117 		if (loaded++ == 0) {
14118 			t4_sge_modload();
14119 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14120 			    t4_filter_rpl, CPL_COOKIE_FILTER);
14121 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
14122 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
14123 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
14124 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
14125 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14126 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
14127 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
14128 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
14129 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
14130 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
14131 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
14132 			    do_smt_write_rpl);
14133 			sx_init(&t4_list_lock, "T4/T5 adapters");
14134 			SLIST_INIT(&t4_list);
14135 			callout_init(&fatal_callout, 1);
14136 #ifdef TCP_OFFLOAD
14137 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
14138 #endif
14139 #ifdef INET6
14140 			t4_clip_modload();
14141 #endif
14142 #ifdef KERN_TLS
14143 			t6_ktls_modload();
14144 			t7_ktls_modload();
14145 #endif
14146 			t4_tracer_modload();
14147 			tweak_tunables();
14148 			vxlan_start_evtag =
14149 			    EVENTHANDLER_REGISTER(vxlan_start,
14150 				t4_vxlan_start_handler, NULL,
14151 				EVENTHANDLER_PRI_ANY);
14152 			vxlan_stop_evtag =
14153 			    EVENTHANDLER_REGISTER(vxlan_stop,
14154 				t4_vxlan_stop_handler, NULL,
14155 				EVENTHANDLER_PRI_ANY);
14156 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
14157 			    taskqueue_thread_enqueue, &reset_tq);
14158 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
14159 			    "t4_rst_thr");
14160 		}
14161 		sx_xunlock(&mlu);
14162 		break;
14163 
14164 	case MOD_UNLOAD:
14165 		sx_xlock(&mlu);
14166 		if (--loaded == 0) {
14167 #ifdef TCP_OFFLOAD
14168 			int i;
14169 #endif
14170 			int tries;
14171 
14172 			taskqueue_free(reset_tq);
14173 
14174 			tries = 0;
14175 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
14176 				uprintf("%ju clusters with custom free routine "
14177 				    "still is use.\n", t4_sge_extfree_refs());
14178 				pause("t4unload", 2 * hz);
14179 			}
14180 
14181 			sx_slock(&t4_list_lock);
14182 			if (!SLIST_EMPTY(&t4_list)) {
14183 				rc = EBUSY;
14184 				sx_sunlock(&t4_list_lock);
14185 				goto done_unload;
14186 			}
14187 #ifdef TCP_OFFLOAD
14188 			sx_slock(&t4_uld_list_lock);
14189 			for (i = 0; i <= ULD_MAX; i++) {
14190 				if (t4_uld_list[i] != NULL) {
14191 					rc = EBUSY;
14192 					sx_sunlock(&t4_uld_list_lock);
14193 					sx_sunlock(&t4_list_lock);
14194 					goto done_unload;
14195 				}
14196 			}
14197 			sx_sunlock(&t4_uld_list_lock);
14198 #endif
14199 			sx_sunlock(&t4_list_lock);
14200 
14201 			if (t4_sge_extfree_refs() == 0) {
14202 				EVENTHANDLER_DEREGISTER(vxlan_start,
14203 				    vxlan_start_evtag);
14204 				EVENTHANDLER_DEREGISTER(vxlan_stop,
14205 				    vxlan_stop_evtag);
14206 				t4_tracer_modunload();
14207 #ifdef KERN_TLS
14208 				t7_ktls_modunload();
14209 				t6_ktls_modunload();
14210 #endif
14211 #ifdef INET6
14212 				t4_clip_modunload();
14213 #endif
14214 #ifdef TCP_OFFLOAD
14215 				sx_destroy(&t4_uld_list_lock);
14216 #endif
14217 				sx_destroy(&t4_list_lock);
14218 				t4_sge_modunload();
14219 				loaded = 0;
14220 			} else {
14221 				rc = EBUSY;
14222 				loaded++;	/* undo earlier decrement */
14223 			}
14224 		}
14225 done_unload:
14226 		sx_xunlock(&mlu);
14227 		break;
14228 	}
14229 
14230 	return (rc);
14231 }
14232 
14233 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
14234 MODULE_VERSION(t4nex, 1);
14235 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
14236 #ifdef DEV_NETMAP
14237 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
14238 #endif /* DEV_NETMAP */
14239 
14240 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
14241 MODULE_VERSION(t5nex, 1);
14242 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
14243 #ifdef DEV_NETMAP
14244 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
14245 #endif /* DEV_NETMAP */
14246 
14247 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
14248 MODULE_VERSION(t6nex, 1);
14249 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
14250 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
14251 #ifdef DEV_NETMAP
14252 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
14253 #endif /* DEV_NETMAP */
14254 
14255 DRIVER_MODULE(chnex, pci, ch_driver, mod_event, 0);
14256 MODULE_VERSION(chnex, 1);
14257 MODULE_DEPEND(chnex, crypto, 1, 1, 1);
14258 MODULE_DEPEND(chnex, firmware, 1, 1, 1);
14259 #ifdef DEV_NETMAP
14260 MODULE_DEPEND(chnex, netmap, 1, 1, 1);
14261 #endif /* DEV_NETMAP */
14262 
14263 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
14264 MODULE_VERSION(cxgbe, 1);
14265 
14266 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
14267 MODULE_VERSION(cxl, 1);
14268 
14269 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
14270 MODULE_VERSION(cc, 1);
14271 
14272 DRIVER_MODULE(che, chnex, che_driver, 0, 0);
14273 MODULE_VERSION(che, 1);
14274 
14275 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
14276 MODULE_VERSION(vcxgbe, 1);
14277 
14278 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
14279 MODULE_VERSION(vcxl, 1);
14280 
14281 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
14282 MODULE_VERSION(vcc, 1);
14283 
14284 DRIVER_MODULE(vche, che, vche_driver, 0, 0);
14285 MODULE_VERSION(vche, 1);
14286