xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision c4fde87a3236b500246d4fce76dbca2a3d64f73a)
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/nv.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <dev/pci/pcireg.h>
49 #include <dev/pci/pcivar.h>
50 #include <sys/firmware.h>
51 #include <sys/sbuf.h>
52 #include <sys/smp.h>
53 #include <sys/socket.h>
54 #include <sys/sockio.h>
55 #include <sys/sysctl.h>
56 #include <net/ethernet.h>
57 #include <net/if.h>
58 #include <net/if_types.h>
59 #include <net/if_dl.h>
60 #include <net/if_vlan_var.h>
61 #include <net/if_vf_status.h>
62 #include <net/rss_config.h>
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 	DEVMETHOD_END
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 	DEVMETHOD_END
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_vf_status(if_t, struct if_vf_status **);
286 static int cxgbe_transmit(if_t, struct mbuf *);
287 static void cxgbe_qflush(if_t);
288 #if defined(KERN_TLS) || defined(RATELIMIT)
289 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
290     struct m_snd_tag **);
291 #endif
292 
293 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
294 
295 /*
296  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
297  * then ADAPTER_LOCK, then t4_uld_list_lock.
298  */
299 static struct sx t4_list_lock;
300 SLIST_HEAD(, adapter) t4_list;
301 #ifdef TCP_OFFLOAD
302 static struct sx t4_uld_list_lock;
303 struct uld_info *t4_uld_list[ULD_MAX + 1];
304 #endif
305 
306 /*
307  * Tunables.  See tweak_tunables() too.
308  *
309  * Each tunable is set to a default value here if it's known at compile-time.
310  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
311  * provide a reasonable default (upto n) when the driver is loaded.
312  *
313  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
314  * T5 are under hw.cxl.
315  */
316 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
317     "cxgbe(4) parameters");
318 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
319     "cxgbe(4) T5+ parameters");
320 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
321     "cxgbe(4) TOE parameters");
322 
323 /*
324  * Number of queues for tx and rx, NIC and offload.
325  */
326 #define NTXQ 16
327 int t4_ntxq = -NTXQ;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
329     "Number of TX queues per port");
330 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
331 
332 #define NRXQ 8
333 int t4_nrxq = -NRXQ;
334 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
335     "Number of RX queues per port");
336 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
337 
338 #define NTXQ_VI 1
339 static int t4_ntxq_vi = -NTXQ_VI;
340 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
341     "Number of TX queues per VI");
342 
343 #define NRXQ_VI 1
344 static int t4_nrxq_vi = -NRXQ_VI;
345 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
346     "Number of RX queues per VI");
347 
348 static int t4_rsrv_noflowq = 0;
349 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
350     0, "Reserve TX queue 0 of each VI for non-flowid packets");
351 
352 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
353 #define NOFLDTXQ 8
354 static int t4_nofldtxq = -NOFLDTXQ;
355 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
356     "Number of offload TX queues per port");
357 
358 #define NOFLDTXQ_VI 1
359 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
360 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
361     "Number of offload TX queues per VI");
362 #endif
363 
364 #if defined(TCP_OFFLOAD)
365 #define NOFLDRXQ 2
366 static int t4_nofldrxq = -NOFLDRXQ;
367 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
368     "Number of offload RX queues per port");
369 
370 #define NOFLDRXQ_VI 1
371 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
372 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
373     "Number of offload RX queues per VI");
374 
375 #define TMR_IDX_OFLD 1
376 static int t4_tmr_idx_ofld = TMR_IDX_OFLD;
377 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
378     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
379 
380 #define PKTC_IDX_OFLD (-1)
381 static int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
382 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
383     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
384 
385 /* 0 means chip/fw default, non-zero number is value in microseconds */
386 static u_long t4_toe_keepalive_idle = 0;
387 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
388     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
389 
390 /* 0 means chip/fw default, non-zero number is value in microseconds */
391 static u_long t4_toe_keepalive_interval = 0;
392 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
393     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
394 
395 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
396 static int t4_toe_keepalive_count = 0;
397 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
398     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
399 
400 /* 0 means chip/fw default, non-zero number is value in microseconds */
401 static u_long t4_toe_rexmt_min = 0;
402 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
403     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
404 
405 /* 0 means chip/fw default, non-zero number is value in microseconds */
406 static u_long t4_toe_rexmt_max = 0;
407 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
409 
410 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
411 static int t4_toe_rexmt_count = 0;
412 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
413     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
414 
415 /* -1 means chip/fw default, other values are raw backoff values to use */
416 static int t4_toe_rexmt_backoff[16] = {
417 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
418 };
419 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
420     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
421     "cxgbe(4) TOE retransmit backoff values");
422 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
423     &t4_toe_rexmt_backoff[0], 0, "");
424 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
425     &t4_toe_rexmt_backoff[1], 0, "");
426 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
427     &t4_toe_rexmt_backoff[2], 0, "");
428 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
429     &t4_toe_rexmt_backoff[3], 0, "");
430 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
431     &t4_toe_rexmt_backoff[4], 0, "");
432 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
433     &t4_toe_rexmt_backoff[5], 0, "");
434 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
435     &t4_toe_rexmt_backoff[6], 0, "");
436 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
437     &t4_toe_rexmt_backoff[7], 0, "");
438 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
439     &t4_toe_rexmt_backoff[8], 0, "");
440 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
441     &t4_toe_rexmt_backoff[9], 0, "");
442 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
443     &t4_toe_rexmt_backoff[10], 0, "");
444 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
445     &t4_toe_rexmt_backoff[11], 0, "");
446 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
447     &t4_toe_rexmt_backoff[12], 0, "");
448 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
449     &t4_toe_rexmt_backoff[13], 0, "");
450 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
451     &t4_toe_rexmt_backoff[14], 0, "");
452 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
453     &t4_toe_rexmt_backoff[15], 0, "");
454 
455 int t4_ddp_rcvbuf_len = 256 * 1024;
456 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
457     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
458 
459 unsigned int t4_ddp_rcvbuf_cache = 4;
460 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
461     &t4_ddp_rcvbuf_cache, 0,
462     "maximum number of free DDP RX buffers to cache per connection");
463 #endif
464 
465 #ifdef DEV_NETMAP
466 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
467 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
468 static int t4_native_netmap = NN_EXTRA_VI;
469 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
470     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
471 
472 #define NNMTXQ 8
473 static int t4_nnmtxq = -NNMTXQ;
474 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
475     "Number of netmap TX queues");
476 
477 #define NNMRXQ 8
478 static int t4_nnmrxq = -NNMRXQ;
479 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
480     "Number of netmap RX queues");
481 
482 #define NNMTXQ_VI 2
483 static int t4_nnmtxq_vi = -NNMTXQ_VI;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
485     "Number of netmap TX queues per VI");
486 
487 #define NNMRXQ_VI 2
488 static int t4_nnmrxq_vi = -NNMRXQ_VI;
489 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
490     "Number of netmap RX queues per VI");
491 #endif
492 
493 /*
494  * Holdoff parameters for ports.
495  */
496 #define TMR_IDX 1
497 int t4_tmr_idx = TMR_IDX;
498 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
499     0, "Holdoff timer index");
500 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
501 
502 #define PKTC_IDX (-1)
503 int t4_pktc_idx = PKTC_IDX;
504 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
505     0, "Holdoff packet counter index");
506 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
507 
508 /*
509  * Size (# of entries) of each tx and rx queue.
510  */
511 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
512 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
513     "Number of descriptors in each TX queue");
514 
515 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
516 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
517     "Number of descriptors in each RX queue");
518 
519 /*
520  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
521  */
522 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
523 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
524     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
525 
526 /*
527  * Configuration file.  All the _CF names here are special.
528  */
529 #define DEFAULT_CF	"default"
530 #define BUILTIN_CF	"built-in"
531 #define FLASH_CF	"flash"
532 #define UWIRE_CF	"uwire"
533 #define FPGA_CF		"fpga"
534 static char t4_cfg_file[32] = DEFAULT_CF;
535 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
536     sizeof(t4_cfg_file), "Firmware configuration file");
537 
538 /*
539  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
540  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
541  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
542  *            mark or when signalled to do so, 0 to never emit PAUSE.
543  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
544  *                 negotiated settings will override rx_pause/tx_pause.
545  *                 Otherwise rx_pause/tx_pause are applied forcibly.
546  */
547 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
548 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
549     &t4_pause_settings, 0,
550     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
551 
552 /*
553  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
554  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
555  *  0 to disable FEC.
556  */
557 static int t4_fec = -1;
558 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
559     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
560 
561 static const char *
562 t4_fec_bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2\6auto\7module";
563 
564 /*
565  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
566  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
567  * driver runs as if this is set to 0.
568  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
569  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
570  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
571  *    the firmware anyway (may result in l1cfg errors with old firmwares).
572  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
573  *    means set all FEC bits that are valid for the speed.
574  */
575 static int t4_force_fec = -1;
576 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
577     "Controls the use of FORCE_FEC bit in L1 configuration.");
578 
579 /*
580  * Link autonegotiation.
581  * -1 to run with the firmware default.
582  *  0 to disable.
583  *  1 to enable.
584  */
585 static int t4_autoneg = -1;
586 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
587     "Link autonegotiation");
588 
589 /*
590  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
591  * encouraged respectively).  '-n' is the same as 'n' except the firmware
592  * version used in the checks is read from the firmware bundled with the driver.
593  */
594 static int t4_fw_install = 1;
595 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
596     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
597 
598 /*
599  * ASIC features that will be used.  Disable the ones you don't want so that the
600  * chip resources aren't wasted on features that will not be used.
601  */
602 static int t4_nbmcaps_allowed = 0;
603 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
604     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
605 
606 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
607 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
608     &t4_linkcaps_allowed, 0, "Default link capabilities");
609 
610 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
611     FW_CAPS_CONFIG_SWITCH_EGRESS;
612 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
613     &t4_switchcaps_allowed, 0, "Default switch capabilities");
614 
615 static int t4_nvmecaps_allowed = -1;
616 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nvmecaps_allowed, CTLFLAG_RDTUN,
617     &t4_nvmecaps_allowed, 0, "Default NVMe capabilities");
618 
619 #ifdef RATELIMIT
620 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
621 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
622 #else
623 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
624 	FW_CAPS_CONFIG_NIC_HASHFILTER;
625 #endif
626 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
627     &t4_niccaps_allowed, 0, "Default NIC capabilities");
628 
629 static int t4_toecaps_allowed = -1;
630 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
631     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
632 
633 static int t4_rdmacaps_allowed = -1;
634 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
635     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
636 
637 static int t4_cryptocaps_allowed = -1;
638 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
639     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
640 
641 static int t4_iscsicaps_allowed = -1;
642 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
643     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
644 
645 static int t4_fcoecaps_allowed = 0;
646 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
647     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
648 
649 static int t5_write_combine = 0;
650 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
651     0, "Use WC instead of UC for BAR2");
652 
653 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
654 static int t4_doorbells_allowed = 0xf;
655 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
656 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
657 
658 static int t4_num_vis = 1;
659 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
660     "Number of VIs per port");
661 
662 /*
663  * PCIe Relaxed Ordering.
664  * -1: driver should figure out a good value.
665  * 0: disable RO.
666  * 1: enable RO.
667  * 2: leave RO alone.
668  */
669 static int pcie_relaxed_ordering = -1;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
671     &pcie_relaxed_ordering, 0,
672     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
673 
674 static int t4_panic_on_fatal_err = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
676     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
677 
678 static int t4_reset_on_fatal_err = 0;
679 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
680     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
681 
682 static int t4_reset_method = 1;
683 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_method, CTLFLAG_RWTUN, &t4_reset_method,
684     0, "reset method: 0 = PL_RST, 1 = PCIe secondary bus reset, 2 = PCIe link bounce");
685 
686 static int t4_clock_gate_on_suspend = 0;
687 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
688     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
689 
690 static int t4_tx_vm_wr = 0;
691 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
692     "Use VM work requests to transmit packets.");
693 
694 /*
695  * Set to non-zero to enable the attack filter.  A packet that matches any of
696  * these conditions will get dropped on ingress:
697  * 1) IP && source address == destination address.
698  * 2) TCP/IP && source address is not a unicast address.
699  * 3) TCP/IP && destination address is not a unicast address.
700  * 4) IP && source address is loopback (127.x.y.z).
701  * 5) IP && destination address is loopback (127.x.y.z).
702  * 6) IPv6 && source address == destination address.
703  * 7) IPv6 && source address is not a unicast address.
704  * 8) IPv6 && source address is loopback (::1/128).
705  * 9) IPv6 && destination address is loopback (::1/128).
706  * 10) IPv6 && source address is unspecified (::/128).
707  * 11) IPv6 && destination address is unspecified (::/128).
708  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
709  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
710  */
711 static int t4_attack_filter = 0;
712 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
713     &t4_attack_filter, 0, "Drop suspicious traffic");
714 
715 static int t4_drop_ip_fragments = 0;
716 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
717     &t4_drop_ip_fragments, 0, "Drop IP fragments");
718 
719 static int t4_drop_pkts_with_l2_errors = 1;
720 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
721     &t4_drop_pkts_with_l2_errors, 0,
722     "Drop all frames with Layer 2 length or checksum errors");
723 
724 static int t4_drop_pkts_with_l3_errors = 0;
725 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
726     &t4_drop_pkts_with_l3_errors, 0,
727     "Drop all frames with IP version, length, or checksum errors");
728 
729 static int t4_drop_pkts_with_l4_errors = 0;
730 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
731     &t4_drop_pkts_with_l4_errors, 0,
732     "Drop all frames with Layer 4 length, checksum, or other errors");
733 
734 #ifdef TCP_OFFLOAD
735 /*
736  * TOE tunables.
737  */
738 static int t4_cop_managed_offloading = 0;
739 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
740     &t4_cop_managed_offloading, 0,
741     "COP (Connection Offload Policy) controls all TOE offload");
742 TUNABLE_INT("hw.cxgbe.cop_managed_offloading", &t4_cop_managed_offloading);
743 #endif
744 
745 #ifdef KERN_TLS
746 /*
747  * This enables KERN_TLS for all adapters if set.
748  */
749 static int t4_kern_tls = 0;
750 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
751     "Enable KERN_TLS mode for T6+ adapters");
752 
753 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
754     "cxgbe(4) KERN_TLS parameters");
755 
756 static int t4_tls_cbc = 0;
757 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, cbc, CTLFLAG_RDTUN,
758     &t4_tls_cbc, 0,
759     "Enable offload of AES-CBC cipher suites.");
760 
761 static int t4_tls_inline_keys = 0;
762 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
763     &t4_tls_inline_keys, 0,
764     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
765     "in card memory.");
766 
767 static int t4_tls_combo_wrs = 0;
768 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
769     0, "Attempt to combine TCB field updates with TLS record work requests.");
770 
771 static int t4_tls_short_records = 1;
772 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, short_records, CTLFLAG_RDTUN,
773     &t4_tls_short_records, 0, "Use cipher-only mode for short records.");
774 
775 static int t4_tls_partial_ghash = 1;
776 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, partial_ghash, CTLFLAG_RDTUN,
777     &t4_tls_partial_ghash, 0, "Use partial GHASH for AES-GCM records.");
778 #endif
779 
780 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
781 static int vi_mac_funcs[] = {
782 	FW_VI_FUNC_ETH,
783 	FW_VI_FUNC_OFLD,
784 	FW_VI_FUNC_IWARP,
785 	FW_VI_FUNC_OPENISCSI,
786 	FW_VI_FUNC_OPENFCOE,
787 	FW_VI_FUNC_FOISCSI,
788 	FW_VI_FUNC_FOFCOE,
789 };
790 
791 struct intrs_and_queues {
792 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
793 	uint16_t num_vis;	/* number of VIs for each port */
794 	uint16_t nirq;		/* Total # of vectors */
795 	uint16_t ntxq;		/* # of NIC txq's for each port */
796 	uint16_t nrxq;		/* # of NIC rxq's for each port */
797 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
798 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
799 	uint16_t nnmtxq;	/* # of netmap txq's */
800 	uint16_t nnmrxq;	/* # of netmap rxq's */
801 
802 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
803 	uint16_t ntxq_vi;	/* # of NIC txq's */
804 	uint16_t nrxq_vi;	/* # of NIC rxq's */
805 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
806 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
807 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
808 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
809 };
810 
811 static void setup_memwin(struct adapter *);
812 static void position_memwin(struct adapter *, int, uint32_t);
813 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
814 static int fwmtype_to_hwmtype(int);
815 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
816     uint32_t *);
817 static int fixup_devlog_ncores_params(struct adapter *);
818 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
819 static int contact_firmware(struct adapter *);
820 static int partition_resources(struct adapter *);
821 static int get_params__pre_init(struct adapter *);
822 static int set_params__pre_init(struct adapter *);
823 static int get_params__post_init(struct adapter *);
824 static int set_params__post_init(struct adapter *);
825 static void t4_set_desc(struct adapter *);
826 static bool fixed_ifmedia(struct port_info *);
827 static void build_medialist(struct port_info *);
828 static void init_link_config(struct port_info *);
829 static int fixup_link_config(struct port_info *);
830 static int apply_link_config(struct port_info *);
831 static int cxgbe_init_synchronized(struct vi_info *);
832 static int cxgbe_uninit_synchronized(struct vi_info *);
833 static int adapter_full_init(struct adapter *);
834 static void adapter_full_uninit(struct adapter *);
835 static int vi_full_init(struct vi_info *);
836 static void vi_full_uninit(struct vi_info *);
837 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
838 static void quiesce_txq(struct sge_txq *);
839 static void quiesce_wrq(struct sge_wrq *);
840 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
841 static void quiesce_vi(struct vi_info *);
842 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
843     driver_intr_t *, void *, char *);
844 static int t4_free_irq(struct adapter *, struct irq *);
845 static void t4_init_atid_table(struct adapter *);
846 static void t4_free_atid_table(struct adapter *);
847 static void stop_atid_allocator(struct adapter *);
848 static void restart_atid_allocator(struct adapter *);
849 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
850 static void vi_refresh_stats(struct vi_info *);
851 static void cxgbe_refresh_stats(struct vi_info *);
852 static void cxgbe_tick(void *);
853 static void vi_tick(void *);
854 static void cxgbe_sysctls(struct port_info *);
855 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
856 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
857 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
858 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
859 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
860 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
861 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
862 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
863 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
864 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
865 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
866 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
867 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
868 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
869 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
870 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
871 static int sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS);
872 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
873 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
874 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
875 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
876 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
877 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
878 static int sysctl_cim_ibq(SYSCTL_HANDLER_ARGS);
879 static int sysctl_cim_obq(SYSCTL_HANDLER_ARGS);
880 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
881 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
882 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
883 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
884 static int sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS);
885 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
886 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
887 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
888 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
889 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
890 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
891 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
892 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
893 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
894 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
895 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
896 static int sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS);
897 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
898 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
899 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
900 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
901 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
902 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
903 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
904 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
905 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
906 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
907 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
908 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
909 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
910 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
911 static int sysctl_tcb_cache(SYSCTL_HANDLER_ARGS);
912 #ifdef TCP_OFFLOAD
913 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
914 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
915 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
916 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
917 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
918 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
919 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
920 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
921 #endif
922 static int get_sge_context(struct adapter *, int, uint32_t, int, uint32_t *);
923 static int load_fw(struct adapter *, struct t4_data *);
924 static int load_cfg(struct adapter *, struct t4_data *);
925 static int load_boot(struct adapter *, struct t4_bootrom *);
926 static int load_bootcfg(struct adapter *, struct t4_data *);
927 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
928 static void free_offload_policy(struct t4_offload_policy *);
929 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
930 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
931 static int read_i2c(struct adapter *, struct t4_i2c_data *);
932 static int clear_stats(struct adapter *, u_int);
933 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
934 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
935 static inline int stop_adapter(struct adapter *);
936 static inline void set_adapter_hwstatus(struct adapter *, const bool);
937 static int stop_lld(struct adapter *);
938 static inline int restart_adapter(struct adapter *);
939 static int restart_lld(struct adapter *);
940 #ifdef TCP_OFFLOAD
941 static int deactivate_all_uld(struct adapter *);
942 static void stop_all_uld(struct adapter *);
943 static void restart_all_uld(struct adapter *);
944 #endif
945 #ifdef KERN_TLS
946 static int ktls_capability(struct adapter *, bool);
947 #endif
948 static int mod_event(module_t, int, void *);
949 static int notify_siblings(device_t, int);
950 static uint64_t vi_get_counter(if_t, ift_counter);
951 static uint64_t cxgbe_get_counter(if_t, ift_counter);
952 static void enable_vxlan_rx(struct adapter *);
953 static void reset_adapter_task(void *, int);
954 static void fatal_error_task(void *, int);
955 static void dump_devlog(struct adapter *);
956 static void dump_cim_regs(struct adapter *);
957 static void dump_cimla(struct adapter *);
958 
959 struct {
960 	uint16_t device;
961 	char *desc;
962 } t4_pciids[] = {
963 	{0xa000, "Chelsio Terminator 4 FPGA"},
964 	{0x4400, "Chelsio T440-dbg"},
965 	{0x4401, "Chelsio T420-CR"},
966 	{0x4402, "Chelsio T422-CR"},
967 	{0x4403, "Chelsio T440-CR"},
968 	{0x4404, "Chelsio T420-BCH"},
969 	{0x4405, "Chelsio T440-BCH"},
970 	{0x4406, "Chelsio T440-CH"},
971 	{0x4407, "Chelsio T420-SO"},
972 	{0x4408, "Chelsio T420-CX"},
973 	{0x4409, "Chelsio T420-BT"},
974 	{0x440a, "Chelsio T404-BT"},
975 	{0x440e, "Chelsio T440-LP-CR"},
976 }, t5_pciids[] = {
977 	{0xb000, "Chelsio Terminator 5 FPGA"},
978 	{0x5400, "Chelsio T580-dbg"},
979 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
980 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
981 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
982 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
983 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
984 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
985 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
986 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
987 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
988 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
989 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
990 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
991 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
992 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
993 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
994 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
995 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
996 
997 	/* Custom */
998 	{0x5483, "Custom T540-CR"},
999 	{0x5484, "Custom T540-BT"},
1000 }, t6_pciids[] = {
1001 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
1002 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
1003 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
1004 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
1005 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
1006 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
1007 	{0x6405, "Chelsio T6225-SO-OCP3"},	/* 2 x 10/25G, nomem */
1008 	{0x6406, "Chelsio T6225-OCP3"},		/* 2 x 10/25G */
1009 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
1010 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
1011 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
1012 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
1013 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
1014 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
1015 	{0x6414, "Chelsio T62100-SO-OCP3"},	/* 2 x 40/50/100G, nomem */
1016 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
1017 
1018 	/* Custom */
1019 	{0x6480, "Custom T6225-CR"},
1020 	{0x6481, "Custom T62100-CR"},
1021 	{0x6482, "Custom T6225-CR"},
1022 	{0x6483, "Custom T62100-CR"},
1023 	{0x6484, "Custom T64100-CR"},
1024 	{0x6485, "Custom T6240-SO"},
1025 	{0x6486, "Custom T6225-SO-CR"},
1026 	{0x6487, "Custom T6225-CR"},
1027 }, t7_pciids[] = {
1028 	{0xd000, "Chelsio Terminator 7 FPGA"},	/* T7 PE12K FPGA */
1029 	{0x7400, "Chelsio T72200-DBG"},		/* 2 x 200G, debug */
1030 	{0x7401, "Chelsio T7250"},		/* 2 x 10/25/50G, 1 mem */
1031 	{0x7402, "Chelsio S7250"},		/* 2 x 10/25/50G, nomem */
1032 	{0x7403, "Chelsio T7450"},		/* 4 x 10/25/50G, 1 mem */
1033 	{0x7404, "Chelsio S7450"},		/* 4 x 10/25/50G, nomem */
1034 	{0x7405, "Chelsio T72200"},		/* 2 x 40/100/200G, 1 mem */
1035 	{0x7406, "Chelsio S72200"},		/* 2 x 40/100/200G, nomem */
1036 	{0x7407, "Chelsio T72200-FH"},		/* 2 x 40/100/200G, 2 mem */
1037 	{0x7408, "Chelsio S71400"},		/* 1 x 400G, nomem */
1038 	{0x7409, "Chelsio S7210-BT"},		/* 2 x 10GBASE-T, nomem */
1039 	{0x740a, "Chelsio T7450-RC"},		/* 4 x 10/25/50G, 1 mem, RC */
1040 	{0x740b, "Chelsio T72200-RC"},		/* 2 x 40/100/200G, 1 mem, RC */
1041 	{0x740c, "Chelsio T72200-FH-RC"},	/* 2 x 40/100/200G, 2 mem, RC */
1042 	{0x740d, "Chelsio S72200-OCP3"},	/* 2 x 40/100/200G OCP3 */
1043 	{0x740e, "Chelsio S7450-OCP3"},		/* 4 x 1/20/25/50G OCP3 */
1044 	{0x740f, "Chelsio S7410-BT-OCP3"},	/* 4 x 10GBASE-T OCP3 */
1045 	{0x7410, "Chelsio S7210-BT-A"},		/* 2 x 10GBASE-T */
1046 	{0x7411, "Chelsio T7_MAYRA_7"},		/* Motherboard */
1047 
1048 	/* Custom */
1049 	{0x7480, "Custom T7"},
1050 };
1051 
1052 #ifdef TCP_OFFLOAD
1053 /*
1054  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
1055  * be exactly the same for both rxq and ofld_rxq.
1056  */
1057 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
1058 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
1059 #endif
1060 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
1061 
1062 static int
1063 t4_probe(device_t dev)
1064 {
1065 	int i;
1066 	uint16_t v = pci_get_vendor(dev);
1067 	uint16_t d = pci_get_device(dev);
1068 	uint8_t f = pci_get_function(dev);
1069 
1070 	if (v != PCI_VENDOR_ID_CHELSIO)
1071 		return (ENXIO);
1072 
1073 	/* Attach only to PF0 of the FPGA */
1074 	if (d == 0xa000 && f != 0)
1075 		return (ENXIO);
1076 
1077 	for (i = 0; i < nitems(t4_pciids); i++) {
1078 		if (d == t4_pciids[i].device) {
1079 			device_set_desc(dev, t4_pciids[i].desc);
1080 			return (BUS_PROBE_DEFAULT);
1081 		}
1082 	}
1083 
1084 	return (ENXIO);
1085 }
1086 
1087 static int
1088 t5_probe(device_t dev)
1089 {
1090 	int i;
1091 	uint16_t v = pci_get_vendor(dev);
1092 	uint16_t d = pci_get_device(dev);
1093 	uint8_t f = pci_get_function(dev);
1094 
1095 	if (v != PCI_VENDOR_ID_CHELSIO)
1096 		return (ENXIO);
1097 
1098 	/* Attach only to PF0 of the FPGA */
1099 	if (d == 0xb000 && f != 0)
1100 		return (ENXIO);
1101 
1102 	for (i = 0; i < nitems(t5_pciids); i++) {
1103 		if (d == t5_pciids[i].device) {
1104 			device_set_desc(dev, t5_pciids[i].desc);
1105 			return (BUS_PROBE_DEFAULT);
1106 		}
1107 	}
1108 
1109 	return (ENXIO);
1110 }
1111 
1112 static int
1113 t6_probe(device_t dev)
1114 {
1115 	int i;
1116 	uint16_t v = pci_get_vendor(dev);
1117 	uint16_t d = pci_get_device(dev);
1118 
1119 	if (v != PCI_VENDOR_ID_CHELSIO)
1120 		return (ENXIO);
1121 
1122 	for (i = 0; i < nitems(t6_pciids); i++) {
1123 		if (d == t6_pciids[i].device) {
1124 			device_set_desc(dev, t6_pciids[i].desc);
1125 			return (BUS_PROBE_DEFAULT);
1126 		}
1127 	}
1128 
1129 	return (ENXIO);
1130 }
1131 
1132 static int
1133 ch_probe(device_t dev)
1134 {
1135 	int i;
1136 	uint16_t v = pci_get_vendor(dev);
1137 	uint16_t d = pci_get_device(dev);
1138 	uint8_t f = pci_get_function(dev);
1139 
1140 	if (v != PCI_VENDOR_ID_CHELSIO)
1141 		return (ENXIO);
1142 
1143 	/* Attach only to PF0 of the FPGA */
1144 	if (d == 0xd000 && f != 0)
1145 		return (ENXIO);
1146 
1147 	for (i = 0; i < nitems(t7_pciids); i++) {
1148 		if (d == t7_pciids[i].device) {
1149 			device_set_desc(dev, t7_pciids[i].desc);
1150 			return (BUS_PROBE_DEFAULT);
1151 		}
1152 	}
1153 
1154 	return (ENXIO);
1155 }
1156 
1157 static void
1158 t5_attribute_workaround(device_t dev)
1159 {
1160 	device_t root_port;
1161 	uint32_t v;
1162 
1163 	/*
1164 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1165 	 * Ordering attributes when replying to a TLP from a Root
1166 	 * Port.  As a workaround, find the parent Root Port and
1167 	 * disable No Snoop and Relaxed Ordering.  Note that this
1168 	 * affects all devices under this root port.
1169 	 */
1170 	root_port = pci_find_pcie_root_port(dev);
1171 	if (root_port == NULL) {
1172 		device_printf(dev, "Unable to find parent root port\n");
1173 		return;
1174 	}
1175 
1176 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1177 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1178 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1179 	    0)
1180 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1181 		    device_get_nameunit(root_port));
1182 }
1183 
1184 static const struct devnames devnames[] = {
1185 	{
1186 		.nexus_name = "t4nex",
1187 		.ifnet_name = "cxgbe",
1188 		.vi_ifnet_name = "vcxgbe",
1189 		.pf03_drv_name = "t4iov",
1190 		.vf_nexus_name = "t4vf",
1191 		.vf_ifnet_name = "cxgbev"
1192 	}, {
1193 		.nexus_name = "t5nex",
1194 		.ifnet_name = "cxl",
1195 		.vi_ifnet_name = "vcxl",
1196 		.pf03_drv_name = "t5iov",
1197 		.vf_nexus_name = "t5vf",
1198 		.vf_ifnet_name = "cxlv"
1199 	}, {
1200 		.nexus_name = "t6nex",
1201 		.ifnet_name = "cc",
1202 		.vi_ifnet_name = "vcc",
1203 		.pf03_drv_name = "t6iov",
1204 		.vf_nexus_name = "t6vf",
1205 		.vf_ifnet_name = "ccv"
1206 	}, {
1207 		.nexus_name = "chnex",
1208 		.ifnet_name = "che",
1209 		.vi_ifnet_name = "vche",
1210 		.pf03_drv_name = "chiov",
1211 		.vf_nexus_name = "chvf",
1212 		.vf_ifnet_name = "chev"
1213 	}
1214 };
1215 
1216 void
1217 t4_init_devnames(struct adapter *sc)
1218 {
1219 	int id;
1220 
1221 	id = chip_id(sc);
1222 	if (id < CHELSIO_T4) {
1223 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1224 		sc->names = NULL;
1225 	} else if (id - CHELSIO_T4 < nitems(devnames))
1226 		sc->names = &devnames[id - CHELSIO_T4];
1227 	else
1228 		sc->names = &devnames[nitems(devnames) - 1];
1229 }
1230 
1231 static int
1232 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1233 {
1234 	const char *parent, *name;
1235 	long value;
1236 	int line, unit;
1237 
1238 	line = 0;
1239 	parent = device_get_nameunit(sc->dev);
1240 	name = sc->names->ifnet_name;
1241 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1242 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1243 		    value == pi->port_id)
1244 			return (unit);
1245 	}
1246 	return (-1);
1247 }
1248 
1249 static void
1250 t4_calibration(void *arg)
1251 {
1252 	struct adapter *sc;
1253 	struct clock_sync *cur, *nex;
1254 	uint64_t hw;
1255 	sbintime_t sbt;
1256 	int next_up;
1257 
1258 	sc = (struct adapter *)arg;
1259 
1260 	KASSERT(!hw_off_limits(sc), ("hw_off_limits at t4_calibration"));
1261 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1262 	sbt = sbinuptime();
1263 
1264 	cur = &sc->cal_info[sc->cal_current];
1265 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1266 	nex = &sc->cal_info[next_up];
1267 	if (__predict_false(sc->cal_count == 0)) {
1268 		/* First time in, just get the values in */
1269 		cur->hw_cur = hw;
1270 		cur->sbt_cur = sbt;
1271 		sc->cal_count++;
1272 		goto done;
1273 	}
1274 
1275 	if (cur->hw_cur == hw) {
1276 		/* The clock is not advancing? */
1277 		sc->cal_count = 0;
1278 		atomic_store_rel_int(&cur->gen, 0);
1279 		goto done;
1280 	}
1281 
1282 	seqc_write_begin(&nex->gen);
1283 	nex->hw_prev = cur->hw_cur;
1284 	nex->sbt_prev = cur->sbt_cur;
1285 	nex->hw_cur = hw;
1286 	nex->sbt_cur = sbt;
1287 	seqc_write_end(&nex->gen);
1288 	sc->cal_current = next_up;
1289 done:
1290 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1291 	    sc, C_DIRECT_EXEC);
1292 }
1293 
1294 static void
1295 t4_calibration_start(struct adapter *sc)
1296 {
1297 	/*
1298 	 * Here if we have not done a calibration
1299 	 * then do so otherwise start the appropriate
1300 	 * timer.
1301 	 */
1302 	int i;
1303 
1304 	for (i = 0; i < CNT_CAL_INFO; i++) {
1305 		sc->cal_info[i].gen = 0;
1306 	}
1307 	sc->cal_current = 0;
1308 	sc->cal_count = 0;
1309 	sc->cal_gen = 0;
1310 	t4_calibration(sc);
1311 }
1312 
1313 static int
1314 t4_attach(device_t dev)
1315 {
1316 	struct adapter *sc;
1317 	int rc = 0, i, j, rqidx, tqidx, nports;
1318 	struct make_dev_args mda;
1319 	struct intrs_and_queues iaq;
1320 	struct sge *s;
1321 	uint32_t *buf;
1322 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1323 	int ofld_tqidx;
1324 #endif
1325 #ifdef TCP_OFFLOAD
1326 	int ofld_rqidx;
1327 #endif
1328 #ifdef DEV_NETMAP
1329 	int nm_rqidx, nm_tqidx;
1330 #endif
1331 	int num_vis;
1332 
1333 	sc = device_get_softc(dev);
1334 	sc->dev = dev;
1335 	sysctl_ctx_init(&sc->ctx);
1336 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1337 	if (TUNABLE_INT_FETCH("hw.cxgbe.iflags", &sc->intr_flags) == 0)
1338 		sc->intr_flags = IHF_INTR_CLEAR_ON_INIT | IHF_CLR_ALL_UNIGNORED;
1339 
1340 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1341 		t5_attribute_workaround(dev);
1342 	pci_enable_busmaster(dev);
1343 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1344 		uint32_t v;
1345 
1346 		pci_set_max_read_req(dev, 4096);
1347 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1348 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1349 		if (pcie_relaxed_ordering == 0 &&
1350 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1351 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1352 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1353 		} else if (pcie_relaxed_ordering == 1 &&
1354 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1355 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1356 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1357 		}
1358 	}
1359 
1360 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1361 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1362 	sc->traceq = -1;
1363 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1364 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1365 	    device_get_nameunit(dev));
1366 
1367 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1368 	    device_get_nameunit(dev));
1369 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1370 	t4_add_adapter(sc);
1371 
1372 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1373 	TAILQ_INIT(&sc->sfl);
1374 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1375 
1376 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1377 
1378 	sc->policy = NULL;
1379 	rw_init(&sc->policy_lock, "connection offload policy");
1380 
1381 	callout_init(&sc->ktls_tick, 1);
1382 
1383 	callout_init(&sc->cal_callout, 1);
1384 
1385 	refcount_init(&sc->vxlan_refcount, 0);
1386 
1387 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1388 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1389 
1390 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1391 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1392 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1393 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1394 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1395 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1396 
1397 	rc = t4_map_bars_0_and_4(sc);
1398 	if (rc != 0)
1399 		goto done; /* error message displayed already */
1400 
1401 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1402 	memset(sc->port_map, 0xff, sizeof(sc->port_map));
1403 
1404 	/* Prepare the adapter for operation. */
1405 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1406 	rc = -t4_prep_adapter(sc, buf);
1407 	free(buf, M_CXGBE);
1408 	if (rc != 0) {
1409 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1410 		goto done;
1411 	}
1412 
1413 	/*
1414 	 * This is the real PF# to which we're attaching.  Works from within PCI
1415 	 * passthrough environments too, where pci_get_function() could return a
1416 	 * different PF# depending on the passthrough configuration.  We need to
1417 	 * use the real PF# in all our communication with the firmware.
1418 	 */
1419 	j = t4_read_reg(sc, A_PL_WHOAMI);
1420 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1421 	sc->mbox = sc->pf;
1422 
1423 	t4_init_devnames(sc);
1424 	if (sc->names == NULL) {
1425 		rc = ENOTSUP;
1426 		goto done; /* error message displayed already */
1427 	}
1428 
1429 	/*
1430 	 * Do this really early, with the memory windows set up even before the
1431 	 * character device.  The userland tool's register i/o and mem read
1432 	 * will work even in "recovery mode".
1433 	 */
1434 	setup_memwin(sc);
1435 	if (t4_init_devlog_ncores_params(sc, 0) == 0)
1436 		fixup_devlog_ncores_params(sc);
1437 	make_dev_args_init(&mda);
1438 	mda.mda_devsw = &t4_cdevsw;
1439 	mda.mda_uid = UID_ROOT;
1440 	mda.mda_gid = GID_WHEEL;
1441 	mda.mda_mode = 0600;
1442 	mda.mda_si_drv1 = sc;
1443 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1444 	if (rc != 0)
1445 		device_printf(dev, "failed to create nexus char device: %d.\n",
1446 		    rc);
1447 
1448 	/* Go no further if recovery mode has been requested. */
1449 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1450 		device_printf(dev, "recovery mode.\n");
1451 		goto done;
1452 	}
1453 
1454 #if defined(__i386__)
1455 	if ((cpu_feature & CPUID_CX8) == 0) {
1456 		device_printf(dev, "64 bit atomics not available.\n");
1457 		rc = ENOTSUP;
1458 		goto done;
1459 	}
1460 #endif
1461 
1462 	/* Contact the firmware and try to become the master driver. */
1463 	rc = contact_firmware(sc);
1464 	if (rc != 0)
1465 		goto done; /* error message displayed already */
1466 	MPASS(sc->flags & FW_OK);
1467 
1468 	rc = get_params__pre_init(sc);
1469 	if (rc != 0)
1470 		goto done; /* error message displayed already */
1471 
1472 	if (sc->flags & MASTER_PF) {
1473 		rc = partition_resources(sc);
1474 		if (rc != 0)
1475 			goto done; /* error message displayed already */
1476 	}
1477 
1478 	rc = get_params__post_init(sc);
1479 	if (rc != 0)
1480 		goto done; /* error message displayed already */
1481 
1482 	rc = set_params__post_init(sc);
1483 	if (rc != 0)
1484 		goto done; /* error message displayed already */
1485 
1486 	rc = t4_map_bar_2(sc);
1487 	if (rc != 0)
1488 		goto done; /* error message displayed already */
1489 
1490 	rc = t4_adj_doorbells(sc);
1491 	if (rc != 0)
1492 		goto done; /* error message displayed already */
1493 
1494 	rc = t4_create_dma_tag(sc);
1495 	if (rc != 0)
1496 		goto done; /* error message displayed already */
1497 
1498 	/*
1499 	 * First pass over all the ports - allocate VIs and initialize some
1500 	 * basic parameters like mac address, port type, etc.
1501 	 */
1502 	for_each_port(sc, i) {
1503 		struct port_info *pi;
1504 
1505 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1506 		sc->port[i] = pi;
1507 
1508 		/* These must be set before t4_port_init */
1509 		pi->adapter = sc;
1510 		pi->port_id = i;
1511 		/*
1512 		 * XXX: vi[0] is special so we can't delay this allocation until
1513 		 * pi->nvi's final value is known.
1514 		 */
1515 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1516 		    M_ZERO | M_WAITOK);
1517 
1518 		/*
1519 		 * Allocate the "main" VI and initialize parameters
1520 		 * like mac addr.
1521 		 */
1522 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1523 		if (rc != 0) {
1524 			device_printf(dev, "unable to initialize port %d: %d\n",
1525 			    i, rc);
1526 			free(pi->vi, M_CXGBE);
1527 			free(pi, M_CXGBE);
1528 			sc->port[i] = NULL;
1529 			goto done;
1530 		}
1531 
1532 		if (is_bt(pi->port_type))
1533 			setbit(&sc->bt_map, pi->hw_port);
1534 		else
1535 			MPASS(!isset(&sc->bt_map, pi->hw_port));
1536 
1537 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1538 		    device_get_nameunit(dev), i);
1539 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1540 		for (j = 0; j < sc->params.tp.lb_nchan; j++)
1541 			sc->chan_map[pi->tx_chan + j] = i;
1542 		sc->port_map[pi->hw_port] = i;
1543 
1544 		/*
1545 		 * The MPS counter for FCS errors doesn't work correctly on the
1546 		 * T6 so we use the MAC counter here.  Which MAC is in use
1547 		 * depends on the link settings which will be known when the
1548 		 * link comes up.
1549 		 */
1550 		if (is_t6(sc))
1551 			pi->fcs_reg = -1;
1552 		else
1553 			pi->fcs_reg = A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L;
1554 		pi->fcs_base = 0;
1555 
1556 		/* All VIs on this port share this media. */
1557 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1558 		    cxgbe_media_status);
1559 
1560 		PORT_LOCK(pi);
1561 		init_link_config(pi);
1562 		fixup_link_config(pi);
1563 		build_medialist(pi);
1564 		if (fixed_ifmedia(pi))
1565 			pi->flags |= FIXED_IFMEDIA;
1566 		PORT_UNLOCK(pi);
1567 
1568 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1569 		    t4_ifnet_unit(sc, pi));
1570 		if (pi->dev == NULL) {
1571 			device_printf(dev,
1572 			    "failed to add device for port %d.\n", i);
1573 			rc = ENXIO;
1574 			goto done;
1575 		}
1576 		pi->vi[0].dev = pi->dev;
1577 		device_set_softc(pi->dev, pi);
1578 	}
1579 
1580 	/*
1581 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1582 	 */
1583 	nports = sc->params.nports;
1584 	rc = cfg_itype_and_nqueues(sc, &iaq);
1585 	if (rc != 0)
1586 		goto done; /* error message displayed already */
1587 
1588 	num_vis = iaq.num_vis;
1589 	sc->intr_type = iaq.intr_type;
1590 	sc->intr_count = iaq.nirq;
1591 
1592 	s = &sc->sge;
1593 	s->nctrlq = max(sc->params.nports, sc->params.ncores);
1594 	s->nrxq = nports * iaq.nrxq;
1595 	s->ntxq = nports * iaq.ntxq;
1596 	if (num_vis > 1) {
1597 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1598 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1599 	}
1600 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1601 	s->neq += nports;		/* ctrl queues: 1 per port */
1602 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1603 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1604 	if (is_offload(sc) || is_ethoffload(sc)) {
1605 		s->nofldtxq = nports * iaq.nofldtxq;
1606 		if (num_vis > 1)
1607 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1608 		s->neq += s->nofldtxq;
1609 
1610 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1611 		    M_CXGBE, M_ZERO | M_WAITOK);
1612 	}
1613 #endif
1614 #ifdef TCP_OFFLOAD
1615 	if (is_offload(sc)) {
1616 		s->nofldrxq = nports * iaq.nofldrxq;
1617 		if (num_vis > 1)
1618 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1619 		s->neq += s->nofldrxq;	/* free list */
1620 		s->niq += s->nofldrxq;
1621 
1622 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1623 		    M_CXGBE, M_ZERO | M_WAITOK);
1624 	}
1625 #endif
1626 #ifdef DEV_NETMAP
1627 	s->nnmrxq = 0;
1628 	s->nnmtxq = 0;
1629 	if (t4_native_netmap & NN_MAIN_VI) {
1630 		s->nnmrxq += nports * iaq.nnmrxq;
1631 		s->nnmtxq += nports * iaq.nnmtxq;
1632 	}
1633 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1634 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1635 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1636 	}
1637 	s->neq += s->nnmtxq + s->nnmrxq;
1638 	s->niq += s->nnmrxq;
1639 
1640 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1641 	    M_CXGBE, M_ZERO | M_WAITOK);
1642 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1643 	    M_CXGBE, M_ZERO | M_WAITOK);
1644 #endif
1645 	MPASS(s->niq <= s->iqmap_sz);
1646 	MPASS(s->neq <= s->eqmap_sz);
1647 
1648 	s->ctrlq = malloc(s->nctrlq * sizeof(struct sge_wrq), M_CXGBE,
1649 	    M_ZERO | M_WAITOK);
1650 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1651 	    M_ZERO | M_WAITOK);
1652 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1653 	    M_ZERO | M_WAITOK);
1654 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1655 	    M_ZERO | M_WAITOK);
1656 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1657 	    M_ZERO | M_WAITOK);
1658 
1659 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1660 	    M_ZERO | M_WAITOK);
1661 
1662 	t4_init_l2t(sc, M_WAITOK);
1663 	t4_init_smt(sc, M_WAITOK);
1664 	t4_init_tx_sched(sc);
1665 	t4_init_atid_table(sc);
1666 #ifdef RATELIMIT
1667 	t4_init_etid_table(sc);
1668 #endif
1669 #ifdef INET6
1670 	t4_init_clip_table(sc);
1671 #endif
1672 	if (sc->vres.key.size != 0)
1673 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1674 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1675 	t4_init_tpt(sc);
1676 
1677 	/*
1678 	 * Second pass over the ports.  This time we know the number of rx and
1679 	 * tx queues that each port should get.
1680 	 */
1681 	rqidx = tqidx = 0;
1682 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1683 	ofld_tqidx = 0;
1684 #endif
1685 #ifdef TCP_OFFLOAD
1686 	ofld_rqidx = 0;
1687 #endif
1688 #ifdef DEV_NETMAP
1689 	nm_rqidx = nm_tqidx = 0;
1690 #endif
1691 	for_each_port(sc, i) {
1692 		struct port_info *pi = sc->port[i];
1693 		struct vi_info *vi;
1694 
1695 		if (pi == NULL)
1696 			continue;
1697 
1698 		pi->nvi = num_vis;
1699 		for_each_vi(pi, j, vi) {
1700 			vi->pi = pi;
1701 			vi->adapter = sc;
1702 			vi->first_intr = -1;
1703 			vi->qsize_rxq = t4_qsize_rxq;
1704 			vi->qsize_txq = t4_qsize_txq;
1705 
1706 			vi->first_rxq = rqidx;
1707 			vi->first_txq = tqidx;
1708 			vi->tmr_idx = t4_tmr_idx;
1709 			vi->pktc_idx = t4_pktc_idx;
1710 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1711 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1712 
1713 			rqidx += vi->nrxq;
1714 			tqidx += vi->ntxq;
1715 
1716 			if (j == 0 && vi->ntxq > 1)
1717 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1718 			else
1719 				vi->rsrv_noflowq = 0;
1720 
1721 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1722 			vi->first_ofld_txq = ofld_tqidx;
1723 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1724 			ofld_tqidx += vi->nofldtxq;
1725 #endif
1726 #ifdef TCP_OFFLOAD
1727 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1728 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1729 			vi->first_ofld_rxq = ofld_rqidx;
1730 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1731 
1732 			ofld_rqidx += vi->nofldrxq;
1733 #endif
1734 #ifdef DEV_NETMAP
1735 			vi->first_nm_rxq = nm_rqidx;
1736 			vi->first_nm_txq = nm_tqidx;
1737 			if (j == 0) {
1738 				vi->nnmrxq = iaq.nnmrxq;
1739 				vi->nnmtxq = iaq.nnmtxq;
1740 			} else {
1741 				vi->nnmrxq = iaq.nnmrxq_vi;
1742 				vi->nnmtxq = iaq.nnmtxq_vi;
1743 			}
1744 			nm_rqidx += vi->nnmrxq;
1745 			nm_tqidx += vi->nnmtxq;
1746 #endif
1747 		}
1748 	}
1749 
1750 	rc = t4_setup_intr_handlers(sc);
1751 	if (rc != 0) {
1752 		device_printf(dev,
1753 		    "failed to setup interrupt handlers: %d\n", rc);
1754 		goto done;
1755 	}
1756 
1757 	bus_identify_children(dev);
1758 
1759 	/*
1760 	 * Ensure thread-safe mailbox access (in debug builds).
1761 	 *
1762 	 * So far this was the only thread accessing the mailbox but various
1763 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1764 	 * will access the mailbox from different threads.
1765 	 */
1766 	sc->flags |= CHK_MBOX_ACCESS;
1767 
1768 	bus_attach_children(dev);
1769 	t4_calibration_start(sc);
1770 
1771 	device_printf(dev,
1772 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1773 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1774 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1775 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1776 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1777 
1778 	t4_set_desc(sc);
1779 
1780 	notify_siblings(dev, 0);
1781 
1782 done:
1783 	if (rc != 0 && sc->cdev) {
1784 		/* cdev was created and so cxgbetool works; recover that way. */
1785 		device_printf(dev,
1786 		    "error during attach, adapter is now in recovery mode.\n");
1787 		rc = 0;
1788 	}
1789 
1790 	if (rc != 0)
1791 		t4_detach_common(dev);
1792 	else
1793 		t4_sysctls(sc);
1794 
1795 	return (rc);
1796 }
1797 
1798 static int
1799 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1800 {
1801 	struct adapter *sc;
1802 	struct port_info *pi;
1803 	int i;
1804 
1805 	sc = device_get_softc(bus);
1806 	for_each_port(sc, i) {
1807 		pi = sc->port[i];
1808 		if (pi != NULL && pi->dev == dev) {
1809 			sbuf_printf(sb, "port=%d", pi->port_id);
1810 			break;
1811 		}
1812 	}
1813 	return (0);
1814 }
1815 
1816 static int
1817 t4_ready(device_t dev)
1818 {
1819 	struct adapter *sc;
1820 
1821 	sc = device_get_softc(dev);
1822 	if (sc->flags & FW_OK)
1823 		return (0);
1824 	return (ENXIO);
1825 }
1826 
1827 static int
1828 t4_read_port_device(device_t dev, int port, device_t *child)
1829 {
1830 	struct adapter *sc;
1831 	struct port_info *pi;
1832 
1833 	sc = device_get_softc(dev);
1834 	if (port < 0 || port >= MAX_NPORTS)
1835 		return (EINVAL);
1836 	pi = sc->port[port];
1837 	if (pi == NULL || pi->dev == NULL)
1838 		return (ENXIO);
1839 	*child = pi->dev;
1840 	return (0);
1841 }
1842 
1843 static int
1844 notify_siblings(device_t dev, int detaching)
1845 {
1846 	device_t sibling;
1847 	int error, i;
1848 
1849 	error = 0;
1850 	for (i = 0; i < PCI_FUNCMAX; i++) {
1851 		if (i == pci_get_function(dev))
1852 			continue;
1853 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1854 		    pci_get_slot(dev), i);
1855 		if (sibling == NULL || !device_is_attached(sibling))
1856 			continue;
1857 		if (detaching)
1858 			error = T4_DETACH_CHILD(sibling);
1859 		else
1860 			(void)T4_ATTACH_CHILD(sibling);
1861 		if (error)
1862 			break;
1863 	}
1864 	return (error);
1865 }
1866 
1867 /*
1868  * Idempotent
1869  */
1870 static int
1871 t4_detach(device_t dev)
1872 {
1873 	int rc;
1874 
1875 	rc = notify_siblings(dev, 1);
1876 	if (rc) {
1877 		device_printf(dev,
1878 		    "failed to detach sibling devices: %d\n", rc);
1879 		return (rc);
1880 	}
1881 
1882 	return (t4_detach_common(dev));
1883 }
1884 
1885 int
1886 t4_detach_common(device_t dev)
1887 {
1888 	struct adapter *sc;
1889 	struct port_info *pi;
1890 	int i, rc;
1891 
1892 	sc = device_get_softc(dev);
1893 
1894 #ifdef TCP_OFFLOAD
1895 	rc = deactivate_all_uld(sc);
1896 	if (rc) {
1897 		device_printf(dev,
1898 		    "failed to detach upper layer drivers: %d\n", rc);
1899 		return (rc);
1900 	}
1901 #endif
1902 
1903 	if (sc->cdev) {
1904 		destroy_dev(sc->cdev);
1905 		sc->cdev = NULL;
1906 	}
1907 
1908 	sx_xlock(&t4_list_lock);
1909 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1910 	sx_xunlock(&t4_list_lock);
1911 
1912 	sc->flags &= ~CHK_MBOX_ACCESS;
1913 	if (sc->flags & FULL_INIT_DONE) {
1914 		if (!(sc->flags & IS_VF))
1915 			t4_intr_disable(sc);
1916 	}
1917 
1918 	if (device_is_attached(dev)) {
1919 		rc = bus_detach_children(dev);
1920 		if (rc) {
1921 			device_printf(dev,
1922 			    "failed to detach child devices: %d\n", rc);
1923 			return (rc);
1924 		}
1925 	}
1926 
1927 	for (i = 0; i < sc->intr_count; i++)
1928 		t4_free_irq(sc, &sc->irq[i]);
1929 
1930 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1931 		t4_free_tx_sched(sc);
1932 
1933 	for (i = 0; i < MAX_NPORTS; i++) {
1934 		pi = sc->port[i];
1935 		if (pi) {
1936 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1937 
1938 			mtx_destroy(&pi->pi_lock);
1939 			free(pi->vi, M_CXGBE);
1940 			free(pi, M_CXGBE);
1941 		}
1942 	}
1943 	callout_stop(&sc->cal_callout);
1944 	callout_drain(&sc->cal_callout);
1945 	device_delete_children(dev);
1946 	sysctl_ctx_free(&sc->ctx);
1947 	adapter_full_uninit(sc);
1948 
1949 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1950 		t4_fw_bye(sc, sc->mbox);
1951 
1952 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1953 		pci_release_msi(dev);
1954 
1955 	if (sc->regs_res)
1956 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1957 		    sc->regs_res);
1958 
1959 	if (sc->udbs_res)
1960 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1961 		    sc->udbs_res);
1962 
1963 	if (sc->msix_res)
1964 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1965 		    sc->msix_res);
1966 
1967 	if (sc->l2t)
1968 		t4_free_l2t(sc);
1969 	if (sc->smt)
1970 		t4_free_smt(sc->smt);
1971 	t4_free_atid_table(sc);
1972 #ifdef RATELIMIT
1973 	t4_free_etid_table(sc);
1974 #endif
1975 	if (sc->key_map)
1976 		vmem_destroy(sc->key_map);
1977 	t4_free_tpt(sc);
1978 #ifdef INET6
1979 	t4_destroy_clip_table(sc);
1980 #endif
1981 
1982 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1983 	free(sc->sge.ofld_txq, M_CXGBE);
1984 #endif
1985 #ifdef TCP_OFFLOAD
1986 	free(sc->sge.ofld_rxq, M_CXGBE);
1987 #endif
1988 #ifdef DEV_NETMAP
1989 	free(sc->sge.nm_rxq, M_CXGBE);
1990 	free(sc->sge.nm_txq, M_CXGBE);
1991 #endif
1992 	free(sc->irq, M_CXGBE);
1993 	free(sc->sge.rxq, M_CXGBE);
1994 	free(sc->sge.txq, M_CXGBE);
1995 	free(sc->sge.ctrlq, M_CXGBE);
1996 	free(sc->sge.iqmap, M_CXGBE);
1997 	free(sc->sge.eqmap, M_CXGBE);
1998 	free(sc->tids.ftid_tab, M_CXGBE);
1999 	free(sc->tids.hpftid_tab, M_CXGBE);
2000 	free_hftid_hash(&sc->tids);
2001 	free(sc->tids.tid_tab, M_CXGBE);
2002 	t4_destroy_dma_tag(sc);
2003 
2004 	callout_drain(&sc->ktls_tick);
2005 	callout_drain(&sc->sfl_callout);
2006 	if (mtx_initialized(&sc->tids.ftid_lock)) {
2007 		mtx_destroy(&sc->tids.ftid_lock);
2008 		cv_destroy(&sc->tids.ftid_cv);
2009 	}
2010 	if (mtx_initialized(&sc->tids.atid_lock))
2011 		mtx_destroy(&sc->tids.atid_lock);
2012 	if (mtx_initialized(&sc->ifp_lock))
2013 		mtx_destroy(&sc->ifp_lock);
2014 
2015 	if (rw_initialized(&sc->policy_lock)) {
2016 		rw_destroy(&sc->policy_lock);
2017 #ifdef TCP_OFFLOAD
2018 		if (sc->policy != NULL)
2019 			free_offload_policy(sc->policy);
2020 #endif
2021 	}
2022 
2023 	for (i = 0; i < NUM_MEMWIN; i++) {
2024 		struct memwin *mw = &sc->memwin[i];
2025 
2026 		if (rw_initialized(&mw->mw_lock))
2027 			rw_destroy(&mw->mw_lock);
2028 	}
2029 
2030 	mtx_destroy(&sc->sfl_lock);
2031 	mtx_destroy(&sc->reg_lock);
2032 	mtx_destroy(&sc->sc_lock);
2033 
2034 	bzero(sc, sizeof(*sc));
2035 
2036 	return (0);
2037 }
2038 
2039 static inline int
2040 stop_adapter(struct adapter *sc)
2041 {
2042 	struct port_info *pi;
2043 	int i;
2044 
2045 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2046 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2047 			 __func__, curthread, sc->flags, sc->error_flags);
2048 		return (EALREADY);
2049 	}
2050 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2051 		 sc->flags, sc->error_flags);
2052 	t4_shutdown_adapter(sc);
2053 	for_each_port(sc, i) {
2054 		pi = sc->port[i];
2055 		if (pi == NULL)
2056 			continue;
2057 		PORT_LOCK(pi);
2058 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
2059 			/*
2060 			 * t4_shutdown_adapter has already shut down all the
2061 			 * PHYs but it also disables interrupts and DMA so there
2062 			 * won't be a link interrupt.  Update the state manually
2063 			 * if the link was up previously and inform the kernel.
2064 			 */
2065 			pi->link_cfg.link_ok = false;
2066 			t4_os_link_changed(pi);
2067 		}
2068 		PORT_UNLOCK(pi);
2069 	}
2070 
2071 	return (0);
2072 }
2073 
2074 static inline int
2075 restart_adapter(struct adapter *sc)
2076 {
2077 	uint32_t val;
2078 
2079 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2080 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2081 			 __func__, curthread, sc->flags, sc->error_flags);
2082 		return (EALREADY);
2083 	}
2084 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2085 		 sc->flags, sc->error_flags);
2086 
2087 	MPASS(hw_off_limits(sc));
2088 	MPASS((sc->flags & FW_OK) == 0);
2089 	MPASS((sc->flags & MASTER_PF) == 0);
2090 	MPASS(sc->reset_thread == NULL);
2091 
2092 	/*
2093 	 * The adapter is supposed to be back on PCIE with its config space and
2094 	 * BARs restored to their state before reset.  Register access via
2095 	 * t4_read_reg BAR0 should just work.
2096 	 */
2097 	sc->reset_thread = curthread;
2098 	val = t4_read_reg(sc, A_PL_WHOAMI);
2099 	if (val == 0xffffffff || val == 0xeeeeeeee) {
2100 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
2101 		sc->reset_thread = NULL;
2102 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
2103 		return (ENXIO);
2104 	}
2105 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
2106 	atomic_add_int(&sc->incarnation, 1);
2107 	atomic_add_int(&sc->num_resets, 1);
2108 
2109 	return (0);
2110 }
2111 
2112 static inline void
2113 set_adapter_hwstatus(struct adapter *sc, const bool usable)
2114 {
2115 	if (usable) {
2116 		/* Must be marked reusable by the designated thread. */
2117 		ASSERT_SYNCHRONIZED_OP(sc);
2118 		MPASS(sc->reset_thread == curthread);
2119 		mtx_lock(&sc->reg_lock);
2120 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2121 		mtx_unlock(&sc->reg_lock);
2122 	} else {
2123 		/* Mark the adapter totally off limits. */
2124 		begin_synchronized_op(sc, NULL, SLEEP_OK, "t4hwsts");
2125 		mtx_lock(&sc->reg_lock);
2126 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2127 		mtx_unlock(&sc->reg_lock);
2128 		sc->flags &= ~(FW_OK | MASTER_PF);
2129 		sc->reset_thread = NULL;
2130 		end_synchronized_op(sc, 0);
2131 	}
2132 }
2133 
2134 static int
2135 stop_lld(struct adapter *sc)
2136 {
2137 	struct port_info *pi;
2138 	struct vi_info *vi;
2139 	if_t ifp;
2140 	struct sge_rxq *rxq;
2141 	struct sge_txq *txq;
2142 	struct sge_wrq *wrq;
2143 #ifdef TCP_OFFLOAD
2144 	struct sge_ofld_rxq *ofld_rxq;
2145 #endif
2146 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2147 	struct sge_ofld_txq *ofld_txq;
2148 #endif
2149 	int rc, i, j, k;
2150 
2151 	/*
2152 	 * XXX: Can there be a synch_op in progress that will hang because
2153 	 * hardware has been stopped?  We'll hang too and the solution will be
2154 	 * to use a version of begin_synch_op that wakes up existing synch_op
2155 	 * with errors.  Maybe stop_adapter should do this wakeup?
2156 	 *
2157 	 * I don't think any synch_op could get stranded waiting for DMA or
2158 	 * interrupt so I think we're okay here.  Remove this comment block
2159 	 * after testing.
2160 	 */
2161 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2162 	if (rc != 0)
2163 		return (ENXIO);
2164 
2165 	/* Quiesce all activity. */
2166 	for_each_port(sc, i) {
2167 		pi = sc->port[i];
2168 		if (pi == NULL)
2169 			continue;
2170 		pi->vxlan_tcam_entry = false;
2171 		for_each_vi(pi, j, vi) {
2172 			vi->xact_addr_filt = -1;
2173 			mtx_lock(&vi->tick_mtx);
2174 			vi->flags |= VI_SKIP_STATS;
2175 			mtx_unlock(&vi->tick_mtx);
2176 			if (!(vi->flags & VI_INIT_DONE))
2177 				continue;
2178 
2179 			ifp = vi->ifp;
2180 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2181 				mtx_lock(&vi->tick_mtx);
2182 				callout_stop(&vi->tick);
2183 				mtx_unlock(&vi->tick_mtx);
2184 				callout_drain(&vi->tick);
2185 			}
2186 
2187 			/*
2188 			 * Note that the HW is not available.
2189 			 */
2190 			for_each_txq(vi, k, txq) {
2191 				TXQ_LOCK(txq);
2192 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2193 				TXQ_UNLOCK(txq);
2194 			}
2195 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2196 			for_each_ofld_txq(vi, k, ofld_txq) {
2197 				TXQ_LOCK(&ofld_txq->wrq);
2198 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2199 				TXQ_UNLOCK(&ofld_txq->wrq);
2200 			}
2201 #endif
2202 			for_each_rxq(vi, k, rxq) {
2203 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2204 			}
2205 #if defined(TCP_OFFLOAD)
2206 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2207 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2208 			}
2209 #endif
2210 
2211 			quiesce_vi(vi);
2212 		}
2213 
2214 		if (sc->flags & FULL_INIT_DONE) {
2215 			/* Control queue */
2216 			wrq = &sc->sge.ctrlq[i];
2217 			TXQ_LOCK(wrq);
2218 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2219 			TXQ_UNLOCK(wrq);
2220 			quiesce_wrq(wrq);
2221 		}
2222 
2223 		if (pi->flags & HAS_TRACEQ) {
2224 			pi->flags &= ~HAS_TRACEQ;
2225 			sc->traceq = -1;
2226 			sc->tracer_valid = 0;
2227 			sc->tracer_enabled = 0;
2228 		}
2229 	}
2230 	if (sc->flags & FULL_INIT_DONE) {
2231 		/* Firmware event queue */
2232 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2233 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2234 	}
2235 
2236 	/* Stop calibration */
2237 	callout_stop(&sc->cal_callout);
2238 	callout_drain(&sc->cal_callout);
2239 
2240 	if (t4_clock_gate_on_suspend) {
2241 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2242 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2243 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2244 	}
2245 
2246 	end_synchronized_op(sc, 0);
2247 
2248 	stop_atid_allocator(sc);
2249 	t4_stop_l2t(sc);
2250 
2251 	return (rc);
2252 }
2253 
2254 int
2255 suspend_adapter(struct adapter *sc)
2256 {
2257 	stop_adapter(sc);
2258 	stop_lld(sc);
2259 #ifdef TCP_OFFLOAD
2260 	stop_all_uld(sc);
2261 #endif
2262 	set_adapter_hwstatus(sc, false);
2263 
2264 	return (0);
2265 }
2266 
2267 static int
2268 t4_suspend(device_t dev)
2269 {
2270 	struct adapter *sc = device_get_softc(dev);
2271 	int rc;
2272 
2273 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2274 	rc = suspend_adapter(sc);
2275 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2276 
2277 	return (rc);
2278 }
2279 
2280 struct adapter_pre_reset_state {
2281 	u_int flags;
2282 	uint16_t nbmcaps;
2283 	uint16_t linkcaps;
2284 	uint16_t switchcaps;
2285 	uint16_t nvmecaps;
2286 	uint16_t niccaps;
2287 	uint16_t toecaps;
2288 	uint16_t rdmacaps;
2289 	uint16_t cryptocaps;
2290 	uint16_t iscsicaps;
2291 	uint16_t fcoecaps;
2292 
2293 	u_int cfcsum;
2294 	char cfg_file[32];
2295 
2296 	struct adapter_params params;
2297 	struct t4_virt_res vres;
2298 	struct tid_info tids;
2299 	struct sge sge;
2300 
2301 	int rawf_base;
2302 	int nrawf;
2303 
2304 };
2305 
2306 static void
2307 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2308 {
2309 
2310 	ASSERT_SYNCHRONIZED_OP(sc);
2311 
2312 	o->flags = sc->flags;
2313 
2314 	o->nbmcaps =  sc->nbmcaps;
2315 	o->linkcaps = sc->linkcaps;
2316 	o->switchcaps = sc->switchcaps;
2317 	o->nvmecaps = sc->nvmecaps;
2318 	o->niccaps = sc->niccaps;
2319 	o->toecaps = sc->toecaps;
2320 	o->rdmacaps = sc->rdmacaps;
2321 	o->cryptocaps = sc->cryptocaps;
2322 	o->iscsicaps = sc->iscsicaps;
2323 	o->fcoecaps = sc->fcoecaps;
2324 
2325 	o->cfcsum = sc->cfcsum;
2326 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2327 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2328 
2329 	o->params = sc->params;
2330 	o->vres = sc->vres;
2331 	o->tids = sc->tids;
2332 	o->sge = sc->sge;
2333 
2334 	o->rawf_base = sc->rawf_base;
2335 	o->nrawf = sc->nrawf;
2336 }
2337 
2338 static int
2339 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2340 {
2341 	int rc = 0;
2342 
2343 	ASSERT_SYNCHRONIZED_OP(sc);
2344 
2345 	/* Capabilities */
2346 #define COMPARE_CAPS(c) do { \
2347 	if (o->c##caps != sc->c##caps) { \
2348 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2349 		    sc->c##caps); \
2350 		rc = EINVAL; \
2351 	} \
2352 } while (0)
2353 	COMPARE_CAPS(nbm);
2354 	COMPARE_CAPS(link);
2355 	COMPARE_CAPS(switch);
2356 	COMPARE_CAPS(nvme);
2357 	COMPARE_CAPS(nic);
2358 	COMPARE_CAPS(toe);
2359 	COMPARE_CAPS(rdma);
2360 	COMPARE_CAPS(crypto);
2361 	COMPARE_CAPS(iscsi);
2362 	COMPARE_CAPS(fcoe);
2363 #undef COMPARE_CAPS
2364 
2365 	/* Firmware config file */
2366 	if (o->cfcsum != sc->cfcsum) {
2367 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2368 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2369 		rc = EINVAL;
2370 	}
2371 
2372 #define COMPARE_PARAM(p, name) do { \
2373 	if (o->p != sc->p) { \
2374 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2375 		rc = EINVAL; \
2376 	} \
2377 } while (0)
2378 	COMPARE_PARAM(sge.iq_start, iq_start);
2379 	COMPARE_PARAM(sge.eq_start, eq_start);
2380 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2381 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2382 	COMPARE_PARAM(tids.nftids, nftids);
2383 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2384 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2385 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2386 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2387 	COMPARE_PARAM(tids.tid_base, tid_base);
2388 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2389 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2390 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2391 	COMPARE_PARAM(rawf_base, rawf_base);
2392 	COMPARE_PARAM(nrawf, nrawf);
2393 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2394 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2395 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2396 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2397 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2398 	COMPARE_PARAM(tids.ntids, ntids);
2399 	COMPARE_PARAM(tids.etid_base, etid_base);
2400 	COMPARE_PARAM(tids.etid_end, etid_end);
2401 	COMPARE_PARAM(tids.netids, netids);
2402 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2403 	COMPARE_PARAM(params.ethoffload, ethoffload);
2404 	COMPARE_PARAM(tids.natids, natids);
2405 	COMPARE_PARAM(tids.stid_base, stid_base);
2406 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2407 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2408 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2409 	COMPARE_PARAM(vres.stag.start, stag_start);
2410 	COMPARE_PARAM(vres.stag.size, stag_size);
2411 	COMPARE_PARAM(vres.rq.start, rq_start);
2412 	COMPARE_PARAM(vres.rq.size, rq_size);
2413 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2414 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2415 	COMPARE_PARAM(vres.qp.start, qp_start);
2416 	COMPARE_PARAM(vres.qp.size, qp_size);
2417 	COMPARE_PARAM(vres.cq.start, cq_start);
2418 	COMPARE_PARAM(vres.cq.size, cq_size);
2419 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2420 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2421 	COMPARE_PARAM(vres.srq.start, srq_start);
2422 	COMPARE_PARAM(vres.srq.size, srq_size);
2423 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2424 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2425 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2426 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2427 	COMPARE_PARAM(vres.key.start, key_start);
2428 	COMPARE_PARAM(vres.key.size, key_size);
2429 #undef COMPARE_PARAM
2430 
2431 	return (rc);
2432 }
2433 
2434 static int
2435 restart_lld(struct adapter *sc)
2436 {
2437 	struct adapter_pre_reset_state *old_state = NULL;
2438 	struct port_info *pi;
2439 	struct vi_info *vi;
2440 	if_t ifp;
2441 	struct sge_txq *txq;
2442 	int rc, i, j, k;
2443 
2444 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2445 	if (rc != 0)
2446 		return (ENXIO);
2447 
2448 	/* Restore memory window. */
2449 	setup_memwin(sc);
2450 
2451 	/* Go no further if recovery mode has been requested. */
2452 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2453 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2454 		rc = 0;
2455 		set_adapter_hwstatus(sc, true);
2456 		goto done;
2457 	}
2458 
2459 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2460 	save_caps_and_params(sc, old_state);
2461 
2462 	/* Reestablish contact with firmware and become the primary PF. */
2463 	rc = contact_firmware(sc);
2464 	if (rc != 0)
2465 		goto done; /* error message displayed already */
2466 	MPASS(sc->flags & FW_OK);
2467 
2468 	if (sc->flags & MASTER_PF) {
2469 		rc = partition_resources(sc);
2470 		if (rc != 0)
2471 			goto done; /* error message displayed already */
2472 	}
2473 
2474 	rc = get_params__post_init(sc);
2475 	if (rc != 0)
2476 		goto done; /* error message displayed already */
2477 
2478 	rc = set_params__post_init(sc);
2479 	if (rc != 0)
2480 		goto done; /* error message displayed already */
2481 
2482 	rc = compare_caps_and_params(sc, old_state);
2483 	if (rc != 0)
2484 		goto done; /* error message displayed already */
2485 
2486 	for_each_port(sc, i) {
2487 		pi = sc->port[i];
2488 		MPASS(pi != NULL);
2489 		MPASS(pi->vi != NULL);
2490 		MPASS(pi->vi[0].dev == pi->dev);
2491 
2492 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2493 		if (rc != 0) {
2494 			CH_ERR(sc,
2495 			    "failed to re-initialize port %d: %d\n", i, rc);
2496 			goto done;
2497 		}
2498 		MPASS(sc->chan_map[pi->tx_chan] == i);
2499 
2500 		PORT_LOCK(pi);
2501 		fixup_link_config(pi);
2502 		build_medialist(pi);
2503 		PORT_UNLOCK(pi);
2504 		for_each_vi(pi, j, vi) {
2505 			if (IS_MAIN_VI(vi))
2506 				continue;
2507 			rc = alloc_extra_vi(sc, pi, vi);
2508 			if (rc != 0) {
2509 				CH_ERR(vi,
2510 				    "failed to re-allocate extra VI: %d\n", rc);
2511 				goto done;
2512 			}
2513 		}
2514 	}
2515 
2516 	/*
2517 	 * Interrupts and queues are about to be enabled and other threads will
2518 	 * want to access the hardware too.  It is safe to do so.  Note that
2519 	 * this thread is still in the middle of a synchronized_op.
2520 	 */
2521 	set_adapter_hwstatus(sc, true);
2522 
2523 	if (sc->flags & FULL_INIT_DONE) {
2524 		rc = adapter_full_init(sc);
2525 		if (rc != 0) {
2526 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2527 			goto done;
2528 		}
2529 
2530 		if (sc->vxlan_refcount > 0)
2531 			enable_vxlan_rx(sc);
2532 
2533 		for_each_port(sc, i) {
2534 			pi = sc->port[i];
2535 			for_each_vi(pi, j, vi) {
2536 				mtx_lock(&vi->tick_mtx);
2537 				vi->flags &= ~VI_SKIP_STATS;
2538 				mtx_unlock(&vi->tick_mtx);
2539 				if (!(vi->flags & VI_INIT_DONE))
2540 					continue;
2541 				rc = vi_full_init(vi);
2542 				if (rc != 0) {
2543 					CH_ERR(vi, "failed to re-initialize "
2544 					    "interface: %d\n", rc);
2545 					goto done;
2546 				}
2547 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2548 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2549 					t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
2550 					pi->flags |= HAS_TRACEQ;
2551 				}
2552 
2553 				ifp = vi->ifp;
2554 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2555 					continue;
2556 				/*
2557 				 * Note that we do not setup multicast addresses
2558 				 * in the first pass.  This ensures that the
2559 				 * unicast DMACs for all VIs on all ports get an
2560 				 * MPS TCAM entry.
2561 				 */
2562 				rc = update_mac_settings(ifp, XGMAC_ALL &
2563 				    ~XGMAC_MCADDRS);
2564 				if (rc != 0) {
2565 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2566 					goto done;
2567 				}
2568 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2569 				    true);
2570 				if (rc != 0) {
2571 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2572 					goto done;
2573 				}
2574 				for_each_txq(vi, k, txq) {
2575 					TXQ_LOCK(txq);
2576 					txq->eq.flags |= EQ_ENABLED;
2577 					TXQ_UNLOCK(txq);
2578 				}
2579 				mtx_lock(&vi->tick_mtx);
2580 				callout_schedule(&vi->tick, hz);
2581 				mtx_unlock(&vi->tick_mtx);
2582 			}
2583 			PORT_LOCK(pi);
2584 			if (pi->up_vis > 0) {
2585 				t4_update_port_info(pi);
2586 				fixup_link_config(pi);
2587 				build_medialist(pi);
2588 				apply_link_config(pi);
2589 				if (pi->link_cfg.link_ok)
2590 					t4_os_link_changed(pi);
2591 			}
2592 			PORT_UNLOCK(pi);
2593 		}
2594 
2595 		/* Now reprogram the L2 multicast addresses. */
2596 		for_each_port(sc, i) {
2597 			pi = sc->port[i];
2598 			for_each_vi(pi, j, vi) {
2599 				if (!(vi->flags & VI_INIT_DONE))
2600 					continue;
2601 				ifp = vi->ifp;
2602 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2603 					continue;
2604 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2605 				if (rc != 0) {
2606 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2607 					rc = 0;	/* carry on */
2608 				}
2609 			}
2610 		}
2611 	}
2612 
2613 	/* Reset all calibration */
2614 	t4_calibration_start(sc);
2615 done:
2616 	end_synchronized_op(sc, 0);
2617 	free(old_state, M_CXGBE);
2618 
2619 	restart_atid_allocator(sc);
2620 	t4_restart_l2t(sc);
2621 
2622 	return (rc);
2623 }
2624 
2625 int
2626 resume_adapter(struct adapter *sc)
2627 {
2628 	restart_adapter(sc);
2629 	restart_lld(sc);
2630 #ifdef TCP_OFFLOAD
2631 	restart_all_uld(sc);
2632 #endif
2633 	return (0);
2634 }
2635 
2636 static int
2637 t4_resume(device_t dev)
2638 {
2639 	struct adapter *sc = device_get_softc(dev);
2640 	int rc;
2641 
2642 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2643 	rc = resume_adapter(sc);
2644 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2645 
2646 	return (rc);
2647 }
2648 
2649 static int
2650 t4_reset_prepare(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 t4_reset_post(device_t dev, device_t child)
2660 {
2661 	struct adapter *sc = device_get_softc(dev);
2662 
2663 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2664 	return (0);
2665 }
2666 
2667 static int
2668 reset_adapter_with_pl_rst(struct adapter *sc)
2669 {
2670 	/* This is a t4_write_reg without the hw_off_limits check. */
2671 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2672 	bus_write_4(sc->regs_res, A_PL_RST,
2673 	    F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2674 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2675 	return (0);
2676 }
2677 
2678 static int
2679 reset_adapter_with_pcie_sbr(struct adapter *sc)
2680 {
2681 	device_t pdev = device_get_parent(sc->dev);
2682 	device_t gpdev = device_get_parent(pdev);
2683 	device_t *children;
2684 	int rc, i, lcap, lsta, nchildren;
2685 	uint32_t v;
2686 
2687 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2688 	if (rc != 0) {
2689 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2690 		    device_get_nameunit(gpdev), rc);
2691 		return (ENOTSUP);
2692 	}
2693 	lcap = v + PCIER_LINK_CAP;
2694 	lsta = v + PCIER_LINK_STA;
2695 
2696 	nchildren = 0;
2697 	device_get_children(pdev, &children, &nchildren);
2698 	for (i = 0; i < nchildren; i++)
2699 		pci_save_state(children[i]);
2700 	v = pci_read_config(gpdev, PCIR_BRIDGECTL_1, 2);
2701 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v | PCIB_BCR_SECBUS_RESET, 2);
2702 	pause("pcie_sbr1", hz / 10);	/* 100ms */
2703 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v, 2);
2704 	pause("pcie_sbr2", hz);		/* Wait 1s before restore_state. */
2705 	v = pci_read_config(gpdev, lsta, 2);
2706 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2707 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2708 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2709 		rc = ETIMEDOUT;
2710 	else
2711 		rc = 0;
2712 	if (rc != 0)
2713 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2714 		    __func__, v);
2715 	else {
2716 		for (i = 0; i < nchildren; i++)
2717 			pci_restore_state(children[i]);
2718 	}
2719 	free(children, M_TEMP);
2720 
2721 	return (rc);
2722 }
2723 
2724 static int
2725 reset_adapter_with_pcie_link_bounce(struct adapter *sc)
2726 {
2727 	device_t pdev = device_get_parent(sc->dev);
2728 	device_t gpdev = device_get_parent(pdev);
2729 	device_t *children;
2730 	int rc, i, lcap, lctl, lsta, nchildren;
2731 	uint32_t v;
2732 
2733 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2734 	if (rc != 0) {
2735 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2736 		    device_get_nameunit(gpdev), rc);
2737 		return (ENOTSUP);
2738 	}
2739 	lcap = v + PCIER_LINK_CAP;
2740 	lctl = v + PCIER_LINK_CTL;
2741 	lsta = v + PCIER_LINK_STA;
2742 
2743 	nchildren = 0;
2744 	device_get_children(pdev, &children, &nchildren);
2745 	for (i = 0; i < nchildren; i++)
2746 		pci_save_state(children[i]);
2747 	v = pci_read_config(gpdev, lctl, 2);
2748 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_LINK_DIS, 2);
2749 	pause("pcie_lnk1", 100 * hz / 1000);	/* 100ms */
2750 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_RETRAIN_LINK, 2);
2751 	pause("pcie_lnk2", hz);		/* Wait 1s before restore_state. */
2752 	v = pci_read_config(gpdev, lsta, 2);
2753 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2754 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2755 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2756 		rc = ETIMEDOUT;
2757 	else
2758 		rc = 0;
2759 	if (rc != 0)
2760 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2761 		    __func__, v);
2762 	else {
2763 		for (i = 0; i < nchildren; i++)
2764 			pci_restore_state(children[i]);
2765 	}
2766 	free(children, M_TEMP);
2767 
2768 	return (rc);
2769 }
2770 
2771 static inline int
2772 reset_adapter(struct adapter *sc)
2773 {
2774 	int rc;
2775 	const int reset_method = vm_guest == VM_GUEST_NO ? t4_reset_method : 0;
2776 
2777 	rc = suspend_adapter(sc);
2778 	if (rc != 0)
2779 		return (rc);
2780 
2781 	switch (reset_method) {
2782 	case 1:
2783 		rc = reset_adapter_with_pcie_sbr(sc);
2784 		break;
2785 	case 2:
2786 		rc = reset_adapter_with_pcie_link_bounce(sc);
2787 		break;
2788 	case 0:
2789 	default:
2790 		rc = reset_adapter_with_pl_rst(sc);
2791 		break;
2792 	}
2793 	if (rc == 0)
2794 		rc = resume_adapter(sc);
2795 	return (rc);
2796 }
2797 
2798 static void
2799 reset_adapter_task(void *arg, int pending)
2800 {
2801 	struct adapter *sc = arg;
2802 	const int flags = sc->flags;
2803 	const int eflags = sc->error_flags;
2804 	int rc;
2805 
2806 	if (pending > 1)
2807 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2808 	rc = reset_adapter(sc);
2809 	if (rc != 0) {
2810 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2811 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2812 		       rc, flags, sc->flags, eflags, sc->error_flags);
2813 	}
2814 }
2815 
2816 static int
2817 cxgbe_probe(device_t dev)
2818 {
2819 	struct port_info *pi = device_get_softc(dev);
2820 
2821 	device_set_descf(dev, "port %d", pi->port_id);
2822 
2823 	return (BUS_PROBE_DEFAULT);
2824 }
2825 
2826 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2827     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2828     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2829     IFCAP_HWRXTSTMP | IFCAP_MEXTPG | IFCAP_NV)
2830 #define T4_CAP_ENABLE (T4_CAP)
2831 
2832 static void
2833 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2834 {
2835 	if_t ifp;
2836 	struct sbuf *sb;
2837 	struct sysctl_ctx_list *ctx = &vi->ctx;
2838 	struct sysctl_oid_list *children;
2839 	struct pfil_head_args pa;
2840 	struct adapter *sc = vi->adapter;
2841 
2842 	sysctl_ctx_init(ctx);
2843 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2844 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2845 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2846 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2847 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2848 #ifdef DEV_NETMAP
2849 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2850 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2851 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2852 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2853 #endif
2854 #ifdef TCP_OFFLOAD
2855 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2856 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2857 #endif
2858 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2859 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2860 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2861 #endif
2862 
2863 	vi->xact_addr_filt = -1;
2864 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2865 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2866 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2867 		vi->flags |= TX_USES_VM_WR;
2868 
2869 	/* Allocate an ifnet and set it up */
2870 	ifp = if_alloc_dev(IFT_ETHER, dev);
2871 	vi->ifp = ifp;
2872 	if_setsoftc(ifp, vi);
2873 
2874 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2875 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2876 
2877 	if_setinitfn(ifp, cxgbe_init);
2878 	if_setioctlfn(ifp, cxgbe_ioctl);
2879 	if_setvfstatusfn(ifp, cxgbe_vf_status);
2880 	if_settransmitfn(ifp, cxgbe_transmit);
2881 	if_setqflushfn(ifp, cxgbe_qflush);
2882 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2883 		if_setgetcounterfn(ifp, vi_get_counter);
2884 	else
2885 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2886 #if defined(KERN_TLS) || defined(RATELIMIT)
2887 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2888 #endif
2889 #ifdef RATELIMIT
2890 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2891 #endif
2892 
2893 	if_setcapabilities(ifp, T4_CAP);
2894 	if_setcapenable(ifp, T4_CAP_ENABLE);
2895 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2896 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2897 	if (chip_id(sc) >= CHELSIO_T6) {
2898 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2899 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2900 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2901 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2902 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2903 	}
2904 
2905 #ifdef TCP_OFFLOAD
2906 	if (vi->nofldrxq != 0)
2907 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2908 #endif
2909 #ifdef RATELIMIT
2910 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2911 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2912 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2913 	}
2914 #endif
2915 
2916 	if_sethwtsomax(ifp, IP_MAXPACKET);
2917 	if (vi->flags & TX_USES_VM_WR)
2918 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2919 	else
2920 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2921 #ifdef RATELIMIT
2922 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2923 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2924 #endif
2925 	if_sethwtsomaxsegsize(ifp, 65536);
2926 #ifdef KERN_TLS
2927 	if (is_ktls(sc)) {
2928 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2929 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2930 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2931 	}
2932 #endif
2933 
2934 	ether_ifattach(ifp, vi->hw_addr);
2935 #ifdef DEV_NETMAP
2936 	if (vi->nnmrxq != 0)
2937 		cxgbe_nm_attach(vi);
2938 #endif
2939 	sb = sbuf_new_auto();
2940 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2941 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2942 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2943 	case IFCAP_TOE:
2944 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2945 		break;
2946 	case IFCAP_TOE | IFCAP_TXRTLMT:
2947 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2948 		break;
2949 	case IFCAP_TXRTLMT:
2950 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2951 		break;
2952 	}
2953 #endif
2954 #ifdef TCP_OFFLOAD
2955 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2956 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2957 #endif
2958 #ifdef DEV_NETMAP
2959 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2960 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2961 		    vi->nnmtxq, vi->nnmrxq);
2962 #endif
2963 	sbuf_finish(sb);
2964 	device_printf(dev, "%s\n", sbuf_data(sb));
2965 	sbuf_delete(sb);
2966 
2967 	vi_sysctls(vi);
2968 
2969 	pa.pa_version = PFIL_VERSION;
2970 	pa.pa_flags = PFIL_IN;
2971 	pa.pa_type = PFIL_TYPE_ETHERNET;
2972 	pa.pa_headname = if_name(ifp);
2973 	vi->pfil = pfil_head_register(&pa);
2974 }
2975 
2976 static int
2977 cxgbe_attach(device_t dev)
2978 {
2979 	struct port_info *pi = device_get_softc(dev);
2980 	struct adapter *sc = pi->adapter;
2981 	struct vi_info *vi;
2982 	int i;
2983 
2984 	sysctl_ctx_init(&pi->ctx);
2985 
2986 	cxgbe_vi_attach(dev, &pi->vi[0]);
2987 
2988 	for_each_vi(pi, i, vi) {
2989 		if (i == 0)
2990 			continue;
2991 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2992 		if (vi->dev == NULL) {
2993 			device_printf(dev, "failed to add VI %d\n", i);
2994 			continue;
2995 		}
2996 		device_set_softc(vi->dev, vi);
2997 	}
2998 
2999 	cxgbe_sysctls(pi);
3000 
3001 	bus_attach_children(dev);
3002 
3003 	return (0);
3004 }
3005 
3006 static void
3007 cxgbe_vi_detach(struct vi_info *vi)
3008 {
3009 	if_t ifp = vi->ifp;
3010 
3011 	if (vi->pfil != NULL) {
3012 		pfil_head_unregister(vi->pfil);
3013 		vi->pfil = NULL;
3014 	}
3015 
3016 	ether_ifdetach(ifp);
3017 
3018 	/* Let detach proceed even if these fail. */
3019 #ifdef DEV_NETMAP
3020 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
3021 		cxgbe_nm_detach(vi);
3022 #endif
3023 	cxgbe_uninit_synchronized(vi);
3024 	callout_drain(&vi->tick);
3025 	mtx_destroy(&vi->tick_mtx);
3026 	sysctl_ctx_free(&vi->ctx);
3027 	vi_full_uninit(vi);
3028 
3029 	if_free(vi->ifp);
3030 	vi->ifp = NULL;
3031 }
3032 
3033 static int
3034 cxgbe_detach(device_t dev)
3035 {
3036 	struct port_info *pi = device_get_softc(dev);
3037 	struct adapter *sc = pi->adapter;
3038 	int rc;
3039 
3040 	/* Detach the extra VIs first. */
3041 	rc = bus_generic_detach(dev);
3042 	if (rc)
3043 		return (rc);
3044 
3045 	sysctl_ctx_free(&pi->ctx);
3046 	begin_vi_detach(sc, &pi->vi[0]);
3047 	if (pi->flags & HAS_TRACEQ) {
3048 		sc->traceq = -1;	/* cloner should not create ifnet */
3049 		t4_tracer_port_detach(sc);
3050 	}
3051 	cxgbe_vi_detach(&pi->vi[0]);
3052 	ifmedia_removeall(&pi->media);
3053 	end_vi_detach(sc, &pi->vi[0]);
3054 
3055 	return (0);
3056 }
3057 
3058 static void
3059 cxgbe_init(void *arg)
3060 {
3061 	struct vi_info *vi = arg;
3062 	struct adapter *sc = vi->adapter;
3063 
3064 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
3065 		return;
3066 	cxgbe_init_synchronized(vi);
3067 	end_synchronized_op(sc, 0);
3068 }
3069 
3070 static int
3071 cxgbe_vf_status(if_t ifp, struct if_vf_status **statusp)
3072 {
3073 	struct port_info *pi;
3074 	struct adapter *sc;
3075 	struct t4_vf_info *snapshot;
3076 	struct if_vf_info *vf;
3077 	struct if_vf_status *status;
3078 	struct vi_info *vi;
3079 	uint16_t num_vfs;
3080 	int error, i;
3081 
3082 	vi = if_getsoftc(ifp);
3083 	pi = vi->pi;
3084 	sc = pi->adapter;
3085 	if (!IS_MAIN_VI(vi))
3086 		return (EOPNOTSUPP);
3087 	error = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK,
3088 	    "t4vfstat");
3089 	if (error != 0)
3090 		return (error);
3091 	if (!pi->iov_status_supported) {
3092 		end_synchronized_op(sc, 0);
3093 		return (EOPNOTSUPP);
3094 	}
3095 	num_vfs = pi->iov_num_vfs;
3096 	snapshot = NULL;
3097 	if (num_vfs != 0) {
3098 		snapshot = mallocarray(num_vfs, sizeof(*snapshot), M_CXGBE,
3099 		    M_WAITOK);
3100 		memcpy(snapshot, pi->iov_vfs, num_vfs * sizeof(*snapshot));
3101 	}
3102 	end_synchronized_op(sc, 0);
3103 
3104 	status = if_vf_status_alloc(num_vfs);
3105 	for (i = 0; i < num_vfs; i++) {
3106 		vf = &status->vfs[i];
3107 		vf->fields = IFVF_F_CONFIGURED;
3108 		vf->index = i;
3109 		vf->configured = snapshot[i].configured;
3110 		if (!vf->configured)
3111 			continue;
3112 		vf->fields |= IFVF_F_VLAN_MODE;
3113 		if (!ETHER_IS_ZERO(snapshot[i].mac)) {
3114 			memcpy(vf->mac, snapshot[i].mac, sizeof(vf->mac));
3115 			vf->fields |= IFVF_F_MAC;
3116 		}
3117 		if (snapshot[i].access_vlan) {
3118 			vf->vlan_mode = IFVF_VLAN_ACCESS;
3119 			vf->vlan = snapshot[i].vlan;
3120 			vf->vlan_proto = ETHERTYPE_VLAN;
3121 			vf->vlan_count = 1;
3122 			vf->fields |= IFVF_F_VLAN | IFVF_F_VLAN_PROTO |
3123 			    IFVF_F_VLAN_COUNT;
3124 		} else
3125 			vf->vlan_mode = IFVF_VLAN_TRUNK;
3126 	}
3127 	free(snapshot, M_CXGBE);
3128 	*statusp = status;
3129 	return (0);
3130 }
3131 
3132 static int
3133 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
3134 {
3135 	int rc = 0, mtu, flags;
3136 	struct vi_info *vi = if_getsoftc(ifp);
3137 	struct port_info *pi = vi->pi;
3138 	struct adapter *sc = pi->adapter;
3139 	struct ifreq *ifr = (struct ifreq *)data;
3140 	uint32_t mask, mask2;
3141 
3142 	switch (cmd) {
3143 	case SIOCSIFMTU:
3144 		mtu = ifr->ifr_mtu;
3145 		if (mtu < ETHERMIN || mtu > MAX_MTU)
3146 			return (EINVAL);
3147 
3148 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
3149 		if (rc)
3150 			return (rc);
3151 		if_setmtu(ifp, mtu);
3152 		if (vi->flags & VI_INIT_DONE) {
3153 			t4_update_fl_bufsize(ifp);
3154 			if (hw_all_ok(sc) &&
3155 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3156 				rc = update_mac_settings(ifp, XGMAC_MTU);
3157 		}
3158 		end_synchronized_op(sc, 0);
3159 		break;
3160 
3161 	case SIOCSIFFLAGS:
3162 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
3163 		if (rc)
3164 			return (rc);
3165 
3166 		if (!hw_all_ok(sc)) {
3167 			rc = ENXIO;
3168 			goto fail;
3169 		}
3170 
3171 		if (if_getflags(ifp) & IFF_UP) {
3172 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3173 				flags = vi->if_flags;
3174 				if ((if_getflags(ifp) ^ flags) &
3175 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3176 					rc = update_mac_settings(ifp,
3177 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
3178 				}
3179 			} else {
3180 				rc = cxgbe_init_synchronized(vi);
3181 			}
3182 			vi->if_flags = if_getflags(ifp);
3183 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3184 			rc = cxgbe_uninit_synchronized(vi);
3185 		}
3186 		end_synchronized_op(sc, 0);
3187 		break;
3188 
3189 	case SIOCADDMULTI:
3190 	case SIOCDELMULTI:
3191 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
3192 		if (rc)
3193 			return (rc);
3194 		if (hw_all_ok(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3195 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
3196 		end_synchronized_op(sc, 0);
3197 		break;
3198 
3199 	case SIOCGIFCAPNV:
3200 		break;
3201 	case SIOCSIFCAPNV:
3202 	case SIOCSIFCAP:
3203 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
3204 		if (rc)
3205 			return (rc);
3206 
3207 		if (cmd == SIOCSIFCAPNV) {
3208 			const struct siocsifcapnv_driver_data *ifr_nv =
3209 			    (struct siocsifcapnv_driver_data *)data;
3210 
3211 			mask = ifr_nv->reqcap ^ if_getcapenable(ifp);
3212 			mask2 = ifr_nv->reqcap2 ^ if_getcapenable2(ifp);
3213 		} else {
3214 			mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3215 			mask2 = 0;
3216 		}
3217 		if (mask & IFCAP_TXCSUM) {
3218 			if_togglecapenable(ifp, IFCAP_TXCSUM);
3219 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
3220 
3221 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
3222 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3223 				mask &= ~IFCAP_TSO4;
3224 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
3225 				if_printf(ifp,
3226 				    "tso4 disabled due to -txcsum.\n");
3227 			}
3228 		}
3229 		if (mask & IFCAP_TXCSUM_IPV6) {
3230 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
3231 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
3232 
3233 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
3234 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3235 				mask &= ~IFCAP_TSO6;
3236 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
3237 				if_printf(ifp,
3238 				    "tso6 disabled due to -txcsum6.\n");
3239 			}
3240 		}
3241 		if (mask & IFCAP_RXCSUM)
3242 			if_togglecapenable(ifp, IFCAP_RXCSUM);
3243 		if (mask & IFCAP_RXCSUM_IPV6)
3244 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
3245 
3246 		/*
3247 		 * Note that we leave CSUM_TSO alone (it is always set).  The
3248 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
3249 		 * sending a TSO request our way, so it's sufficient to toggle
3250 		 * IFCAP_TSOx only.
3251 		 */
3252 		if (mask & IFCAP_TSO4) {
3253 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
3254 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3255 				if_printf(ifp, "enable txcsum first.\n");
3256 				rc = EAGAIN;
3257 				goto fail;
3258 			}
3259 			if_togglecapenable(ifp, IFCAP_TSO4);
3260 		}
3261 		if (mask & IFCAP_TSO6) {
3262 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
3263 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3264 				if_printf(ifp, "enable txcsum6 first.\n");
3265 				rc = EAGAIN;
3266 				goto fail;
3267 			}
3268 			if_togglecapenable(ifp, IFCAP_TSO6);
3269 		}
3270 		if (mask & IFCAP_LRO) {
3271 #if defined(INET) || defined(INET6)
3272 			int i;
3273 			struct sge_rxq *rxq;
3274 
3275 			if_togglecapenable(ifp, IFCAP_LRO);
3276 			for_each_rxq(vi, i, rxq) {
3277 				if (if_getcapenable(ifp) & IFCAP_LRO)
3278 					rxq->iq.flags |= IQ_LRO_ENABLED;
3279 				else
3280 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
3281 			}
3282 #endif
3283 		}
3284 #ifdef TCP_OFFLOAD
3285 		if (mask & IFCAP_TOE) {
3286 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
3287 
3288 			rc = toe_capability(vi, enable);
3289 			if (rc != 0)
3290 				goto fail;
3291 
3292 			if_togglecapenable(ifp, mask);
3293 		}
3294 #endif
3295 		if (mask & IFCAP_VLAN_HWTAGGING) {
3296 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3297 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3298 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3299 		}
3300 		if (mask & IFCAP_VLAN_MTU) {
3301 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3302 
3303 			/* Need to find out how to disable auto-mtu-inflation */
3304 		}
3305 		if (mask & IFCAP_VLAN_HWTSO)
3306 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3307 		if (mask & IFCAP_VLAN_HWCSUM)
3308 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3309 #ifdef RATELIMIT
3310 		if (mask & IFCAP_TXRTLMT)
3311 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3312 #endif
3313 		if (mask & IFCAP_HWRXTSTMP) {
3314 			int i;
3315 			struct sge_rxq *rxq;
3316 
3317 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3318 			for_each_rxq(vi, i, rxq) {
3319 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3320 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3321 				else
3322 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3323 			}
3324 		}
3325 		if (mask & IFCAP_MEXTPG)
3326 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3327 
3328 #ifdef KERN_TLS
3329 		if (mask & IFCAP_TXTLS) {
3330 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3331 
3332 			rc = ktls_capability(sc, enable);
3333 			if (rc != 0)
3334 				goto fail;
3335 
3336 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3337 		}
3338 #endif
3339 		if (mask & IFCAP_VXLAN_HWCSUM) {
3340 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3341 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3342 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3343 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3344 		}
3345 		if (mask & IFCAP_VXLAN_HWTSO) {
3346 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3347 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3348 			    CSUM_INNER_IP_TSO);
3349 		}
3350 
3351 		MPASS(mask2 == 0);
3352 		(void)mask2;
3353 
3354 #ifdef VLAN_CAPABILITIES
3355 		VLAN_CAPABILITIES(ifp);
3356 #endif
3357 fail:
3358 		end_synchronized_op(sc, 0);
3359 		break;
3360 
3361 	case SIOCSIFMEDIA:
3362 	case SIOCGIFMEDIA:
3363 	case SIOCGIFXMEDIA:
3364 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3365 		break;
3366 
3367 	case SIOCGI2C: {
3368 		struct ifi2creq i2c;
3369 
3370 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3371 		if (rc != 0)
3372 			break;
3373 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3374 			rc = EPERM;
3375 			break;
3376 		}
3377 		if (i2c.len > sizeof(i2c.data)) {
3378 			rc = EINVAL;
3379 			break;
3380 		}
3381 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3382 		if (rc)
3383 			return (rc);
3384 		if (!hw_all_ok(sc))
3385 			rc = ENXIO;
3386 		else
3387 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3388 			    i2c.offset, i2c.len, &i2c.data[0]);
3389 		end_synchronized_op(sc, 0);
3390 		if (rc == 0)
3391 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3392 		break;
3393 	}
3394 
3395 	default:
3396 		rc = ether_ioctl(ifp, cmd, data);
3397 	}
3398 
3399 	return (rc);
3400 }
3401 
3402 static int
3403 cxgbe_transmit(if_t ifp, struct mbuf *m)
3404 {
3405 	struct vi_info *vi = if_getsoftc(ifp);
3406 	struct port_info *pi = vi->pi;
3407 	struct adapter *sc;
3408 	struct sge_txq *txq;
3409 	void *items[1];
3410 	int rc;
3411 
3412 	M_ASSERTPKTHDR(m);
3413 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3414 #if defined(KERN_TLS) || defined(RATELIMIT)
3415 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3416 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3417 #endif
3418 
3419 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3420 		m_freem(m);
3421 		return (ENETDOWN);
3422 	}
3423 
3424 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3425 	if (__predict_false(rc != 0)) {
3426 		if (__predict_true(rc == EINPROGRESS)) {
3427 			/* queued by parse_pkt */
3428 			MPASS(m != NULL);
3429 			return (0);
3430 		}
3431 
3432 		MPASS(m == NULL);			/* was freed already */
3433 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3434 		return (rc);
3435 	}
3436 
3437 	/* Select a txq. */
3438 	sc = vi->adapter;
3439 	txq = &sc->sge.txq[vi->first_txq];
3440 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3441 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3442 		    vi->rsrv_noflowq);
3443 
3444 	items[0] = m;
3445 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3446 	if (__predict_false(rc != 0))
3447 		m_freem(m);
3448 
3449 	return (rc);
3450 }
3451 
3452 static void
3453 cxgbe_qflush(if_t ifp)
3454 {
3455 	struct vi_info *vi = if_getsoftc(ifp);
3456 	struct sge_txq *txq;
3457 	int i;
3458 
3459 	/* queues do not exist if !VI_INIT_DONE. */
3460 	if (vi->flags & VI_INIT_DONE) {
3461 		for_each_txq(vi, i, txq) {
3462 			TXQ_LOCK(txq);
3463 			txq->eq.flags |= EQ_QFLUSH;
3464 			TXQ_UNLOCK(txq);
3465 			while (!mp_ring_is_idle(txq->r)) {
3466 				mp_ring_check_drainage(txq->r, 4096);
3467 				pause("qflush", 1);
3468 			}
3469 			TXQ_LOCK(txq);
3470 			txq->eq.flags &= ~EQ_QFLUSH;
3471 			TXQ_UNLOCK(txq);
3472 		}
3473 	}
3474 	if_qflush(ifp);
3475 }
3476 
3477 static uint64_t
3478 vi_get_counter(if_t ifp, ift_counter c)
3479 {
3480 	struct vi_info *vi = if_getsoftc(ifp);
3481 	struct fw_vi_stats_vf *s = &vi->stats;
3482 
3483 	mtx_lock(&vi->tick_mtx);
3484 	vi_refresh_stats(vi);
3485 	mtx_unlock(&vi->tick_mtx);
3486 
3487 	switch (c) {
3488 	case IFCOUNTER_IPACKETS:
3489 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3490 		    s->rx_ucast_frames);
3491 	case IFCOUNTER_IERRORS:
3492 		return (s->rx_err_frames);
3493 	case IFCOUNTER_OPACKETS:
3494 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3495 		    s->tx_ucast_frames + s->tx_offload_frames);
3496 	case IFCOUNTER_OERRORS:
3497 		return (s->tx_drop_frames);
3498 	case IFCOUNTER_IBYTES:
3499 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3500 		    s->rx_ucast_bytes);
3501 	case IFCOUNTER_OBYTES:
3502 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3503 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3504 	case IFCOUNTER_IMCASTS:
3505 		return (s->rx_mcast_frames);
3506 	case IFCOUNTER_OMCASTS:
3507 		return (s->tx_mcast_frames);
3508 	case IFCOUNTER_OQDROPS: {
3509 		uint64_t drops;
3510 
3511 		drops = 0;
3512 		if (vi->flags & VI_INIT_DONE) {
3513 			int i;
3514 			struct sge_txq *txq;
3515 
3516 			for_each_txq(vi, i, txq)
3517 				drops += counter_u64_fetch(txq->r->dropped);
3518 		}
3519 
3520 		return (drops);
3521 
3522 	}
3523 
3524 	default:
3525 		return (if_get_counter_default(ifp, c));
3526 	}
3527 }
3528 
3529 static uint64_t
3530 cxgbe_get_counter(if_t ifp, ift_counter c)
3531 {
3532 	struct vi_info *vi = if_getsoftc(ifp);
3533 	struct port_info *pi = vi->pi;
3534 	struct port_stats *s = &pi->stats;
3535 
3536 	mtx_lock(&vi->tick_mtx);
3537 	cxgbe_refresh_stats(vi);
3538 	mtx_unlock(&vi->tick_mtx);
3539 
3540 	switch (c) {
3541 	case IFCOUNTER_IPACKETS:
3542 		return (s->rx_frames);
3543 
3544 	case IFCOUNTER_IERRORS:
3545 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3546 		    s->rx_fcs_err + s->rx_len_err);
3547 
3548 	case IFCOUNTER_OPACKETS:
3549 		return (s->tx_frames);
3550 
3551 	case IFCOUNTER_OERRORS:
3552 		return (s->tx_error_frames);
3553 
3554 	case IFCOUNTER_IBYTES:
3555 		return (s->rx_octets);
3556 
3557 	case IFCOUNTER_OBYTES:
3558 		return (s->tx_octets);
3559 
3560 	case IFCOUNTER_IMCASTS:
3561 		return (s->rx_mcast_frames);
3562 
3563 	case IFCOUNTER_OMCASTS:
3564 		return (s->tx_mcast_frames);
3565 
3566 	case IFCOUNTER_IQDROPS:
3567 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3568 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3569 		    s->rx_trunc3 + pi->tnl_cong_drops);
3570 
3571 	case IFCOUNTER_OQDROPS: {
3572 		uint64_t drops;
3573 
3574 		drops = s->tx_drop;
3575 		if (vi->flags & VI_INIT_DONE) {
3576 			int i;
3577 			struct sge_txq *txq;
3578 
3579 			for_each_txq(vi, i, txq)
3580 				drops += counter_u64_fetch(txq->r->dropped);
3581 		}
3582 
3583 		return (drops);
3584 
3585 	}
3586 
3587 	default:
3588 		return (if_get_counter_default(ifp, c));
3589 	}
3590 }
3591 
3592 #if defined(KERN_TLS) || defined(RATELIMIT)
3593 static int
3594 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3595     struct m_snd_tag **pt)
3596 {
3597 	int error;
3598 
3599 	switch (params->hdr.type) {
3600 #ifdef RATELIMIT
3601 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3602 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3603 		break;
3604 #endif
3605 #ifdef KERN_TLS
3606 	case IF_SND_TAG_TYPE_TLS:
3607 	{
3608 		struct vi_info *vi = if_getsoftc(ifp);
3609 
3610 		if (is_t6(vi->pi->adapter))
3611 			error = t6_tls_tag_alloc(ifp, params, pt);
3612 		else
3613 			error = t7_tls_tag_alloc(ifp, params, pt);
3614 		break;
3615 	}
3616 #endif
3617 	default:
3618 		error = EOPNOTSUPP;
3619 	}
3620 	return (error);
3621 }
3622 #endif
3623 
3624 /*
3625  * The kernel picks a media from the list we had provided but we still validate
3626  * the requeste.
3627  */
3628 int
3629 cxgbe_media_change(if_t ifp)
3630 {
3631 	struct vi_info *vi = if_getsoftc(ifp);
3632 	struct port_info *pi = vi->pi;
3633 	struct ifmedia *ifm = &pi->media;
3634 	struct link_config *lc = &pi->link_cfg;
3635 	struct adapter *sc = pi->adapter;
3636 	int rc;
3637 
3638 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3639 	if (rc != 0)
3640 		return (rc);
3641 	PORT_LOCK(pi);
3642 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3643 		/* ifconfig .. media autoselect */
3644 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3645 			rc = ENOTSUP; /* AN not supported by transceiver */
3646 			goto done;
3647 		}
3648 		lc->requested_aneg = AUTONEG_ENABLE;
3649 		lc->requested_speed = 0;
3650 		lc->requested_fc |= PAUSE_AUTONEG;
3651 	} else {
3652 		lc->requested_aneg = AUTONEG_DISABLE;
3653 		lc->requested_speed =
3654 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3655 		lc->requested_fc = 0;
3656 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3657 			lc->requested_fc |= PAUSE_RX;
3658 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3659 			lc->requested_fc |= PAUSE_TX;
3660 	}
3661 	if (pi->up_vis > 0 && hw_all_ok(sc)) {
3662 		fixup_link_config(pi);
3663 		rc = apply_link_config(pi);
3664 	}
3665 done:
3666 	PORT_UNLOCK(pi);
3667 	end_synchronized_op(sc, 0);
3668 	return (rc);
3669 }
3670 
3671 /*
3672  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3673  * given speed.
3674  */
3675 static int
3676 port_mword(struct port_info *pi, uint32_t speed)
3677 {
3678 
3679 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3680 	MPASS(powerof2(speed));
3681 
3682 	switch(pi->port_type) {
3683 	case FW_PORT_TYPE_BT_SGMII:
3684 	case FW_PORT_TYPE_BT_XFI:
3685 	case FW_PORT_TYPE_BT_XAUI:
3686 		/* BaseT */
3687 		switch (speed) {
3688 		case FW_PORT_CAP32_SPEED_100M:
3689 			return (IFM_100_T);
3690 		case FW_PORT_CAP32_SPEED_1G:
3691 			return (IFM_1000_T);
3692 		case FW_PORT_CAP32_SPEED_10G:
3693 			return (IFM_10G_T);
3694 		}
3695 		break;
3696 	case FW_PORT_TYPE_KX4:
3697 		if (speed == FW_PORT_CAP32_SPEED_10G)
3698 			return (IFM_10G_KX4);
3699 		break;
3700 	case FW_PORT_TYPE_CX4:
3701 		if (speed == FW_PORT_CAP32_SPEED_10G)
3702 			return (IFM_10G_CX4);
3703 		break;
3704 	case FW_PORT_TYPE_KX:
3705 		if (speed == FW_PORT_CAP32_SPEED_1G)
3706 			return (IFM_1000_KX);
3707 		break;
3708 	case FW_PORT_TYPE_KR:
3709 	case FW_PORT_TYPE_BP_AP:
3710 	case FW_PORT_TYPE_BP4_AP:
3711 	case FW_PORT_TYPE_BP40_BA:
3712 	case FW_PORT_TYPE_KR4_100G:
3713 	case FW_PORT_TYPE_KR_SFP28:
3714 	case FW_PORT_TYPE_KR_XLAUI:
3715 		switch (speed) {
3716 		case FW_PORT_CAP32_SPEED_1G:
3717 			return (IFM_1000_KX);
3718 		case FW_PORT_CAP32_SPEED_10G:
3719 			return (IFM_10G_KR);
3720 		case FW_PORT_CAP32_SPEED_25G:
3721 			return (IFM_25G_KR);
3722 		case FW_PORT_CAP32_SPEED_40G:
3723 			return (IFM_40G_KR4);
3724 		case FW_PORT_CAP32_SPEED_50G:
3725 			return (IFM_50G_KR2);
3726 		case FW_PORT_CAP32_SPEED_100G:
3727 			return (IFM_100G_KR4);
3728 		}
3729 		break;
3730 	case FW_PORT_TYPE_FIBER_XFI:
3731 	case FW_PORT_TYPE_FIBER_XAUI:
3732 	case FW_PORT_TYPE_SFP:
3733 	case FW_PORT_TYPE_QSFP_10G:
3734 	case FW_PORT_TYPE_QSA:
3735 	case FW_PORT_TYPE_QSFP:
3736 	case FW_PORT_TYPE_CR4_QSFP:
3737 	case FW_PORT_TYPE_CR_QSFP:
3738 	case FW_PORT_TYPE_CR2_QSFP:
3739 	case FW_PORT_TYPE_SFP28:
3740 	case FW_PORT_TYPE_SFP56:
3741 	case FW_PORT_TYPE_QSFP56:
3742 	case FW_PORT_TYPE_QSFPDD:
3743 		/* Pluggable transceiver */
3744 		switch (pi->mod_type) {
3745 		case FW_PORT_MOD_TYPE_LR:
3746 		case FW_PORT_MOD_TYPE_LR_SIMPLEX:
3747 			switch (speed) {
3748 			case FW_PORT_CAP32_SPEED_1G:
3749 				return (IFM_1000_LX);
3750 			case FW_PORT_CAP32_SPEED_10G:
3751 				return (IFM_10G_LR);
3752 			case FW_PORT_CAP32_SPEED_25G:
3753 				return (IFM_25G_LR);
3754 			case FW_PORT_CAP32_SPEED_40G:
3755 				return (IFM_40G_LR4);
3756 			case FW_PORT_CAP32_SPEED_50G:
3757 				return (IFM_50G_LR2);
3758 			case FW_PORT_CAP32_SPEED_100G:
3759 				return (IFM_100G_LR4);
3760 			case FW_PORT_CAP32_SPEED_200G:
3761 				return (IFM_200G_LR4);
3762 			case FW_PORT_CAP32_SPEED_400G:
3763 				return (IFM_400G_LR8);
3764 			}
3765 			break;
3766 		case FW_PORT_MOD_TYPE_SR:
3767 			switch (speed) {
3768 			case FW_PORT_CAP32_SPEED_1G:
3769 				return (IFM_1000_SX);
3770 			case FW_PORT_CAP32_SPEED_10G:
3771 				return (IFM_10G_SR);
3772 			case FW_PORT_CAP32_SPEED_25G:
3773 				return (IFM_25G_SR);
3774 			case FW_PORT_CAP32_SPEED_40G:
3775 				return (IFM_40G_SR4);
3776 			case FW_PORT_CAP32_SPEED_50G:
3777 				return (IFM_50G_SR2);
3778 			case FW_PORT_CAP32_SPEED_100G:
3779 				return (IFM_100G_SR4);
3780 			case FW_PORT_CAP32_SPEED_200G:
3781 				return (IFM_200G_SR4);
3782 			case FW_PORT_CAP32_SPEED_400G:
3783 				return (IFM_400G_SR8);
3784 			}
3785 			break;
3786 		case FW_PORT_MOD_TYPE_ER:
3787 			if (speed == FW_PORT_CAP32_SPEED_10G)
3788 				return (IFM_10G_ER);
3789 			break;
3790 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3791 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3792 			switch (speed) {
3793 			case FW_PORT_CAP32_SPEED_1G:
3794 				return (IFM_1000_CX);
3795 			case FW_PORT_CAP32_SPEED_10G:
3796 				return (IFM_10G_TWINAX);
3797 			case FW_PORT_CAP32_SPEED_25G:
3798 				return (IFM_25G_CR);
3799 			case FW_PORT_CAP32_SPEED_40G:
3800 				return (IFM_40G_CR4);
3801 			case FW_PORT_CAP32_SPEED_50G:
3802 				return (IFM_50G_CR2);
3803 			case FW_PORT_CAP32_SPEED_100G:
3804 				return (IFM_100G_CR4);
3805 			case FW_PORT_CAP32_SPEED_200G:
3806 				return (IFM_200G_CR4_PAM4);
3807 			case FW_PORT_CAP32_SPEED_400G:
3808 				return (IFM_400G_CR8);
3809 			}
3810 			break;
3811 		case FW_PORT_MOD_TYPE_LRM:
3812 			if (speed == FW_PORT_CAP32_SPEED_10G)
3813 				return (IFM_10G_LRM);
3814 			break;
3815 		case FW_PORT_MOD_TYPE_DR:
3816 			if (speed == FW_PORT_CAP32_SPEED_100G)
3817 				return (IFM_100G_DR);
3818 			if (speed == FW_PORT_CAP32_SPEED_200G)
3819 				return (IFM_200G_DR4);
3820 			if (speed == FW_PORT_CAP32_SPEED_400G)
3821 				return (IFM_400G_DR4);
3822 			break;
3823 		case FW_PORT_MOD_TYPE_NA:
3824 			MPASS(0);	/* Not pluggable? */
3825 			/* fall through */
3826 		case FW_PORT_MOD_TYPE_ERROR:
3827 		case FW_PORT_MOD_TYPE_UNKNOWN:
3828 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3829 			break;
3830 		case FW_PORT_MOD_TYPE_NONE:
3831 			return (IFM_NONE);
3832 		}
3833 		break;
3834 	case FW_PORT_TYPE_KR4_200G: {
3835 		/*
3836 		 * Pre-T7 firmware used M_FW_PORT_CMD_PTYPE for PORT_TYPE_NONE
3837 		 * and driver needs to deal with both.
3838 		 */
3839 		_Static_assert(M_FW_PORT_CMD_PTYPE == FW_PORT_TYPE_KR4_200G,
3840 		    "driver/firmware mismatch");
3841 		if (chip_id(pi->adapter) < CHELSIO_T7)
3842 			return (IFM_NONE);
3843 		return (IFM_200G_KR4_PAM4);
3844 	}
3845 	case FW_PORT_TYPE_NONE:
3846 		return (IFM_NONE);
3847 	}
3848 
3849 	return (IFM_UNKNOWN);
3850 }
3851 
3852 void
3853 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3854 {
3855 	struct vi_info *vi = if_getsoftc(ifp);
3856 	struct port_info *pi = vi->pi;
3857 	struct adapter *sc = pi->adapter;
3858 	struct link_config *lc = &pi->link_cfg;
3859 
3860 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3861 		return;
3862 	PORT_LOCK(pi);
3863 
3864 	if (pi->up_vis == 0 && hw_all_ok(sc)) {
3865 		/*
3866 		 * If all the interfaces are administratively down the firmware
3867 		 * does not report transceiver changes.  Refresh port info here
3868 		 * so that ifconfig displays accurate ifmedia at all times.
3869 		 * This is the only reason we have a synchronized op in this
3870 		 * function.  Just PORT_LOCK would have been enough otherwise.
3871 		 */
3872 		t4_update_port_info(pi);
3873 		build_medialist(pi);
3874 	}
3875 
3876 	/* ifm_status */
3877 	ifmr->ifm_status = IFM_AVALID;
3878 	if (lc->link_ok == false)
3879 		goto done;
3880 	ifmr->ifm_status |= IFM_ACTIVE;
3881 
3882 	/* ifm_active */
3883 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3884 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3885 	if (lc->fc & PAUSE_RX)
3886 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3887 	if (lc->fc & PAUSE_TX)
3888 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3889 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3890 done:
3891 	PORT_UNLOCK(pi);
3892 	end_synchronized_op(sc, 0);
3893 }
3894 
3895 static int
3896 vcxgbe_probe(device_t dev)
3897 {
3898 	struct vi_info *vi = device_get_softc(dev);
3899 
3900 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3901 	    vi - vi->pi->vi);
3902 
3903 	return (BUS_PROBE_DEFAULT);
3904 }
3905 
3906 static int
3907 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3908 {
3909 	int func, index, rc;
3910 	uint32_t param, val;
3911 
3912 	ASSERT_SYNCHRONIZED_OP(sc);
3913 
3914 	index = vi - pi->vi;
3915 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3916 	KASSERT(index < nitems(vi_mac_funcs),
3917 	    ("%s: VI %s doesn't have a MAC func", __func__,
3918 	    device_get_nameunit(vi->dev)));
3919 	func = vi_mac_funcs[index];
3920 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->hw_port, sc->pf, 0, 1,
3921 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3922 	if (rc < 0) {
3923 		CH_ERR(vi, "failed to allocate virtual interface %d"
3924 		    "for port %d: %d\n", index, pi->port_id, -rc);
3925 		return (-rc);
3926 	}
3927 	vi->viid = rc;
3928 
3929 	if (vi->rss_size == 1) {
3930 		/*
3931 		 * This VI didn't get a slice of the RSS table.  Reduce the
3932 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3933 		 * configuration file (nvi, rssnvi for this PF) if this is a
3934 		 * problem.
3935 		 */
3936 		device_printf(vi->dev, "RSS table not available.\n");
3937 		vi->rss_base = 0xffff;
3938 
3939 		return (0);
3940 	}
3941 
3942 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3943 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3944 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3945 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3946 	if (rc)
3947 		vi->rss_base = 0xffff;
3948 	else {
3949 		MPASS((val >> 16) == vi->rss_size);
3950 		vi->rss_base = val & 0xffff;
3951 	}
3952 
3953 	return (0);
3954 }
3955 
3956 static int
3957 vcxgbe_attach(device_t dev)
3958 {
3959 	struct vi_info *vi;
3960 	struct port_info *pi;
3961 	struct adapter *sc;
3962 	int rc;
3963 
3964 	vi = device_get_softc(dev);
3965 	pi = vi->pi;
3966 	sc = pi->adapter;
3967 
3968 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3969 	if (rc)
3970 		return (rc);
3971 	rc = alloc_extra_vi(sc, pi, vi);
3972 	end_synchronized_op(sc, 0);
3973 	if (rc)
3974 		return (rc);
3975 
3976 	cxgbe_vi_attach(dev, vi);
3977 
3978 	return (0);
3979 }
3980 
3981 static int
3982 vcxgbe_detach(device_t dev)
3983 {
3984 	struct vi_info *vi;
3985 	struct adapter *sc;
3986 
3987 	vi = device_get_softc(dev);
3988 	sc = vi->adapter;
3989 
3990 	begin_vi_detach(sc, vi);
3991 	cxgbe_vi_detach(vi);
3992 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3993 	end_vi_detach(sc, vi);
3994 
3995 	return (0);
3996 }
3997 
3998 static struct callout fatal_callout;
3999 static struct taskqueue *reset_tq;
4000 
4001 static void
4002 delayed_panic(void *arg)
4003 {
4004 	struct adapter *sc = arg;
4005 
4006 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
4007 }
4008 
4009 static void
4010 fatal_error_task(void *arg, int pending)
4011 {
4012 	struct adapter *sc = arg;
4013 	int rc;
4014 
4015 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
4016 		dump_cim_regs(sc);
4017 		dump_cimla(sc);
4018 		dump_devlog(sc);
4019 	}
4020 
4021 	if (t4_reset_on_fatal_err) {
4022 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
4023 		rc = reset_adapter(sc);
4024 		if (rc == 0 && t4_panic_on_fatal_err) {
4025 			CH_ALERT(sc, "reset was successful, "
4026 			    "system will NOT panic.\n");
4027 			return;
4028 		}
4029 	}
4030 
4031 	if (t4_panic_on_fatal_err) {
4032 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
4033 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
4034 	}
4035 }
4036 
4037 void
4038 t4_fatal_err(struct adapter *sc, bool fw_error)
4039 {
4040 	stop_adapter(sc);
4041 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
4042 		return;
4043 	if (fw_error) {
4044 		/*
4045 		 * We are here because of a firmware error/timeout and not
4046 		 * because of a hardware interrupt.  It is possible (although
4047 		 * not very likely) that an error interrupt was also raised but
4048 		 * this thread ran first and inhibited t4_intr_err.  We walk the
4049 		 * main INT_CAUSE registers here to make sure we haven't missed
4050 		 * anything interesting.
4051 		 */
4052 		t4_slow_intr_handler(sc, sc->intr_flags);
4053 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
4054 	}
4055 	t4_report_fw_error(sc);
4056 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
4057 	    device_get_nameunit(sc->dev), fw_error);
4058 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
4059 }
4060 
4061 void
4062 t4_add_adapter(struct adapter *sc)
4063 {
4064 	sx_xlock(&t4_list_lock);
4065 	SLIST_INSERT_HEAD(&t4_list, sc, link);
4066 	sx_xunlock(&t4_list_lock);
4067 }
4068 
4069 int
4070 t4_map_bars_0_and_4(struct adapter *sc)
4071 {
4072 	sc->regs_rid = PCIR_BAR(0);
4073 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4074 	    &sc->regs_rid, RF_ACTIVE);
4075 	if (sc->regs_res == NULL) {
4076 		device_printf(sc->dev, "cannot map registers.\n");
4077 		return (ENXIO);
4078 	}
4079 	sc->mmio_len = rman_get_size(sc->regs_res);
4080 	setbit(&sc->doorbells, DOORBELL_KDB);
4081 
4082 	sc->msix_rid = PCIR_BAR(4);
4083 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4084 	    &sc->msix_rid, RF_ACTIVE);
4085 	if (sc->msix_res == NULL) {
4086 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
4087 		return (ENXIO);
4088 	}
4089 
4090 	return (0);
4091 }
4092 
4093 int
4094 t4_map_bar_2(struct adapter *sc)
4095 {
4096 
4097 	/*
4098 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
4099 	 * to map it if RDMA is disabled.
4100 	 */
4101 	if (is_t4(sc) && sc->rdmacaps == 0)
4102 		return (0);
4103 
4104 	sc->udbs_rid = PCIR_BAR(2);
4105 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4106 	    &sc->udbs_rid, RF_ACTIVE);
4107 	if (sc->udbs_res == NULL) {
4108 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
4109 		return (ENXIO);
4110 	}
4111 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
4112 
4113 	if (chip_id(sc) >= CHELSIO_T5) {
4114 		setbit(&sc->doorbells, DOORBELL_UDB);
4115 #if defined(__i386__) || defined(__amd64__)
4116 		if (t5_write_combine) {
4117 			int rc, mode;
4118 
4119 			/*
4120 			 * Enable write combining on BAR2.  This is the
4121 			 * userspace doorbell BAR and is split into 128B
4122 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
4123 			 * with an egress queue.  The first 64B has the doorbell
4124 			 * and the second 64B can be used to submit a tx work
4125 			 * request with an implicit doorbell.
4126 			 */
4127 
4128 			rc = pmap_change_attr(__DEVOLATILE(void *, sc->udbs_base),
4129 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
4130 			if (rc == 0) {
4131 				clrbit(&sc->doorbells, DOORBELL_UDB);
4132 				setbit(&sc->doorbells, DOORBELL_WCWR);
4133 				setbit(&sc->doorbells, DOORBELL_UDBWC);
4134 			} else {
4135 				device_printf(sc->dev,
4136 				    "couldn't enable write combining: %d\n",
4137 				    rc);
4138 			}
4139 
4140 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
4141 			t4_write_reg(sc, A_SGE_STAT_CFG,
4142 			    V_STATSOURCE_T5(7) | mode);
4143 		}
4144 #endif
4145 	}
4146 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
4147 
4148 	return (0);
4149 }
4150 
4151 int
4152 t4_adj_doorbells(struct adapter *sc)
4153 {
4154 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
4155 		sc->doorbells &= t4_doorbells_allowed;
4156 		return (0);
4157 	}
4158 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
4159 	       sc->doorbells, t4_doorbells_allowed);
4160 	return (EINVAL);
4161 }
4162 
4163 struct memwin_init {
4164 	uint32_t base;
4165 	uint32_t aperture;
4166 };
4167 
4168 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
4169 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4170 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4171 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
4172 };
4173 
4174 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
4175 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4176 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4177 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
4178 };
4179 
4180 static void
4181 setup_memwin(struct adapter *sc)
4182 {
4183 	const struct memwin_init *mw_init;
4184 	struct memwin *mw;
4185 	int i;
4186 	uint32_t bar0, reg;
4187 
4188 	if (is_t4(sc)) {
4189 		/*
4190 		 * Read low 32b of bar0 indirectly via the hardware backdoor
4191 		 * mechanism.  Works from within PCI passthrough environments
4192 		 * too, where rman_get_start() can return a different value.  We
4193 		 * need to program the T4 memory window decoders with the actual
4194 		 * addresses that will be coming across the PCIe link.
4195 		 */
4196 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
4197 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
4198 
4199 		mw_init = &t4_memwin[0];
4200 	} else {
4201 		/* T5+ use the relative offset inside the PCIe BAR */
4202 		bar0 = 0;
4203 
4204 		mw_init = &t5_memwin[0];
4205 	}
4206 
4207 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
4208 		if (!rw_initialized(&mw->mw_lock)) {
4209 			rw_init(&mw->mw_lock, "memory window access");
4210 			mw->mw_base = mw_init->base;
4211 			mw->mw_aperture = mw_init->aperture;
4212 			mw->mw_curpos = 0;
4213 		}
4214 		reg = chip_id(sc) > CHELSIO_T6 ?
4215 		    PCIE_MEM_ACCESS_T7_REG(A_T7_PCIE_MEM_ACCESS_BASE_WIN, i) :
4216 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i);
4217 		t4_write_reg(sc, reg, (mw->mw_base + bar0) | V_BIR(0) |
4218 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
4219 		rw_wlock(&mw->mw_lock);
4220 		position_memwin(sc, i, mw->mw_curpos);
4221 		rw_wunlock(&mw->mw_lock);
4222 	}
4223 
4224 	/* flush */
4225 	t4_read_reg(sc, reg);
4226 }
4227 
4228 /*
4229  * Positions the memory window at the given address in the card's address space.
4230  * There are some alignment requirements and the actual position may be at an
4231  * address prior to the requested address.  mw->mw_curpos always has the actual
4232  * position of the window.
4233  */
4234 static void
4235 position_memwin(struct adapter *sc, int idx, uint32_t addr)
4236 {
4237 	struct memwin *mw;
4238 	uint32_t pf, reg, val;
4239 
4240 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4241 	mw = &sc->memwin[idx];
4242 	rw_assert(&mw->mw_lock, RA_WLOCKED);
4243 
4244 	if (is_t4(sc)) {
4245 		pf = 0;
4246 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
4247 	} else {
4248 		pf = V_PFNUM(sc->pf);
4249 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
4250 	}
4251 	if (chip_id(sc) > CHELSIO_T6) {
4252 		reg = PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, idx);
4253 		val = (mw->mw_curpos >> X_T7_MEMOFST_SHIFT) | pf;
4254 	} else {
4255 		reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
4256 		val = mw->mw_curpos | pf;
4257 	}
4258 	t4_write_reg(sc, reg, val);
4259 	t4_read_reg(sc, reg);	/* flush */
4260 }
4261 
4262 int
4263 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
4264     int len, int rw)
4265 {
4266 	struct memwin *mw;
4267 	uint32_t mw_end, v;
4268 
4269 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4270 
4271 	/* Memory can only be accessed in naturally aligned 4 byte units */
4272 	if (addr & 3 || len & 3 || len <= 0)
4273 		return (EINVAL);
4274 
4275 	mw = &sc->memwin[idx];
4276 	while (len > 0) {
4277 		rw_rlock(&mw->mw_lock);
4278 		mw_end = mw->mw_curpos + mw->mw_aperture;
4279 		if (addr >= mw_end || addr < mw->mw_curpos) {
4280 			/* Will need to reposition the window */
4281 			if (!rw_try_upgrade(&mw->mw_lock)) {
4282 				rw_runlock(&mw->mw_lock);
4283 				rw_wlock(&mw->mw_lock);
4284 			}
4285 			rw_assert(&mw->mw_lock, RA_WLOCKED);
4286 			position_memwin(sc, idx, addr);
4287 			rw_downgrade(&mw->mw_lock);
4288 			mw_end = mw->mw_curpos + mw->mw_aperture;
4289 		}
4290 		rw_assert(&mw->mw_lock, RA_RLOCKED);
4291 		while (addr < mw_end && len > 0) {
4292 			if (rw == 0) {
4293 				v = t4_read_reg(sc, mw->mw_base + addr -
4294 				    mw->mw_curpos);
4295 				*val++ = le32toh(v);
4296 			} else {
4297 				v = *val++;
4298 				t4_write_reg(sc, mw->mw_base + addr -
4299 				    mw->mw_curpos, htole32(v));
4300 			}
4301 			addr += 4;
4302 			len -= 4;
4303 		}
4304 		rw_runlock(&mw->mw_lock);
4305 	}
4306 
4307 	return (0);
4308 }
4309 
4310 CTASSERT(M_TID_COOKIE == M_COOKIE);
4311 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
4312 
4313 static void
4314 t4_init_atid_table(struct adapter *sc)
4315 {
4316 	struct tid_info *t;
4317 	int i;
4318 
4319 	t = &sc->tids;
4320 	if (t->natids == 0)
4321 		return;
4322 
4323 	MPASS(t->atid_tab == NULL);
4324 
4325 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
4326 	    M_ZERO | M_WAITOK);
4327 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
4328 	t->afree = t->atid_tab;
4329 	t->atids_in_use = 0;
4330 	t->atid_alloc_stopped = false;
4331 	for (i = 1; i < t->natids; i++)
4332 		t->atid_tab[i - 1].next = &t->atid_tab[i];
4333 	t->atid_tab[t->natids - 1].next = NULL;
4334 }
4335 
4336 static void
4337 t4_free_atid_table(struct adapter *sc)
4338 {
4339 	struct tid_info *t;
4340 
4341 	t = &sc->tids;
4342 
4343 	KASSERT(t->atids_in_use == 0,
4344 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4345 
4346 	if (mtx_initialized(&t->atid_lock))
4347 		mtx_destroy(&t->atid_lock);
4348 	free(t->atid_tab, M_CXGBE);
4349 	t->atid_tab = NULL;
4350 }
4351 
4352 static void
4353 stop_atid_allocator(struct adapter *sc)
4354 {
4355 	struct tid_info *t = &sc->tids;
4356 
4357 	if (t->natids == 0)
4358 		return;
4359 	mtx_lock(&t->atid_lock);
4360 	t->atid_alloc_stopped = true;
4361 	mtx_unlock(&t->atid_lock);
4362 }
4363 
4364 static void
4365 restart_atid_allocator(struct adapter *sc)
4366 {
4367 	struct tid_info *t = &sc->tids;
4368 
4369 	if (t->natids == 0)
4370 		return;
4371 	mtx_lock(&t->atid_lock);
4372 	KASSERT(t->atids_in_use == 0,
4373 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4374 	t->atid_alloc_stopped = false;
4375 	mtx_unlock(&t->atid_lock);
4376 }
4377 
4378 int
4379 alloc_atid(struct adapter *sc, void *ctx)
4380 {
4381 	struct tid_info *t = &sc->tids;
4382 	int atid = -1;
4383 
4384 	mtx_lock(&t->atid_lock);
4385 	if (t->afree && !t->atid_alloc_stopped) {
4386 		union aopen_entry *p = t->afree;
4387 
4388 		atid = p - t->atid_tab;
4389 		MPASS(atid <= M_TID_TID);
4390 		t->afree = p->next;
4391 		p->data = ctx;
4392 		t->atids_in_use++;
4393 	}
4394 	mtx_unlock(&t->atid_lock);
4395 	return (atid);
4396 }
4397 
4398 void *
4399 lookup_atid(struct adapter *sc, int atid)
4400 {
4401 	struct tid_info *t = &sc->tids;
4402 
4403 	return (t->atid_tab[atid].data);
4404 }
4405 
4406 void
4407 free_atid(struct adapter *sc, int atid)
4408 {
4409 	struct tid_info *t = &sc->tids;
4410 	union aopen_entry *p = &t->atid_tab[atid];
4411 
4412 	mtx_lock(&t->atid_lock);
4413 	p->next = t->afree;
4414 	t->afree = p;
4415 	t->atids_in_use--;
4416 	mtx_unlock(&t->atid_lock);
4417 }
4418 
4419 static void
4420 queue_tid_release(struct adapter *sc, int tid)
4421 {
4422 
4423 	CXGBE_UNIMPLEMENTED("deferred tid release");
4424 }
4425 
4426 void
4427 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4428 {
4429 	struct wrqe *wr;
4430 	struct cpl_tid_release *req;
4431 
4432 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4433 	if (wr == NULL) {
4434 		queue_tid_release(sc, tid);	/* defer */
4435 		return;
4436 	}
4437 	req = wrtod(wr);
4438 
4439 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4440 
4441 	t4_wrq_tx(sc, wr);
4442 }
4443 
4444 static int
4445 t4_range_cmp(const void *a, const void *b)
4446 {
4447 	return ((const struct t4_range *)a)->start -
4448 	       ((const struct t4_range *)b)->start;
4449 }
4450 
4451 /*
4452  * Verify that the memory range specified by the addr/len pair is valid within
4453  * the card's address space.
4454  */
4455 static int
4456 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4457 {
4458 	struct t4_range mem_ranges[4], *r, *next;
4459 	uint32_t em, addr_len;
4460 	int i, n, remaining;
4461 
4462 	/* Memory can only be accessed in naturally aligned 4 byte units */
4463 	if (addr & 3 || len & 3 || len == 0)
4464 		return (EINVAL);
4465 
4466 	/* Enabled memories */
4467 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4468 
4469 	r = &mem_ranges[0];
4470 	n = 0;
4471 	bzero(r, sizeof(mem_ranges));
4472 	if (em & F_EDRAM0_ENABLE) {
4473 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4474 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4475 		if (r->size > 0) {
4476 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4477 			if (addr >= r->start &&
4478 			    addr + len <= r->start + r->size)
4479 				return (0);
4480 			r++;
4481 			n++;
4482 		}
4483 	}
4484 	if (em & F_EDRAM1_ENABLE) {
4485 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4486 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4487 		if (r->size > 0) {
4488 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4489 			if (addr >= r->start &&
4490 			    addr + len <= r->start + r->size)
4491 				return (0);
4492 			r++;
4493 			n++;
4494 		}
4495 	}
4496 	if (em & F_EXT_MEM_ENABLE) {
4497 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4498 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4499 		if (r->size > 0) {
4500 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4501 			if (addr >= r->start &&
4502 			    addr + len <= r->start + r->size)
4503 				return (0);
4504 			r++;
4505 			n++;
4506 		}
4507 	}
4508 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4509 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4510 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4511 		if (r->size > 0) {
4512 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4513 			if (addr >= r->start &&
4514 			    addr + len <= r->start + r->size)
4515 				return (0);
4516 			r++;
4517 			n++;
4518 		}
4519 	}
4520 	MPASS(n <= nitems(mem_ranges));
4521 
4522 	if (n > 1) {
4523 		/* Sort and merge the ranges. */
4524 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4525 
4526 		/* Start from index 0 and examine the next n - 1 entries. */
4527 		r = &mem_ranges[0];
4528 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4529 
4530 			MPASS(r->size > 0);	/* r is a valid entry. */
4531 			next = r + 1;
4532 			MPASS(next->size > 0);	/* and so is the next one. */
4533 
4534 			while (r->start + r->size >= next->start) {
4535 				/* Merge the next one into the current entry. */
4536 				r->size = max(r->start + r->size,
4537 				    next->start + next->size) - r->start;
4538 				n--;	/* One fewer entry in total. */
4539 				if (--remaining == 0)
4540 					goto done;	/* short circuit */
4541 				next++;
4542 			}
4543 			if (next != r + 1) {
4544 				/*
4545 				 * Some entries were merged into r and next
4546 				 * points to the first valid entry that couldn't
4547 				 * be merged.
4548 				 */
4549 				MPASS(next->size > 0);	/* must be valid */
4550 				memcpy(r + 1, next, remaining * sizeof(*r));
4551 #ifdef INVARIANTS
4552 				/*
4553 				 * This so that the foo->size assertion in the
4554 				 * next iteration of the loop do the right
4555 				 * thing for entries that were pulled up and are
4556 				 * no longer valid.
4557 				 */
4558 				MPASS(n < nitems(mem_ranges));
4559 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4560 				    sizeof(struct t4_range));
4561 #endif
4562 			}
4563 		}
4564 done:
4565 		/* Done merging the ranges. */
4566 		MPASS(n > 0);
4567 		r = &mem_ranges[0];
4568 		for (i = 0; i < n; i++, r++) {
4569 			if (addr >= r->start &&
4570 			    addr + len <= r->start + r->size)
4571 				return (0);
4572 		}
4573 	}
4574 
4575 	return (EFAULT);
4576 }
4577 
4578 static int
4579 fwmtype_to_hwmtype(int mtype)
4580 {
4581 
4582 	switch (mtype) {
4583 	case FW_MEMTYPE_EDC0:
4584 		return (MEM_EDC0);
4585 	case FW_MEMTYPE_EDC1:
4586 		return (MEM_EDC1);
4587 	case FW_MEMTYPE_EXTMEM:
4588 		return (MEM_MC0);
4589 	case FW_MEMTYPE_EXTMEM1:
4590 		return (MEM_MC1);
4591 	default:
4592 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4593 	}
4594 }
4595 
4596 /*
4597  * Verify that the memory range specified by the memtype/offset/len pair is
4598  * valid and lies entirely within the memtype specified.  The global address of
4599  * the start of the range is returned in addr.
4600  */
4601 static int
4602 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4603     uint32_t *addr)
4604 {
4605 	uint32_t em, addr_len, maddr;
4606 
4607 	/* Memory can only be accessed in naturally aligned 4 byte units */
4608 	if (off & 3 || len & 3 || len == 0)
4609 		return (EINVAL);
4610 
4611 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4612 	switch (fwmtype_to_hwmtype(mtype)) {
4613 	case MEM_EDC0:
4614 		if (!(em & F_EDRAM0_ENABLE))
4615 			return (EINVAL);
4616 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4617 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4618 		break;
4619 	case MEM_EDC1:
4620 		if (!(em & F_EDRAM1_ENABLE))
4621 			return (EINVAL);
4622 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4623 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4624 		break;
4625 	case MEM_MC:
4626 		if (!(em & F_EXT_MEM_ENABLE))
4627 			return (EINVAL);
4628 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4629 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4630 		break;
4631 	case MEM_MC1:
4632 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4633 			return (EINVAL);
4634 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4635 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4636 		break;
4637 	default:
4638 		return (EINVAL);
4639 	}
4640 
4641 	*addr = maddr + off;	/* global address */
4642 	return (validate_mem_range(sc, *addr, len));
4643 }
4644 
4645 static int
4646 fixup_devlog_ncores_params(struct adapter *sc)
4647 {
4648 	struct devlog_params *dparams = &sc->params.devlog;
4649 	int rc;
4650 
4651 #ifdef INVARIANTS
4652 	if (sc->params.ncores > 1)
4653 		MPASS(chip_id(sc) >= CHELSIO_T7);
4654 #endif
4655 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4656 	    dparams->size, &dparams->addr);
4657 
4658 	return (rc);
4659 }
4660 
4661 static void
4662 update_nirq(struct intrs_and_queues *iaq, int nports)
4663 {
4664 
4665 	iaq->nirq = T4_EXTRA_INTR;
4666 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4667 	iaq->nirq += nports * iaq->nofldrxq;
4668 	iaq->nirq += nports * (iaq->num_vis - 1) *
4669 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4670 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4671 }
4672 
4673 /*
4674  * Adjust requirements to fit the number of interrupts available.
4675  */
4676 static void
4677 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4678     int navail)
4679 {
4680 	int old_nirq;
4681 	const int nports = sc->params.nports;
4682 
4683 	MPASS(nports > 0);
4684 	MPASS(navail > 0);
4685 
4686 	bzero(iaq, sizeof(*iaq));
4687 	iaq->intr_type = itype;
4688 	iaq->num_vis = t4_num_vis;
4689 	iaq->ntxq = t4_ntxq;
4690 	iaq->ntxq_vi = t4_ntxq_vi;
4691 	iaq->nrxq = t4_nrxq;
4692 	iaq->nrxq_vi = t4_nrxq_vi;
4693 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4694 	if (is_offload(sc) || is_ethoffload(sc)) {
4695 		if (sc->params.tid_qid_sel_mask == 0) {
4696 			iaq->nofldtxq = t4_nofldtxq;
4697 			iaq->nofldtxq_vi = t4_nofldtxq_vi;
4698 		} else {
4699 			iaq->nofldtxq = roundup(t4_nofldtxq, sc->params.ncores);
4700 			iaq->nofldtxq_vi = roundup(t4_nofldtxq_vi,
4701 			    sc->params.ncores);
4702 			if (iaq->nofldtxq != t4_nofldtxq)
4703 				device_printf(sc->dev,
4704 				    "nofldtxq updated (%d -> %d) for correct"
4705 				    " operation with %d firmware cores.\n",
4706 				    t4_nofldtxq, iaq->nofldtxq,
4707 				    sc->params.ncores);
4708 			if (iaq->num_vis > 1 &&
4709 			    iaq->nofldtxq_vi != t4_nofldtxq_vi)
4710 				device_printf(sc->dev,
4711 				    "nofldtxq_vi updated (%d -> %d) for correct"
4712 				    " operation with %d firmware cores.\n",
4713 				    t4_nofldtxq_vi, iaq->nofldtxq_vi,
4714 				    sc->params.ncores);
4715 		}
4716 	}
4717 #endif
4718 #ifdef TCP_OFFLOAD
4719 	if (is_offload(sc)) {
4720 		iaq->nofldrxq = t4_nofldrxq;
4721 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4722 	}
4723 #endif
4724 #ifdef DEV_NETMAP
4725 	if (t4_native_netmap & NN_MAIN_VI) {
4726 		iaq->nnmtxq = t4_nnmtxq;
4727 		iaq->nnmrxq = t4_nnmrxq;
4728 	}
4729 	if (t4_native_netmap & NN_EXTRA_VI) {
4730 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4731 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4732 	}
4733 #endif
4734 
4735 	update_nirq(iaq, nports);
4736 	if (iaq->nirq <= navail &&
4737 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4738 		/*
4739 		 * This is the normal case -- there are enough interrupts for
4740 		 * everything.
4741 		 */
4742 		goto done;
4743 	}
4744 
4745 	/*
4746 	 * If extra VIs have been configured try reducing their count and see if
4747 	 * that works.
4748 	 */
4749 	while (iaq->num_vis > 1) {
4750 		iaq->num_vis--;
4751 		update_nirq(iaq, nports);
4752 		if (iaq->nirq <= navail &&
4753 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4754 			device_printf(sc->dev, "virtual interfaces per port "
4755 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4756 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4757 			    "itype %d, navail %u, nirq %d.\n",
4758 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4759 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4760 			    itype, navail, iaq->nirq);
4761 			goto done;
4762 		}
4763 	}
4764 
4765 	/*
4766 	 * Extra VIs will not be created.  Log a message if they were requested.
4767 	 */
4768 	MPASS(iaq->num_vis == 1);
4769 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4770 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4771 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4772 	if (iaq->num_vis != t4_num_vis) {
4773 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4774 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4775 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4776 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4777 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4778 	}
4779 
4780 	/*
4781 	 * Keep reducing the number of NIC rx queues to the next lower power of
4782 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4783 	 * if that works.
4784 	 */
4785 	do {
4786 		if (iaq->nrxq > 1) {
4787 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4788 			if (iaq->nnmrxq > iaq->nrxq)
4789 				iaq->nnmrxq = iaq->nrxq;
4790 		}
4791 		if (iaq->nofldrxq > 1)
4792 			iaq->nofldrxq >>= 1;
4793 
4794 		old_nirq = iaq->nirq;
4795 		update_nirq(iaq, nports);
4796 		if (iaq->nirq <= navail &&
4797 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4798 			device_printf(sc->dev, "running with reduced number of "
4799 			    "rx queues because of shortage of interrupts.  "
4800 			    "nrxq=%u, nofldrxq=%u.  "
4801 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4802 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4803 			goto done;
4804 		}
4805 	} while (old_nirq != iaq->nirq);
4806 
4807 	/* One interrupt for everything.  Ugh. */
4808 	device_printf(sc->dev, "running with minimal number of queues.  "
4809 	    "itype %d, navail %u.\n", itype, navail);
4810 	iaq->nirq = 1;
4811 	iaq->nrxq = 1;
4812 	iaq->ntxq = 1;
4813 	if (iaq->nofldrxq > 0) {
4814 		iaq->nofldrxq = 1;
4815 		iaq->nofldtxq = 1;
4816 		if (sc->params.tid_qid_sel_mask == 0)
4817 			iaq->nofldtxq = 1;
4818 		else
4819 			iaq->nofldtxq = sc->params.ncores;
4820 	}
4821 	iaq->nnmtxq = 0;
4822 	iaq->nnmrxq = 0;
4823 done:
4824 	MPASS(iaq->num_vis > 0);
4825 	if (iaq->num_vis > 1) {
4826 		MPASS(iaq->nrxq_vi > 0);
4827 		MPASS(iaq->ntxq_vi > 0);
4828 	}
4829 	MPASS(iaq->nirq > 0);
4830 	MPASS(iaq->nrxq > 0);
4831 	MPASS(iaq->ntxq > 0);
4832 	if (itype == INTR_MSI)
4833 		MPASS(powerof2(iaq->nirq));
4834 	if (sc->params.tid_qid_sel_mask != 0)
4835 		MPASS(iaq->nofldtxq % sc->params.ncores == 0);
4836 }
4837 
4838 static int
4839 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4840 {
4841 	int rc, itype, navail, nalloc;
4842 
4843 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4844 
4845 		if ((itype & t4_intr_types) == 0)
4846 			continue;	/* not allowed */
4847 
4848 		if (itype == INTR_MSIX)
4849 			navail = pci_msix_count(sc->dev);
4850 		else if (itype == INTR_MSI)
4851 			navail = pci_msi_count(sc->dev);
4852 		else
4853 			navail = 1;
4854 restart:
4855 		if (navail == 0)
4856 			continue;
4857 
4858 		calculate_iaq(sc, iaq, itype, navail);
4859 		nalloc = iaq->nirq;
4860 		rc = 0;
4861 		if (itype == INTR_MSIX)
4862 			rc = pci_alloc_msix(sc->dev, &nalloc);
4863 		else if (itype == INTR_MSI)
4864 			rc = pci_alloc_msi(sc->dev, &nalloc);
4865 
4866 		if (rc == 0 && nalloc > 0) {
4867 			if (nalloc == iaq->nirq)
4868 				return (0);
4869 
4870 			/*
4871 			 * Didn't get the number requested.  Use whatever number
4872 			 * the kernel is willing to allocate.
4873 			 */
4874 			device_printf(sc->dev, "fewer vectors than requested, "
4875 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4876 			    itype, iaq->nirq, nalloc);
4877 			pci_release_msi(sc->dev);
4878 			navail = nalloc;
4879 			goto restart;
4880 		}
4881 
4882 		device_printf(sc->dev,
4883 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4884 		    itype, rc, iaq->nirq, nalloc);
4885 	}
4886 
4887 	device_printf(sc->dev,
4888 	    "failed to find a usable interrupt type.  "
4889 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4890 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4891 
4892 	return (ENXIO);
4893 }
4894 
4895 #define FW_VERSION(chip) ( \
4896     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4897     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4898     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4899     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4900 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4901 
4902 /* Just enough of fw_hdr to cover all version info. */
4903 struct fw_h {
4904 	__u8	ver;
4905 	__u8	chip;
4906 	__be16	len512;
4907 	__be32	fw_ver;
4908 	__be32	tp_microcode_ver;
4909 	__u8	intfver_nic;
4910 	__u8	intfver_vnic;
4911 	__u8	intfver_ofld;
4912 	__u8	intfver_ri;
4913 	__u8	intfver_iscsipdu;
4914 	__u8	intfver_iscsi;
4915 	__u8	intfver_fcoepdu;
4916 	__u8	intfver_fcoe;
4917 };
4918 /* Spot check a couple of fields. */
4919 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4920 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4921 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4922 
4923 struct fw_info {
4924 	uint8_t chip;
4925 	char *kld_name;
4926 	char *fw_mod_name;
4927 	struct fw_h fw_h;
4928 } fw_info[] = {
4929 	{
4930 		.chip = CHELSIO_T4,
4931 		.kld_name = "t4fw_cfg",
4932 		.fw_mod_name = "t4fw",
4933 		.fw_h = {
4934 			.chip = FW_HDR_CHIP_T4,
4935 			.fw_ver = htobe32(FW_VERSION(T4)),
4936 			.intfver_nic = FW_INTFVER(T4, NIC),
4937 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4938 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4939 			.intfver_ri = FW_INTFVER(T4, RI),
4940 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4941 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4942 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4943 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4944 		},
4945 	}, {
4946 		.chip = CHELSIO_T5,
4947 		.kld_name = "t5fw_cfg",
4948 		.fw_mod_name = "t5fw",
4949 		.fw_h = {
4950 			.chip = FW_HDR_CHIP_T5,
4951 			.fw_ver = htobe32(FW_VERSION(T5)),
4952 			.intfver_nic = FW_INTFVER(T5, NIC),
4953 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4954 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4955 			.intfver_ri = FW_INTFVER(T5, RI),
4956 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4957 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4958 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4959 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4960 		},
4961 	}, {
4962 		.chip = CHELSIO_T6,
4963 		.kld_name = "t6fw_cfg",
4964 		.fw_mod_name = "t6fw",
4965 		.fw_h = {
4966 			.chip = FW_HDR_CHIP_T6,
4967 			.fw_ver = htobe32(FW_VERSION(T6)),
4968 			.intfver_nic = FW_INTFVER(T6, NIC),
4969 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4970 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4971 			.intfver_ri = FW_INTFVER(T6, RI),
4972 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4973 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4974 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4975 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4976 		},
4977 	}, {
4978 		.chip = CHELSIO_T7,
4979 		.kld_name = "t7fw_cfg",
4980 		.fw_mod_name = "t7fw",
4981 		.fw_h = {
4982 			.chip = FW_HDR_CHIP_T7,
4983 			.fw_ver = htobe32(FW_VERSION(T7)),
4984 			.intfver_nic = FW_INTFVER(T7, NIC),
4985 			.intfver_vnic = FW_INTFVER(T7, VNIC),
4986 			.intfver_ofld = FW_INTFVER(T7, OFLD),
4987 			.intfver_ri = FW_INTFVER(T7, RI),
4988 			.intfver_iscsipdu = FW_INTFVER(T7, ISCSIPDU),
4989 			.intfver_iscsi = FW_INTFVER(T7, ISCSI),
4990 			.intfver_fcoepdu = FW_INTFVER(T7, FCOEPDU),
4991 			.intfver_fcoe = FW_INTFVER(T7, FCOE),
4992 		},
4993 	}
4994 };
4995 
4996 static struct fw_info *
4997 find_fw_info(int chip)
4998 {
4999 	int i;
5000 
5001 	for (i = 0; i < nitems(fw_info); i++) {
5002 		if (fw_info[i].chip == chip)
5003 			return (&fw_info[i]);
5004 	}
5005 	return (NULL);
5006 }
5007 
5008 /*
5009  * Is the given firmware API compatible with the one the driver was compiled
5010  * with?
5011  */
5012 static int
5013 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
5014 {
5015 
5016 	/* short circuit if it's the exact same firmware version */
5017 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
5018 		return (1);
5019 
5020 	/*
5021 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
5022 	 * features that are supported in the driver.
5023 	 */
5024 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
5025 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
5026 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
5027 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
5028 		return (1);
5029 #undef SAME_INTF
5030 
5031 	return (0);
5032 }
5033 
5034 static int
5035 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
5036     const struct firmware **fw)
5037 {
5038 	struct fw_info *fw_info;
5039 
5040 	*dcfg = NULL;
5041 	if (fw != NULL)
5042 		*fw = NULL;
5043 
5044 	fw_info = find_fw_info(chip_id(sc));
5045 	if (fw_info == NULL) {
5046 		device_printf(sc->dev,
5047 		    "unable to look up firmware information for chip %d.\n",
5048 		    chip_id(sc));
5049 		return (EINVAL);
5050 	}
5051 
5052 	*dcfg = firmware_get(fw_info->kld_name);
5053 	if (*dcfg != NULL) {
5054 		if (fw != NULL)
5055 			*fw = firmware_get(fw_info->fw_mod_name);
5056 		return (0);
5057 	}
5058 
5059 	return (ENOENT);
5060 }
5061 
5062 static void
5063 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
5064     const struct firmware *fw)
5065 {
5066 
5067 	if (fw != NULL)
5068 		firmware_put(fw, FIRMWARE_UNLOAD);
5069 	if (dcfg != NULL)
5070 		firmware_put(dcfg, FIRMWARE_UNLOAD);
5071 }
5072 
5073 /*
5074  * Return values:
5075  * 0 means no firmware install attempted.
5076  * ERESTART means a firmware install was attempted and was successful.
5077  * +ve errno means a firmware install was attempted but failed.
5078  */
5079 static int
5080 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
5081     const struct fw_h *drv_fw, const char *reason, int *already)
5082 {
5083 	const struct firmware *cfg, *fw;
5084 	const uint32_t c = be32toh(card_fw->fw_ver);
5085 	uint32_t d, k;
5086 	int rc, fw_install;
5087 	struct fw_h bundled_fw;
5088 	bool load_attempted;
5089 
5090 	cfg = fw = NULL;
5091 	load_attempted = false;
5092 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
5093 
5094 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
5095 	if (t4_fw_install < 0) {
5096 		rc = load_fw_module(sc, &cfg, &fw);
5097 		if (rc != 0 || fw == NULL) {
5098 			device_printf(sc->dev,
5099 			    "failed to load firmware module: %d. cfg %p, fw %p;"
5100 			    " will use compiled-in firmware version for"
5101 			    "hw.cxgbe.fw_install checks.\n",
5102 			    rc, cfg, fw);
5103 		} else {
5104 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
5105 		}
5106 		load_attempted = true;
5107 	}
5108 	d = be32toh(bundled_fw.fw_ver);
5109 
5110 	if (reason != NULL)
5111 		goto install;
5112 
5113 	if ((sc->flags & FW_OK) == 0) {
5114 
5115 		if (c == 0xffffffff) {
5116 			reason = "missing";
5117 			goto install;
5118 		}
5119 
5120 		rc = 0;
5121 		goto done;
5122 	}
5123 
5124 	if (!fw_compatible(card_fw, &bundled_fw)) {
5125 		reason = "incompatible or unusable";
5126 		goto install;
5127 	}
5128 
5129 	if (d > c) {
5130 		reason = "older than the version bundled with this driver";
5131 		goto install;
5132 	}
5133 
5134 	if (fw_install == 2 && d != c) {
5135 		reason = "different than the version bundled with this driver";
5136 		goto install;
5137 	}
5138 
5139 	/* No reason to do anything to the firmware already on the card. */
5140 	rc = 0;
5141 	goto done;
5142 
5143 install:
5144 	rc = 0;
5145 	if ((*already)++)
5146 		goto done;
5147 
5148 	if (fw_install == 0) {
5149 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5150 		    "but the driver is prohibited from installing a firmware "
5151 		    "on the card.\n",
5152 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5153 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5154 
5155 		goto done;
5156 	}
5157 
5158 	/*
5159 	 * We'll attempt to install a firmware.  Load the module first (if it
5160 	 * hasn't been loaded already).
5161 	 */
5162 	if (!load_attempted) {
5163 		rc = load_fw_module(sc, &cfg, &fw);
5164 		if (rc != 0 || fw == NULL) {
5165 			device_printf(sc->dev,
5166 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
5167 			    rc, cfg, fw);
5168 			/* carry on */
5169 		}
5170 	}
5171 	if (fw == NULL) {
5172 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5173 		    "but the driver cannot take corrective action because it "
5174 		    "is unable to load the firmware module.\n",
5175 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5176 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5177 		rc = sc->flags & FW_OK ? 0 : ENOENT;
5178 		goto done;
5179 	}
5180 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
5181 	if (k != d) {
5182 		MPASS(t4_fw_install > 0);
5183 		device_printf(sc->dev,
5184 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
5185 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
5186 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
5187 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
5188 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5189 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5190 		rc = sc->flags & FW_OK ? 0 : EINVAL;
5191 		goto done;
5192 	}
5193 
5194 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5195 	    "installing firmware %u.%u.%u.%u on card.\n",
5196 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5197 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
5198 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5199 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5200 
5201 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
5202 	if (rc != 0) {
5203 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
5204 	} else {
5205 		/* Installed successfully, update the cached header too. */
5206 		rc = ERESTART;
5207 		memcpy(card_fw, fw->data, sizeof(*card_fw));
5208 	}
5209 done:
5210 	unload_fw_module(sc, cfg, fw);
5211 
5212 	return (rc);
5213 }
5214 
5215 /*
5216  * Establish contact with the firmware and attempt to become the master driver.
5217  *
5218  * A firmware will be installed to the card if needed (if the driver is allowed
5219  * to do so).
5220  */
5221 static int
5222 contact_firmware(struct adapter *sc)
5223 {
5224 	int rc, already = 0;
5225 	enum dev_state state;
5226 	struct fw_info *fw_info;
5227 	struct fw_hdr *card_fw;		/* fw on the card */
5228 	const struct fw_h *drv_fw;
5229 
5230 	fw_info = find_fw_info(chip_id(sc));
5231 	if (fw_info == NULL) {
5232 		device_printf(sc->dev,
5233 		    "unable to look up firmware information for chip %d.\n",
5234 		    chip_id(sc));
5235 		return (EINVAL);
5236 	}
5237 	drv_fw = &fw_info->fw_h;
5238 
5239 	/* Read the header of the firmware on the card */
5240 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
5241 restart:
5242 	rc = -t4_get_fw_hdr(sc, card_fw);
5243 	if (rc != 0) {
5244 		device_printf(sc->dev,
5245 		    "unable to read firmware header from card's flash: %d\n",
5246 		    rc);
5247 		goto done;
5248 	}
5249 
5250 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
5251 	    &already);
5252 	if (rc == ERESTART)
5253 		goto restart;
5254 	if (rc != 0)
5255 		goto done;
5256 
5257 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
5258 	if (rc < 0 || state == DEV_STATE_ERR) {
5259 		rc = -rc;
5260 		device_printf(sc->dev,
5261 		    "failed to connect to the firmware: %d, %d.  "
5262 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5263 #if 0
5264 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5265 		    "not responding properly to HELLO", &already) == ERESTART)
5266 			goto restart;
5267 #endif
5268 		goto done;
5269 	}
5270 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
5271 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
5272 
5273 	if (rc == sc->pf) {
5274 		sc->flags |= MASTER_PF;
5275 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5276 		    NULL, &already);
5277 		if (rc == ERESTART)
5278 			rc = 0;
5279 		else if (rc != 0)
5280 			goto done;
5281 	} else if (state == DEV_STATE_UNINIT) {
5282 		/*
5283 		 * We didn't get to be the master so we definitely won't be
5284 		 * configuring the chip.  It's a bug if someone else hasn't
5285 		 * configured it already.
5286 		 */
5287 		device_printf(sc->dev, "couldn't be master(%d), "
5288 		    "device not already initialized either(%d).  "
5289 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5290 		rc = EPROTO;
5291 		goto done;
5292 	} else {
5293 		/*
5294 		 * Some other PF is the master and has configured the chip.
5295 		 * This is allowed but untested.
5296 		 */
5297 		device_printf(sc->dev, "PF%d is master, device state %d.  "
5298 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5299 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
5300 		sc->cfcsum = 0;
5301 		rc = 0;
5302 	}
5303 done:
5304 	if (rc != 0 && sc->flags & FW_OK) {
5305 		t4_fw_bye(sc, sc->mbox);
5306 		sc->flags &= ~FW_OK;
5307 	}
5308 	free(card_fw, M_CXGBE);
5309 	return (rc);
5310 }
5311 
5312 static int
5313 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
5314     uint32_t mtype, uint32_t moff, u_int maxlen)
5315 {
5316 	struct fw_info *fw_info;
5317 	const struct firmware *dcfg, *rcfg = NULL;
5318 	const uint32_t *cfdata;
5319 	uint32_t cflen, addr;
5320 	int rc;
5321 
5322 	load_fw_module(sc, &dcfg, NULL);
5323 
5324 	/* Card specific interpretation of "default". */
5325 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5326 		if (pci_get_device(sc->dev) == 0x440a)
5327 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
5328 		if (is_fpga(sc))
5329 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
5330 	}
5331 
5332 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5333 		if (dcfg == NULL) {
5334 			device_printf(sc->dev,
5335 			    "KLD with default config is not available.\n");
5336 			rc = ENOENT;
5337 			goto done;
5338 		}
5339 		cfdata = dcfg->data;
5340 		cflen = dcfg->datasize & ~3;
5341 	} else {
5342 		char s[32];
5343 
5344 		fw_info = find_fw_info(chip_id(sc));
5345 		if (fw_info == NULL) {
5346 			device_printf(sc->dev,
5347 			    "unable to look up firmware information for chip %d.\n",
5348 			    chip_id(sc));
5349 			rc = EINVAL;
5350 			goto done;
5351 		}
5352 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
5353 
5354 		rcfg = firmware_get(s);
5355 		if (rcfg == NULL) {
5356 			device_printf(sc->dev,
5357 			    "unable to load module \"%s\" for configuration "
5358 			    "profile \"%s\".\n", s, cfg_file);
5359 			rc = ENOENT;
5360 			goto done;
5361 		}
5362 		cfdata = rcfg->data;
5363 		cflen = rcfg->datasize & ~3;
5364 	}
5365 
5366 	if (cflen > maxlen) {
5367 		device_printf(sc->dev,
5368 		    "config file too long (%d, max allowed is %d).\n",
5369 		    cflen, maxlen);
5370 		rc = EINVAL;
5371 		goto done;
5372 	}
5373 
5374 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
5375 	if (rc != 0) {
5376 		device_printf(sc->dev,
5377 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
5378 		    __func__, mtype, moff, cflen, rc);
5379 		rc = EINVAL;
5380 		goto done;
5381 	}
5382 	write_via_memwin(sc, 2, addr, cfdata, cflen);
5383 done:
5384 	if (rcfg != NULL)
5385 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5386 	unload_fw_module(sc, dcfg, NULL);
5387 	return (rc);
5388 }
5389 
5390 struct caps_allowed {
5391 	uint16_t nbmcaps;
5392 	uint16_t linkcaps;
5393 	uint16_t switchcaps;
5394 	uint16_t nvmecaps;
5395 	uint16_t niccaps;
5396 	uint16_t toecaps;
5397 	uint16_t rdmacaps;
5398 	uint16_t cryptocaps;
5399 	uint16_t iscsicaps;
5400 	uint16_t fcoecaps;
5401 };
5402 
5403 #define FW_PARAM_DEV(param) \
5404 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5405 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5406 #define FW_PARAM_PFVF(param) \
5407 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5408 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5409 
5410 /*
5411  * Provide a configuration profile to the firmware and have it initialize the
5412  * chip accordingly.  This may involve uploading a configuration file to the
5413  * card.
5414  */
5415 static int
5416 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5417     const struct caps_allowed *caps_allowed)
5418 {
5419 	int rc;
5420 	struct fw_caps_config_cmd caps;
5421 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5422 	unsigned int maxlen = 0;
5423 	const int cfg_addr = t4_flash_cfg_addr(sc, &maxlen);
5424 
5425 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5426 	if (rc != 0) {
5427 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5428 		return (rc);
5429 	}
5430 
5431 	bzero(&caps, sizeof(caps));
5432 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5433 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5434 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5435 		mtype = 0;
5436 		moff = 0;
5437 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5438 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5439 		mtype = FW_MEMTYPE_FLASH;
5440 		moff = cfg_addr;
5441 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5442 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5443 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5444 		    FW_LEN16(caps));
5445 	} else {
5446 		/*
5447 		 * Ask the firmware where it wants us to upload the config file.
5448 		 */
5449 		param = FW_PARAM_DEV(CF);
5450 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5451 		if (rc != 0) {
5452 			/* No support for config file?  Shouldn't happen. */
5453 			device_printf(sc->dev,
5454 			    "failed to query config file location: %d.\n", rc);
5455 			goto done;
5456 		}
5457 		mtype = G_FW_PARAMS_PARAM_Y(val);
5458 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5459 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5460 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5461 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5462 		    FW_LEN16(caps));
5463 
5464 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff, maxlen);
5465 		if (rc != 0) {
5466 			device_printf(sc->dev,
5467 			    "failed to upload config file to card: %d.\n", rc);
5468 			goto done;
5469 		}
5470 	}
5471 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5472 	if (rc != 0) {
5473 		device_printf(sc->dev, "failed to pre-process config file: %d "
5474 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5475 		goto done;
5476 	}
5477 
5478 	finicsum = be32toh(caps.finicsum);
5479 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5480 	if (finicsum != cfcsum) {
5481 		device_printf(sc->dev,
5482 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5483 		    finicsum, cfcsum);
5484 	}
5485 	sc->cfcsum = cfcsum;
5486 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5487 
5488 	/*
5489 	 * Let the firmware know what features will (not) be used so it can tune
5490 	 * things accordingly.
5491 	 */
5492 #define LIMIT_CAPS(x) do { \
5493 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5494 } while (0)
5495 	LIMIT_CAPS(nbm);
5496 	LIMIT_CAPS(link);
5497 	LIMIT_CAPS(switch);
5498 	LIMIT_CAPS(nvme);
5499 	LIMIT_CAPS(nic);
5500 	LIMIT_CAPS(toe);
5501 	LIMIT_CAPS(rdma);
5502 	LIMIT_CAPS(crypto);
5503 	LIMIT_CAPS(iscsi);
5504 	LIMIT_CAPS(fcoe);
5505 #undef LIMIT_CAPS
5506 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5507 		/*
5508 		 * TOE and hashfilters are mutually exclusive.  It is a config
5509 		 * file or firmware bug if both are reported as available.  Try
5510 		 * to cope with the situation in non-debug builds by disabling
5511 		 * TOE.
5512 		 */
5513 		MPASS(caps.toecaps == 0);
5514 
5515 		caps.toecaps = 0;
5516 		caps.rdmacaps = 0;
5517 		caps.iscsicaps = 0;
5518 		caps.nvmecaps = 0;
5519 	}
5520 
5521 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5522 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5523 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5524 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5525 	if (rc != 0) {
5526 		device_printf(sc->dev,
5527 		    "failed to process config file: %d.\n", rc);
5528 		goto done;
5529 	}
5530 
5531 	t4_tweak_chip_settings(sc);
5532 	set_params__pre_init(sc);
5533 
5534 	/* get basic stuff going */
5535 	rc = -t4_fw_initialize(sc, sc->mbox);
5536 	if (rc != 0) {
5537 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5538 		goto done;
5539 	}
5540 done:
5541 	return (rc);
5542 }
5543 
5544 /*
5545  * Partition chip resources for use between various PFs, VFs, etc.
5546  */
5547 static int
5548 partition_resources(struct adapter *sc)
5549 {
5550 	char cfg_file[sizeof(t4_cfg_file)];
5551 	struct caps_allowed caps_allowed;
5552 	int rc;
5553 	bool fallback;
5554 
5555 	/* Only the master driver gets to configure the chip resources. */
5556 	MPASS(sc->flags & MASTER_PF);
5557 
5558 #define COPY_CAPS(x) do { \
5559 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5560 } while (0)
5561 	bzero(&caps_allowed, sizeof(caps_allowed));
5562 	COPY_CAPS(nbm);
5563 	COPY_CAPS(link);
5564 	COPY_CAPS(switch);
5565 	COPY_CAPS(nvme);
5566 	COPY_CAPS(nic);
5567 	COPY_CAPS(toe);
5568 	COPY_CAPS(rdma);
5569 	COPY_CAPS(crypto);
5570 	COPY_CAPS(iscsi);
5571 	COPY_CAPS(fcoe);
5572 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5573 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5574 retry:
5575 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5576 	if (rc != 0 && fallback) {
5577 		dump_devlog(sc);
5578 		device_printf(sc->dev,
5579 		    "failed (%d) to configure card with \"%s\" profile, "
5580 		    "will fall back to a basic configuration and retry.\n",
5581 		    rc, cfg_file);
5582 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5583 		bzero(&caps_allowed, sizeof(caps_allowed));
5584 		COPY_CAPS(switch);
5585 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5586 		fallback = false;
5587 		goto retry;
5588 	}
5589 #undef COPY_CAPS
5590 	return (rc);
5591 }
5592 
5593 /*
5594  * Retrieve parameters that are needed (or nice to have) very early.
5595  */
5596 static int
5597 get_params__pre_init(struct adapter *sc)
5598 {
5599 	int rc;
5600 	uint32_t param[2], val[2];
5601 
5602 	t4_get_version_info(sc);
5603 
5604 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5605 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5606 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5607 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5608 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5609 
5610 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5611 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5612 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5613 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5614 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5615 
5616 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5617 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5618 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5619 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5620 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5621 
5622 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5623 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5624 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5625 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5626 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5627 
5628 	param[0] = FW_PARAM_DEV(PORTVEC);
5629 	param[1] = FW_PARAM_DEV(CCLK);
5630 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5631 	if (rc != 0) {
5632 		device_printf(sc->dev,
5633 		    "failed to query parameters (pre_init): %d.\n", rc);
5634 		return (rc);
5635 	}
5636 
5637 	sc->params.portvec = val[0];
5638 	sc->params.nports = bitcount32(val[0]);
5639 	sc->params.vpd.cclk = val[1];
5640 
5641 	/* Read device log parameters. */
5642 	rc = -t4_init_devlog_ncores_params(sc, 1);
5643 	if (rc == 0)
5644 		fixup_devlog_ncores_params(sc);
5645 	else {
5646 		device_printf(sc->dev,
5647 		    "failed to get devlog parameters: %d.\n", rc);
5648 		rc = 0;	/* devlog isn't critical for device operation */
5649 	}
5650 
5651 	return (rc);
5652 }
5653 
5654 /*
5655  * Any params that need to be set before FW_INITIALIZE.
5656  */
5657 static int
5658 set_params__pre_init(struct adapter *sc)
5659 {
5660 	int rc = 0;
5661 	uint32_t param, val;
5662 
5663 	if (chip_id(sc) >= CHELSIO_T6) {
5664 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5665 		val = 1;
5666 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5667 		/* firmwares < 1.20.1.0 do not have this param. */
5668 		if (rc == FW_EINVAL &&
5669 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5670 			rc = 0;
5671 		}
5672 		if (rc != 0) {
5673 			device_printf(sc->dev,
5674 			    "failed to enable high priority filters :%d.\n",
5675 			    rc);
5676 		}
5677 
5678 		param = FW_PARAM_DEV(PPOD_EDRAM);
5679 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5680 		if (rc == 0 && val == 1) {
5681 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5682 			    &val);
5683 			if (rc != 0) {
5684 				device_printf(sc->dev,
5685 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5686 			}
5687 		}
5688 	}
5689 
5690 	/* Enable opaque VIIDs with firmwares that support it. */
5691 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5692 	val = 1;
5693 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5694 	if (rc == 0 && val == 1)
5695 		sc->params.viid_smt_extn_support = true;
5696 	else
5697 		sc->params.viid_smt_extn_support = false;
5698 
5699 	return (rc);
5700 }
5701 
5702 /*
5703  * Retrieve various parameters that are of interest to the driver.  The device
5704  * has been initialized by the firmware at this point.
5705  */
5706 static int
5707 get_params__post_init(struct adapter *sc)
5708 {
5709 	int rc;
5710 	uint32_t param[7], val[7];
5711 	struct fw_caps_config_cmd caps;
5712 
5713 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5714 	param[1] = FW_PARAM_PFVF(EQ_START);
5715 	param[2] = FW_PARAM_PFVF(FILTER_START);
5716 	param[3] = FW_PARAM_PFVF(FILTER_END);
5717 	param[4] = FW_PARAM_PFVF(L2T_START);
5718 	param[5] = FW_PARAM_PFVF(L2T_END);
5719 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5720 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5721 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5722 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5723 	if (rc != 0) {
5724 		device_printf(sc->dev,
5725 		    "failed to query parameters (post_init): %d.\n", rc);
5726 		return (rc);
5727 	}
5728 
5729 	sc->sge.iq_start = val[0];
5730 	sc->sge.eq_start = val[1];
5731 	if ((int)val[3] > (int)val[2]) {
5732 		sc->tids.ftid_base = val[2];
5733 		sc->tids.ftid_end = val[3];
5734 		sc->tids.nftids = val[3] - val[2] + 1;
5735 	}
5736 	sc->vres.l2t.start = val[4];
5737 	sc->vres.l2t.size = val[5] - val[4] + 1;
5738 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5739 	if (sc->vres.l2t.size > 0)
5740 		MPASS(fls(val[5]) <= S_SYNC_WR);
5741 	sc->params.core_vdd = val[6];
5742 
5743 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5744 	param[1] = FW_PARAM_PFVF(EQ_END);
5745 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5746 	if (rc != 0) {
5747 		device_printf(sc->dev,
5748 		    "failed to query parameters (post_init2): %d.\n", rc);
5749 		return (rc);
5750 	}
5751 	MPASS((int)val[0] >= sc->sge.iq_start);
5752 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5753 	MPASS((int)val[1] >= sc->sge.eq_start);
5754 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5755 
5756 	if (chip_id(sc) >= CHELSIO_T6) {
5757 
5758 		sc->tids.tid_base = t4_read_reg(sc,
5759 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5760 
5761 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5762 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5763 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5764 		if (rc != 0) {
5765 			device_printf(sc->dev,
5766 			   "failed to query hpfilter parameters: %d.\n", rc);
5767 			return (rc);
5768 		}
5769 		if ((int)val[1] > (int)val[0]) {
5770 			sc->tids.hpftid_base = val[0];
5771 			sc->tids.hpftid_end = val[1];
5772 			sc->tids.nhpftids = val[1] - val[0] + 1;
5773 
5774 			/*
5775 			 * These should go off if the layout changes and the
5776 			 * driver needs to catch up.
5777 			 */
5778 			MPASS(sc->tids.hpftid_base == 0);
5779 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5780 		}
5781 
5782 		param[0] = FW_PARAM_PFVF(RAWF_START);
5783 		param[1] = FW_PARAM_PFVF(RAWF_END);
5784 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5785 		if (rc != 0) {
5786 			device_printf(sc->dev,
5787 			   "failed to query rawf parameters: %d.\n", rc);
5788 			return (rc);
5789 		}
5790 		if ((int)val[1] > (int)val[0]) {
5791 			sc->rawf_base = val[0];
5792 			sc->nrawf = val[1] - val[0] + 1;
5793 		}
5794 	}
5795 
5796 	if (sc->params.ncores > 1) {
5797 		param[0] = FW_PARAM_DEV(TID_QID_SEL_MASK);
5798 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5799 		sc->params.tid_qid_sel_mask = rc == 0 ? val[0] : 0;
5800 	}
5801 
5802 	/*
5803 	 * The parameters that follow may not be available on all firmwares.  We
5804 	 * query them individually rather than in a compound query because old
5805 	 * firmwares fail the entire query if an unknown parameter is queried.
5806 	 */
5807 
5808 	/*
5809 	 * MPS buffer group configuration.
5810 	 */
5811 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5812 	val[0] = 0;
5813 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5814 	if (rc == 0)
5815 		sc->params.mps_bg_map = val[0];
5816 	else
5817 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5818 
5819 	param[0] = FW_PARAM_DEV(TPCHMAP);
5820 	val[0] = 0;
5821 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5822 	if (rc == 0)
5823 		sc->params.tp_ch_map = val[0];
5824 	else
5825 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5826 
5827 	param[0] = FW_PARAM_DEV(TX_TPCHMAP);
5828 	val[0] = 0;
5829 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5830 	if (rc == 0)
5831 		sc->params.tx_tp_ch_map = val[0];
5832 	else
5833 		sc->params.tx_tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5834 
5835 	/*
5836 	 * Determine whether the firmware supports the filter2 work request.
5837 	 */
5838 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5839 	val[0] = 0;
5840 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5841 	if (rc == 0)
5842 		sc->params.filter2_wr_support = val[0] != 0;
5843 	else
5844 		sc->params.filter2_wr_support = 0;
5845 
5846 	/*
5847 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5848 	 */
5849 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5850 	val[0] = 0;
5851 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5852 	if (rc == 0)
5853 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5854 	else
5855 		sc->params.ulptx_memwrite_dsgl = false;
5856 
5857 	/* FW_RI_FR_NSMR_TPTE_WR support */
5858 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5859 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5860 	if (rc == 0)
5861 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5862 	else
5863 		sc->params.fr_nsmr_tpte_wr_support = false;
5864 
5865 	/* Support for 512 SGL entries per FR MR. */
5866 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5867 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5868 	if (rc == 0)
5869 		sc->params.dev_512sgl_mr = val[0] != 0;
5870 	else
5871 		sc->params.dev_512sgl_mr = false;
5872 
5873 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5874 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5875 	if (rc == 0)
5876 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5877 	else
5878 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5879 
5880 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5881 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5882 	if (rc == 0) {
5883 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5884 		sc->params.nsched_cls = val[0];
5885 	} else
5886 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5887 
5888 	/* get capabilites */
5889 	bzero(&caps, sizeof(caps));
5890 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5891 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5892 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5893 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5894 	if (rc != 0) {
5895 		device_printf(sc->dev,
5896 		    "failed to get card capabilities: %d.\n", rc);
5897 		return (rc);
5898 	}
5899 
5900 #define READ_CAPS(x) do { \
5901 	sc->x = htobe16(caps.x); \
5902 } while (0)
5903 	READ_CAPS(nbmcaps);
5904 	READ_CAPS(linkcaps);
5905 	READ_CAPS(switchcaps);
5906 	READ_CAPS(nvmecaps);
5907 	READ_CAPS(niccaps);
5908 	READ_CAPS(toecaps);
5909 	READ_CAPS(rdmacaps);
5910 	READ_CAPS(cryptocaps);
5911 	READ_CAPS(iscsicaps);
5912 	READ_CAPS(fcoecaps);
5913 
5914 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5915 		MPASS(chip_id(sc) > CHELSIO_T4);
5916 		MPASS(sc->toecaps == 0);
5917 		sc->toecaps = 0;
5918 
5919 		param[0] = FW_PARAM_DEV(NTID);
5920 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5921 		if (rc != 0) {
5922 			device_printf(sc->dev,
5923 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5924 			return (rc);
5925 		}
5926 		sc->tids.ntids = val[0];
5927 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5928 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5929 			sc->tids.ntids -= sc->tids.nhpftids;
5930 		}
5931 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5932 		sc->params.hash_filter = 1;
5933 	}
5934 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5935 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5936 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5937 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5938 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5939 		if (rc != 0) {
5940 			device_printf(sc->dev,
5941 			    "failed to query NIC parameters: %d.\n", rc);
5942 			return (rc);
5943 		}
5944 		if ((int)val[1] > (int)val[0]) {
5945 			sc->tids.etid_base = val[0];
5946 			sc->tids.etid_end = val[1];
5947 			sc->tids.netids = val[1] - val[0] + 1;
5948 			sc->params.eo_wr_cred = val[2];
5949 			sc->params.ethoffload = 1;
5950 		}
5951 	}
5952 	if (sc->toecaps) {
5953 		/* query offload-related parameters */
5954 		param[0] = FW_PARAM_DEV(NTID);
5955 		param[1] = FW_PARAM_PFVF(SERVER_START);
5956 		param[2] = FW_PARAM_PFVF(SERVER_END);
5957 		param[3] = FW_PARAM_PFVF(TDDP_START);
5958 		param[4] = FW_PARAM_PFVF(TDDP_END);
5959 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5960 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5961 		if (rc != 0) {
5962 			device_printf(sc->dev,
5963 			    "failed to query TOE parameters: %d.\n", rc);
5964 			return (rc);
5965 		}
5966 		sc->tids.ntids = val[0];
5967 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5968 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5969 			sc->tids.ntids -= sc->tids.nhpftids;
5970 		}
5971 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5972 		if ((int)val[2] > (int)val[1]) {
5973 			sc->tids.stid_base = val[1];
5974 			sc->tids.nstids = val[2] - val[1] + 1;
5975 		}
5976 		sc->vres.ddp.start = val[3];
5977 		sc->vres.ddp.size = val[4] - val[3] + 1;
5978 		sc->params.ofldq_wr_cred = val[5];
5979 		sc->params.offload = 1;
5980 	} else {
5981 		/*
5982 		 * The firmware attempts memfree TOE configuration for -SO cards
5983 		 * and will report toecaps=0 if it runs out of resources (this
5984 		 * depends on the config file).  It may not report 0 for other
5985 		 * capabilities dependent on the TOE in this case.  Set them to
5986 		 * 0 here so that the driver doesn't bother tracking resources
5987 		 * that will never be used.
5988 		 */
5989 		sc->iscsicaps = 0;
5990 		sc->nvmecaps = 0;
5991 		sc->rdmacaps = 0;
5992 	}
5993 	if (sc->nvmecaps || sc->rdmacaps) {
5994 		param[0] = FW_PARAM_PFVF(STAG_START);
5995 		param[1] = FW_PARAM_PFVF(STAG_END);
5996 		param[2] = FW_PARAM_PFVF(PBL_START);
5997 		param[3] = FW_PARAM_PFVF(PBL_END);
5998 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5999 		if (rc != 0) {
6000 			device_printf(sc->dev,
6001 			    "failed to query NVMe/RDMA parameters: %d.\n", rc);
6002 			return (rc);
6003 		}
6004 		sc->vres.stag.start = val[0];
6005 		sc->vres.stag.size = val[1] - val[0] + 1;
6006 		sc->vres.pbl.start = val[2];
6007 		sc->vres.pbl.size = val[3] - val[2] + 1;
6008 	}
6009 	if (sc->rdmacaps) {
6010 		param[0] = FW_PARAM_PFVF(RQ_START);
6011 		param[1] = FW_PARAM_PFVF(RQ_END);
6012 		param[2] = FW_PARAM_PFVF(SQRQ_START);
6013 		param[3] = FW_PARAM_PFVF(SQRQ_END);
6014 		param[4] = FW_PARAM_PFVF(CQ_START);
6015 		param[5] = FW_PARAM_PFVF(CQ_END);
6016 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
6017 		if (rc != 0) {
6018 			device_printf(sc->dev,
6019 			    "failed to query RDMA parameters(1): %d.\n", rc);
6020 			return (rc);
6021 		}
6022 		sc->vres.rq.start = val[0];
6023 		sc->vres.rq.size = val[1] - val[0] + 1;
6024 		sc->vres.qp.start = val[2];
6025 		sc->vres.qp.size = val[3] - val[2] + 1;
6026 		sc->vres.cq.start = val[4];
6027 		sc->vres.cq.size = val[5] - val[4] + 1;
6028 
6029 		param[0] = FW_PARAM_PFVF(OCQ_START);
6030 		param[1] = FW_PARAM_PFVF(OCQ_END);
6031 		param[2] = FW_PARAM_PFVF(SRQ_START);
6032 		param[3] = FW_PARAM_PFVF(SRQ_END);
6033 		param[4] = FW_PARAM_DEV(MAXORDIRD_QP);
6034 		param[5] = FW_PARAM_DEV(MAXIRD_ADAPTER);
6035 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
6036 		if (rc != 0) {
6037 			device_printf(sc->dev,
6038 			    "failed to query RDMA parameters(2): %d.\n", rc);
6039 			return (rc);
6040 		}
6041 		sc->vres.ocq.start = val[0];
6042 		sc->vres.ocq.size = val[1] - val[0] + 1;
6043 		sc->vres.srq.start = val[2];
6044 		sc->vres.srq.size = val[3] - val[2] + 1;
6045 		sc->params.max_ordird_qp = val[4];
6046 		sc->params.max_ird_adapter = val[5];
6047 
6048 		param[0] = FW_PARAM_DEV(RDMA_WRITE_WITH_IMM);
6049 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6050 		if (rc == 0 && val[0] != 0)
6051 			sc->params.write_w_imm_support = true;
6052 
6053 		param[0] = FW_PARAM_DEV(RI_WRITE_CMPL_WR);
6054 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6055 		if (rc == 0 && val[0] != 0)
6056 			sc->params.write_cmpl_support = true;
6057 	}
6058 	if (sc->iscsicaps) {
6059 		param[0] = FW_PARAM_PFVF(ISCSI_START);
6060 		param[1] = FW_PARAM_PFVF(ISCSI_END);
6061 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6062 		if (rc != 0) {
6063 			device_printf(sc->dev,
6064 			    "failed to query iSCSI parameters: %d.\n", rc);
6065 			return (rc);
6066 		}
6067 		sc->vres.iscsi.start = val[0];
6068 		sc->vres.iscsi.size = val[1] - val[0] + 1;
6069 	}
6070 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
6071 		param[0] = FW_PARAM_PFVF(TLS_START);
6072 		param[1] = FW_PARAM_PFVF(TLS_END);
6073 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6074 		if (rc != 0) {
6075 			device_printf(sc->dev,
6076 			    "failed to query TLS parameters: %d.\n", rc);
6077 			return (rc);
6078 		}
6079 		sc->vres.key.start = val[0];
6080 		sc->vres.key.size = val[1] - val[0] + 1;
6081 	}
6082 	if (sc->cryptocaps & FW_CAPS_CONFIG_IPSEC_INLINE) {
6083 		param[0] = FW_PARAM_PFVF(NIPSEC_TUNNEL);
6084 		param[1] = FW_PARAM_PFVF(NIPSEC_TRANSPORT);
6085 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6086 		if (rc == 0) {
6087 			sc->params.nipsec_tunnel = val[0];
6088 			sc->params.nipsec_transport = val[1];
6089 		} else {
6090 			CH_ERR(sc, "failed to query IPsec params: %d.\n", rc);
6091 			MPASS(sc->params.nipsec_tunnel == 0);
6092 			MPASS(sc->params.nipsec_transport == 0);
6093 		}
6094 	}
6095 	if (sc->cryptocaps & FW_CAPS_CONFIG_OFLD_OVER_IPSEC_INLINE) {
6096 		param[0] = FW_PARAM_PFVF(OFLD_NIPSEC_TUNNEL);
6097 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6098 		if (rc == 0) {
6099 			sc->params.nofld_ipsec_tunnel = val[0];
6100 		} else {
6101 			CH_ERR(sc, "failed to query TOE IPsec params: %d.\n", rc);
6102 			MPASS(sc->params.nofld_ipsec_tunnel == 0);
6103 		}
6104 	}
6105 	/*
6106 	 * We've got the params we wanted to query directly from the firmware.
6107 	 * Grab some others via other means.
6108 	 */
6109 	t4_init_sge_params(sc);
6110 	t4_init_tp_params(sc);
6111 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
6112 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
6113 
6114 	rc = t4_verify_chip_settings(sc);
6115 	if (rc != 0)
6116 		return (rc);
6117 	t4_init_rx_buf_info(sc);
6118 
6119 	return (rc);
6120 }
6121 
6122 #ifdef KERN_TLS
6123 static void
6124 ktls_tick(void *arg)
6125 {
6126 	struct adapter *sc;
6127 	uint32_t tstamp;
6128 
6129 	sc = arg;
6130 	tstamp = tcp_ts_getticks();
6131 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
6132 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
6133 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
6134 }
6135 
6136 static int
6137 t6_config_kern_tls(struct adapter *sc, bool enable)
6138 {
6139 	int rc;
6140 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6141 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
6142 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
6143 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
6144 
6145 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
6146 	if (rc != 0) {
6147 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
6148 		    enable ?  "enable" : "disable", rc);
6149 		return (rc);
6150 	}
6151 
6152 	if (enable) {
6153 		sc->flags |= KERN_TLS_ON;
6154 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6155 		    C_HARDCLOCK);
6156 	} else {
6157 		sc->flags &= ~KERN_TLS_ON;
6158 		callout_stop(&sc->ktls_tick);
6159 	}
6160 
6161 	return (rc);
6162 }
6163 #endif
6164 
6165 static int
6166 set_params__post_init(struct adapter *sc)
6167 {
6168 	uint32_t mask, param, val;
6169 #ifdef TCP_OFFLOAD
6170 	int i, v, shift;
6171 #endif
6172 
6173 	/* ask for encapsulated CPLs */
6174 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
6175 	val = 1;
6176 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6177 
6178 	/* Enable 32b port caps if the firmware supports it. */
6179 	param = FW_PARAM_PFVF(PORT_CAPS32);
6180 	val = 1;
6181 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
6182 		sc->params.port_caps32 = 1;
6183 
6184 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
6185 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
6186 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
6187 	    V_MASKFILTER(val - 1));
6188 
6189 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
6190 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
6191 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6192 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
6193 	val = 0;
6194 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
6195 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
6196 		    F_ATTACKFILTERENABLE);
6197 		val |= F_DROPERRORATTACK;
6198 	}
6199 	if (t4_drop_ip_fragments != 0) {
6200 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
6201 		    F_FRAGMENTDROP);
6202 		val |= F_DROPERRORFRAG;
6203 	}
6204 	if (t4_drop_pkts_with_l2_errors != 0)
6205 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
6206 	if (t4_drop_pkts_with_l3_errors != 0) {
6207 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
6208 		    F_DROPERRORCSUMIP;
6209 	}
6210 	if (t4_drop_pkts_with_l4_errors != 0) {
6211 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6212 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
6213 	}
6214 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
6215 
6216 #ifdef TCP_OFFLOAD
6217 	/*
6218 	 * Override the TOE timers with user provided tunables.  This is not the
6219 	 * recommended way to change the timers (the firmware config file is) so
6220 	 * these tunables are not documented.
6221 	 *
6222 	 * All the timer tunables are in microseconds.
6223 	 */
6224 	if (t4_toe_keepalive_idle != 0) {
6225 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
6226 		v &= M_KEEPALIVEIDLE;
6227 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
6228 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
6229 	}
6230 	if (t4_toe_keepalive_interval != 0) {
6231 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
6232 		v &= M_KEEPALIVEINTVL;
6233 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
6234 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
6235 	}
6236 	if (t4_toe_keepalive_count != 0) {
6237 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
6238 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6239 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
6240 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
6241 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
6242 	}
6243 	if (t4_toe_rexmt_min != 0) {
6244 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
6245 		v &= M_RXTMIN;
6246 		t4_set_reg_field(sc, A_TP_RXT_MIN,
6247 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
6248 	}
6249 	if (t4_toe_rexmt_max != 0) {
6250 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
6251 		v &= M_RXTMAX;
6252 		t4_set_reg_field(sc, A_TP_RXT_MAX,
6253 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
6254 	}
6255 	if (t4_toe_rexmt_count != 0) {
6256 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
6257 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6258 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
6259 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
6260 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
6261 	}
6262 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
6263 		if (t4_toe_rexmt_backoff[i] != -1) {
6264 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
6265 			shift = (i & 3) << 3;
6266 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
6267 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
6268 		}
6269 	}
6270 #endif
6271 
6272 	/*
6273 	 * Limit TOE connections to 2 reassembly "islands".  This is
6274 	 * required to permit migrating TOE connections to either
6275 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
6276 	 */
6277 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
6278 	    V_PASSMODE(2));
6279 
6280 #ifdef KERN_TLS
6281 	if (is_ktls(sc)) {
6282 		sc->tlst.cbc = t4_tls_cbc;
6283 		sc->tlst.inline_keys = t4_tls_inline_keys;
6284 		if (t4_kern_tls != 0 && is_t6(sc)) {
6285 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
6286 			t6_config_kern_tls(sc, true);
6287 		} else {
6288 			sc->tlst.short_records = t4_tls_short_records;
6289 			sc->tlst.partial_ghash = t4_tls_partial_ghash;
6290 		}
6291 	}
6292 #endif
6293 	return (0);
6294 }
6295 
6296 #undef FW_PARAM_PFVF
6297 #undef FW_PARAM_DEV
6298 
6299 static void
6300 t4_set_desc(struct adapter *sc)
6301 {
6302 	struct adapter_params *p = &sc->params;
6303 
6304 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
6305 }
6306 
6307 static inline void
6308 ifmedia_add4(struct ifmedia *ifm, int m)
6309 {
6310 
6311 	ifmedia_add(ifm, m, 0, NULL);
6312 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
6313 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
6314 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
6315 }
6316 
6317 /*
6318  * This is the selected media, which is not quite the same as the active media.
6319  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
6320  * and active are not the same, and "media: Ethernet selected" otherwise.
6321  */
6322 static void
6323 set_current_media(struct port_info *pi)
6324 {
6325 	struct link_config *lc;
6326 	struct ifmedia *ifm;
6327 	int mword;
6328 	u_int speed;
6329 
6330 	PORT_LOCK_ASSERT_OWNED(pi);
6331 
6332 	/* Leave current media alone if it's already set to IFM_NONE. */
6333 	ifm = &pi->media;
6334 	if (ifm->ifm_cur != NULL &&
6335 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
6336 		return;
6337 
6338 	lc = &pi->link_cfg;
6339 	if (lc->requested_aneg != AUTONEG_DISABLE &&
6340 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
6341 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
6342 		return;
6343 	}
6344 	mword = IFM_ETHER | IFM_FDX;
6345 	if (lc->requested_fc & PAUSE_TX)
6346 		mword |= IFM_ETH_TXPAUSE;
6347 	if (lc->requested_fc & PAUSE_RX)
6348 		mword |= IFM_ETH_RXPAUSE;
6349 	if (lc->requested_speed == 0)
6350 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
6351 	else
6352 		speed = lc->requested_speed;
6353 	mword |= port_mword(pi, speed_to_fwcap(speed));
6354 	ifmedia_set(ifm, mword);
6355 }
6356 
6357 /*
6358  * Returns true if the ifmedia list for the port cannot change.
6359  */
6360 static bool
6361 fixed_ifmedia(struct port_info *pi)
6362 {
6363 
6364 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
6365 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
6366 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
6367 	    pi->port_type == FW_PORT_TYPE_KX4 ||
6368 	    pi->port_type == FW_PORT_TYPE_KX ||
6369 	    pi->port_type == FW_PORT_TYPE_KR ||
6370 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
6371 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
6372 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
6373 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
6374 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
6375 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
6376 }
6377 
6378 static void
6379 build_medialist(struct port_info *pi)
6380 {
6381 	uint32_t ss, speed;
6382 	int unknown, mword, bit;
6383 	struct link_config *lc;
6384 	struct ifmedia *ifm;
6385 
6386 	PORT_LOCK_ASSERT_OWNED(pi);
6387 
6388 	if (pi->flags & FIXED_IFMEDIA)
6389 		return;
6390 
6391 	/*
6392 	 * Rebuild the ifmedia list.
6393 	 */
6394 	ifm = &pi->media;
6395 	ifmedia_removeall(ifm);
6396 	lc = &pi->link_cfg;
6397 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
6398 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
6399 		MPASS(ss != 0);
6400 no_media:
6401 		MPASS(LIST_EMPTY(&ifm->ifm_list));
6402 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
6403 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
6404 		return;
6405 	}
6406 
6407 	unknown = 0;
6408 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
6409 		speed = 1 << bit;
6410 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
6411 		if (ss & speed) {
6412 			mword = port_mword(pi, speed);
6413 			if (mword == IFM_NONE) {
6414 				goto no_media;
6415 			} else if (mword == IFM_UNKNOWN)
6416 				unknown++;
6417 			else
6418 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
6419 		}
6420 	}
6421 	if (unknown > 0) /* Add one unknown for all unknown media types. */
6422 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
6423 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
6424 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
6425 
6426 	set_current_media(pi);
6427 }
6428 
6429 /*
6430  * Initialize the requested fields in the link config based on driver tunables.
6431  */
6432 static void
6433 init_link_config(struct port_info *pi)
6434 {
6435 	struct link_config *lc = &pi->link_cfg;
6436 
6437 	PORT_LOCK_ASSERT_OWNED(pi);
6438 
6439 	lc->requested_caps = 0;
6440 	lc->requested_speed = 0;
6441 
6442 	if (t4_autoneg == 0)
6443 		lc->requested_aneg = AUTONEG_DISABLE;
6444 	else if (t4_autoneg == 1)
6445 		lc->requested_aneg = AUTONEG_ENABLE;
6446 	else
6447 		lc->requested_aneg = AUTONEG_AUTO;
6448 
6449 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6450 	    PAUSE_AUTONEG);
6451 
6452 	if (t4_fec & FEC_AUTO)
6453 		lc->requested_fec = FEC_AUTO;
6454 	else if (t4_fec == 0)
6455 		lc->requested_fec = FEC_NONE;
6456 	else {
6457 		/* -1 is handled by the FEC_AUTO block above and not here. */
6458 		lc->requested_fec = t4_fec &
6459 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6460 		if (lc->requested_fec == 0)
6461 			lc->requested_fec = FEC_AUTO;
6462 	}
6463 	if (t4_force_fec < 0)
6464 		lc->force_fec = -1;
6465 	else if (t4_force_fec > 0)
6466 		lc->force_fec = 1;
6467 	else
6468 		lc->force_fec = 0;
6469 }
6470 
6471 /*
6472  * Makes sure that all requested settings comply with what's supported by the
6473  * port.  Returns the number of settings that were invalid and had to be fixed.
6474  */
6475 static int
6476 fixup_link_config(struct port_info *pi)
6477 {
6478 	int n = 0;
6479 	struct link_config *lc = &pi->link_cfg;
6480 	uint32_t fwspeed;
6481 
6482 	PORT_LOCK_ASSERT_OWNED(pi);
6483 
6484 	/* Speed (when not autonegotiating) */
6485 	if (lc->requested_speed != 0) {
6486 		fwspeed = speed_to_fwcap(lc->requested_speed);
6487 		if ((fwspeed & lc->pcaps) == 0) {
6488 			n++;
6489 			lc->requested_speed = 0;
6490 		}
6491 	}
6492 
6493 	/* Link autonegotiation */
6494 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6495 	    lc->requested_aneg == AUTONEG_DISABLE ||
6496 	    lc->requested_aneg == AUTONEG_AUTO);
6497 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6498 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6499 		n++;
6500 		lc->requested_aneg = AUTONEG_AUTO;
6501 	}
6502 
6503 	/* Flow control */
6504 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6505 	if (lc->requested_fc & PAUSE_TX &&
6506 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6507 		n++;
6508 		lc->requested_fc &= ~PAUSE_TX;
6509 	}
6510 	if (lc->requested_fc & PAUSE_RX &&
6511 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6512 		n++;
6513 		lc->requested_fc &= ~PAUSE_RX;
6514 	}
6515 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6516 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6517 		n++;
6518 		lc->requested_fc |= PAUSE_AUTONEG;
6519 	}
6520 
6521 	/* FEC */
6522 	if ((lc->requested_fec & FEC_RS &&
6523 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6524 	    (lc->requested_fec & FEC_BASER_RS &&
6525 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6526 		n++;
6527 		lc->requested_fec = FEC_AUTO;
6528 	}
6529 
6530 	return (n);
6531 }
6532 
6533 /*
6534  * Apply the requested L1 settings, which are expected to be valid, to the
6535  * hardware.
6536  */
6537 static int
6538 apply_link_config(struct port_info *pi)
6539 {
6540 	struct adapter *sc = pi->adapter;
6541 	struct link_config *lc = &pi->link_cfg;
6542 	int rc;
6543 
6544 #ifdef INVARIANTS
6545 	ASSERT_SYNCHRONIZED_OP(sc);
6546 	PORT_LOCK_ASSERT_OWNED(pi);
6547 
6548 	if (lc->requested_aneg == AUTONEG_ENABLE)
6549 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6550 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6551 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6552 	if (lc->requested_fc & PAUSE_TX)
6553 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6554 	if (lc->requested_fc & PAUSE_RX)
6555 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6556 	if (lc->requested_fec & FEC_RS)
6557 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6558 	if (lc->requested_fec & FEC_BASER_RS)
6559 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6560 #endif
6561 	if (!(sc->flags & IS_VF)) {
6562 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->hw_port, lc);
6563 		if (rc != 0) {
6564 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6565 			return (rc);
6566 		}
6567 	}
6568 
6569 	/*
6570 	 * An L1_CFG will almost always result in a link-change event if the
6571 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6572 	 * the notification is processed.  If the link is down then the actual
6573 	 * settings are meaningless.
6574 	 *
6575 	 * This takes care of the case where a change in the L1 settings may not
6576 	 * result in a notification.
6577 	 */
6578 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6579 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6580 
6581 	return (0);
6582 }
6583 
6584 #define FW_MAC_EXACT_CHUNK	7
6585 struct mcaddr_ctx {
6586 	if_t ifp;
6587 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6588 	uint64_t hash;
6589 	int i;
6590 	int del;
6591 	int rc;
6592 };
6593 
6594 static u_int
6595 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6596 {
6597 	struct mcaddr_ctx *ctx = arg;
6598 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6599 	struct port_info *pi = vi->pi;
6600 	struct adapter *sc = pi->adapter;
6601 
6602 	if (ctx->rc < 0)
6603 		return (0);
6604 
6605 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6606 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6607 	ctx->i++;
6608 
6609 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6610 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6611 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6612 		if (ctx->rc < 0) {
6613 			int j;
6614 
6615 			for (j = 0; j < ctx->i; j++) {
6616 				if_printf(ctx->ifp,
6617 				    "failed to add mc address"
6618 				    " %02x:%02x:%02x:"
6619 				    "%02x:%02x:%02x rc=%d\n",
6620 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6621 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6622 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6623 				    -ctx->rc);
6624 			}
6625 			return (0);
6626 		}
6627 		ctx->del = 0;
6628 		ctx->i = 0;
6629 	}
6630 
6631 	return (1);
6632 }
6633 
6634 /*
6635  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6636  * indicates which parameters should be programmed (the rest are left alone).
6637  */
6638 int
6639 update_mac_settings(if_t ifp, int flags)
6640 {
6641 	int rc = 0;
6642 	struct vi_info *vi = if_getsoftc(ifp);
6643 	struct port_info *pi = vi->pi;
6644 	struct adapter *sc = pi->adapter;
6645 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6646 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6647 
6648 	ASSERT_SYNCHRONIZED_OP(sc);
6649 	KASSERT(flags, ("%s: not told what to update.", __func__));
6650 
6651 	if (flags & XGMAC_MTU)
6652 		mtu = if_getmtu(ifp);
6653 
6654 	if (flags & XGMAC_PROMISC)
6655 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6656 
6657 	if (flags & XGMAC_ALLMULTI)
6658 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6659 
6660 	if (flags & XGMAC_VLANEX)
6661 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6662 
6663 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6664 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6665 		    allmulti, 1, vlanex, false);
6666 		if (rc) {
6667 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6668 			    rc);
6669 			return (rc);
6670 		}
6671 	}
6672 
6673 	if (flags & XGMAC_UCADDR) {
6674 		uint8_t ucaddr[ETHER_ADDR_LEN];
6675 
6676 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6677 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6678 		    ucaddr, true, &vi->smt_idx);
6679 		if (rc < 0) {
6680 			rc = -rc;
6681 			if_printf(ifp, "change_mac failed: %d\n", rc);
6682 			return (rc);
6683 		} else {
6684 			vi->xact_addr_filt = rc;
6685 			rc = 0;
6686 		}
6687 	}
6688 
6689 	if (flags & XGMAC_MCADDRS) {
6690 		struct epoch_tracker et;
6691 		struct mcaddr_ctx ctx;
6692 		int j;
6693 
6694 		ctx.ifp = ifp;
6695 		ctx.hash = 0;
6696 		ctx.i = 0;
6697 		ctx.del = 1;
6698 		ctx.rc = 0;
6699 		/*
6700 		 * Unlike other drivers, we accumulate list of pointers into
6701 		 * interface address lists and we need to keep it safe even
6702 		 * after if_foreach_llmaddr() returns, thus we must enter the
6703 		 * network epoch.
6704 		 */
6705 		NET_EPOCH_ENTER(et);
6706 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6707 		if (ctx.rc < 0) {
6708 			NET_EPOCH_EXIT(et);
6709 			rc = -ctx.rc;
6710 			return (rc);
6711 		}
6712 		if (ctx.i > 0) {
6713 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6714 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6715 			NET_EPOCH_EXIT(et);
6716 			if (rc < 0) {
6717 				rc = -rc;
6718 				for (j = 0; j < ctx.i; j++) {
6719 					if_printf(ifp,
6720 					    "failed to add mcast address"
6721 					    " %02x:%02x:%02x:"
6722 					    "%02x:%02x:%02x rc=%d\n",
6723 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6724 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6725 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6726 					    rc);
6727 				}
6728 				return (rc);
6729 			}
6730 			ctx.del = 0;
6731 		} else
6732 			NET_EPOCH_EXIT(et);
6733 
6734 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6735 		if (rc != 0)
6736 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6737 			    rc);
6738 		if (ctx.del == 0) {
6739 			/* We clobbered the VXLAN entry if there was one. */
6740 			pi->vxlan_tcam_entry = false;
6741 		}
6742 	}
6743 
6744 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6745 	    pi->vxlan_tcam_entry == false) {
6746 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6747 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6748 		    true);
6749 		if (rc < 0) {
6750 			rc = -rc;
6751 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6752 			    rc);
6753 		} else {
6754 			MPASS(rc == sc->rawf_base + pi->port_id);
6755 			rc = 0;
6756 			pi->vxlan_tcam_entry = true;
6757 		}
6758 	}
6759 
6760 	return (rc);
6761 }
6762 
6763 /*
6764  * {begin|end}_synchronized_op must be called from the same thread.
6765  */
6766 int
6767 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6768     char *wmesg)
6769 {
6770 	int rc;
6771 
6772 #ifdef WITNESS
6773 	/* the caller thinks it's ok to sleep, but is it really? */
6774 	if (flags & SLEEP_OK)
6775 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
6776 #endif
6777 	ADAPTER_LOCK(sc);
6778 	for (;;) {
6779 
6780 		if (vi && IS_DETACHING(vi)) {
6781 			rc = ENXIO;
6782 			goto done;
6783 		}
6784 
6785 		if (!IS_BUSY(sc)) {
6786 			rc = 0;
6787 			break;
6788 		}
6789 
6790 		if (!(flags & SLEEP_OK)) {
6791 			rc = EBUSY;
6792 			goto done;
6793 		}
6794 
6795 		if (mtx_sleep(&sc->flags, &sc->sc_lock,
6796 		    flags & INTR_OK ? PCATCH : 0, wmesg, 0)) {
6797 			rc = EINTR;
6798 			goto done;
6799 		}
6800 	}
6801 
6802 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6803 	SET_BUSY(sc);
6804 #ifdef INVARIANTS
6805 	sc->last_op = wmesg;
6806 	sc->last_op_thr = curthread;
6807 	sc->last_op_flags = flags;
6808 #endif
6809 
6810 done:
6811 	if (!(flags & HOLD_LOCK) || rc)
6812 		ADAPTER_UNLOCK(sc);
6813 
6814 	return (rc);
6815 }
6816 
6817 /*
6818  * Tell if_ioctl and if_init that the VI is going away.  This is
6819  * special variant of begin_synchronized_op and must be paired with a
6820  * call to end_vi_detach.
6821  */
6822 void
6823 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6824 {
6825 	ADAPTER_LOCK(sc);
6826 	SET_DETACHING(vi);
6827 	wakeup(&sc->flags);
6828 	while (IS_BUSY(sc))
6829 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6830 	SET_BUSY(sc);
6831 #ifdef INVARIANTS
6832 	sc->last_op = "t4detach";
6833 	sc->last_op_thr = curthread;
6834 	sc->last_op_flags = 0;
6835 #endif
6836 	ADAPTER_UNLOCK(sc);
6837 }
6838 
6839 void
6840 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6841 {
6842 	ADAPTER_LOCK(sc);
6843 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6844 	CLR_BUSY(sc);
6845 	CLR_DETACHING(vi);
6846 	wakeup(&sc->flags);
6847 	ADAPTER_UNLOCK(sc);
6848 }
6849 
6850 /*
6851  * {begin|end}_synchronized_op must be called from the same thread.
6852  */
6853 void
6854 end_synchronized_op(struct adapter *sc, int flags)
6855 {
6856 
6857 	if (flags & LOCK_HELD)
6858 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6859 	else
6860 		ADAPTER_LOCK(sc);
6861 
6862 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6863 	CLR_BUSY(sc);
6864 	wakeup(&sc->flags);
6865 	ADAPTER_UNLOCK(sc);
6866 }
6867 
6868 static int
6869 cxgbe_init_synchronized(struct vi_info *vi)
6870 {
6871 	struct port_info *pi = vi->pi;
6872 	struct adapter *sc = pi->adapter;
6873 	if_t ifp = vi->ifp;
6874 	int rc = 0, i;
6875 	struct sge_txq *txq;
6876 
6877 	ASSERT_SYNCHRONIZED_OP(sc);
6878 
6879 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6880 		return (0);	/* already running */
6881 
6882 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6883 		return (rc);	/* error message displayed already */
6884 
6885 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6886 		return (rc); /* error message displayed already */
6887 
6888 	rc = update_mac_settings(ifp, XGMAC_ALL);
6889 	if (rc)
6890 		goto done;	/* error message displayed already */
6891 
6892 	PORT_LOCK(pi);
6893 	if (pi->up_vis == 0) {
6894 		t4_update_port_info(pi);
6895 		fixup_link_config(pi);
6896 		build_medialist(pi);
6897 		apply_link_config(pi);
6898 	}
6899 
6900 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6901 	if (rc != 0) {
6902 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6903 		PORT_UNLOCK(pi);
6904 		goto done;
6905 	}
6906 
6907 	/*
6908 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6909 	 * if this changes.
6910 	 */
6911 
6912 	for_each_txq(vi, i, txq) {
6913 		TXQ_LOCK(txq);
6914 		txq->eq.flags |= EQ_ENABLED;
6915 		TXQ_UNLOCK(txq);
6916 	}
6917 
6918 	/*
6919 	 * The first iq of the first port to come up is used for tracing.
6920 	 */
6921 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6922 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6923 		t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
6924 		pi->flags |= HAS_TRACEQ;
6925 	}
6926 
6927 	/* all ok */
6928 	pi->up_vis++;
6929 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6930 	if (pi->link_cfg.link_ok)
6931 		t4_os_link_changed(pi);
6932 	PORT_UNLOCK(pi);
6933 
6934 	mtx_lock(&vi->tick_mtx);
6935 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6936 		callout_reset(&vi->tick, hz, vi_tick, vi);
6937 	else
6938 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6939 	mtx_unlock(&vi->tick_mtx);
6940 done:
6941 	if (rc != 0)
6942 		cxgbe_uninit_synchronized(vi);
6943 
6944 	return (rc);
6945 }
6946 
6947 /*
6948  * Idempotent.
6949  */
6950 static int
6951 cxgbe_uninit_synchronized(struct vi_info *vi)
6952 {
6953 	struct port_info *pi = vi->pi;
6954 	struct adapter *sc = pi->adapter;
6955 	if_t ifp = vi->ifp;
6956 	int rc, i;
6957 	struct sge_txq *txq;
6958 
6959 	ASSERT_SYNCHRONIZED_OP(sc);
6960 
6961 	if (!(vi->flags & VI_INIT_DONE)) {
6962 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6963 			KASSERT(0, ("uninited VI is running"));
6964 			if_printf(ifp, "uninited VI with running ifnet.  "
6965 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6966 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6967 			    if_getdrvflags(ifp));
6968 		}
6969 		return (0);
6970 	}
6971 
6972 	/*
6973 	 * Disable the VI so that all its data in either direction is discarded
6974 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6975 	 * tick) intact as the TP can deliver negative advice or data that it's
6976 	 * holding in its RAM (for an offloaded connection) even after the VI is
6977 	 * disabled.
6978 	 */
6979 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6980 	if (rc) {
6981 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6982 		return (rc);
6983 	}
6984 
6985 	for_each_txq(vi, i, txq) {
6986 		TXQ_LOCK(txq);
6987 		txq->eq.flags &= ~EQ_ENABLED;
6988 		TXQ_UNLOCK(txq);
6989 	}
6990 
6991 	mtx_lock(&vi->tick_mtx);
6992 	callout_stop(&vi->tick);
6993 	mtx_unlock(&vi->tick_mtx);
6994 
6995 	PORT_LOCK(pi);
6996 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6997 		PORT_UNLOCK(pi);
6998 		return (0);
6999 	}
7000 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
7001 	pi->up_vis--;
7002 	if (pi->up_vis > 0) {
7003 		PORT_UNLOCK(pi);
7004 		return (0);
7005 	}
7006 
7007 	pi->link_cfg.link_ok = false;
7008 	pi->link_cfg.speed = 0;
7009 	pi->link_cfg.link_down_rc = 255;
7010 	t4_os_link_changed(pi);
7011 	PORT_UNLOCK(pi);
7012 
7013 	return (0);
7014 }
7015 
7016 /*
7017  * It is ok for this function to fail midway and return right away.  t4_detach
7018  * will walk the entire sc->irq list and clean up whatever is valid.
7019  */
7020 int
7021 t4_setup_intr_handlers(struct adapter *sc)
7022 {
7023 	int rc, rid, p, q, v;
7024 	char s[8];
7025 	struct irq *irq;
7026 	struct port_info *pi;
7027 	struct vi_info *vi;
7028 	struct sge *sge = &sc->sge;
7029 	struct sge_rxq *rxq;
7030 #ifdef TCP_OFFLOAD
7031 	struct sge_ofld_rxq *ofld_rxq;
7032 #endif
7033 #ifdef DEV_NETMAP
7034 	struct sge_nm_rxq *nm_rxq;
7035 #endif
7036 #ifdef RSS
7037 	int nbuckets = rss_getnumbuckets();
7038 #endif
7039 
7040 	/*
7041 	 * Setup interrupts.
7042 	 */
7043 	irq = &sc->irq[0];
7044 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
7045 	if (forwarding_intr_to_fwq(sc))
7046 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
7047 
7048 	/* Multiple interrupts. */
7049 	if (sc->flags & IS_VF)
7050 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
7051 		    ("%s: too few intr.", __func__));
7052 	else
7053 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
7054 		    ("%s: too few intr.", __func__));
7055 
7056 	/* The first one is always error intr on PFs */
7057 	if (!(sc->flags & IS_VF)) {
7058 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
7059 		if (rc != 0)
7060 			return (rc);
7061 		irq++;
7062 		rid++;
7063 	}
7064 
7065 	/* The second one is always the firmware event queue (first on VFs) */
7066 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
7067 	if (rc != 0)
7068 		return (rc);
7069 	irq++;
7070 	rid++;
7071 
7072 	for_each_port(sc, p) {
7073 		pi = sc->port[p];
7074 		for_each_vi(pi, v, vi) {
7075 			vi->first_intr = rid - 1;
7076 
7077 			if (vi->nnmrxq > 0) {
7078 				int n = max(vi->nrxq, vi->nnmrxq);
7079 
7080 				rxq = &sge->rxq[vi->first_rxq];
7081 #ifdef DEV_NETMAP
7082 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
7083 #endif
7084 				for (q = 0; q < n; q++) {
7085 					snprintf(s, sizeof(s), "%x%c%x", p,
7086 					    'a' + v, q);
7087 					if (q < vi->nrxq)
7088 						irq->rxq = rxq++;
7089 #ifdef DEV_NETMAP
7090 					if (q < vi->nnmrxq)
7091 						irq->nm_rxq = nm_rxq++;
7092 
7093 					if (irq->nm_rxq != NULL &&
7094 					    irq->rxq == NULL) {
7095 						/* Netmap rx only */
7096 						rc = t4_alloc_irq(sc, irq, rid,
7097 						    t4_nm_intr, irq->nm_rxq, s);
7098 					}
7099 					if (irq->nm_rxq != NULL &&
7100 					    irq->rxq != NULL) {
7101 						/* NIC and Netmap rx */
7102 						rc = t4_alloc_irq(sc, irq, rid,
7103 						    t4_vi_intr, irq, s);
7104 					}
7105 #endif
7106 					if (irq->rxq != NULL &&
7107 					    irq->nm_rxq == NULL) {
7108 						/* NIC rx only */
7109 						rc = t4_alloc_irq(sc, irq, rid,
7110 						    t4_intr, irq->rxq, s);
7111 					}
7112 					if (rc != 0)
7113 						return (rc);
7114 #ifdef RSS
7115 					if (q < vi->nrxq) {
7116 						bus_bind_intr(sc->dev, irq->res,
7117 						    rss_getcpu(q % nbuckets));
7118 					}
7119 #endif
7120 					irq++;
7121 					rid++;
7122 					vi->nintr++;
7123 				}
7124 			} else {
7125 				for_each_rxq(vi, q, rxq) {
7126 					snprintf(s, sizeof(s), "%x%c%x", p,
7127 					    'a' + v, q);
7128 					rc = t4_alloc_irq(sc, irq, rid,
7129 					    t4_intr, rxq, s);
7130 					if (rc != 0)
7131 						return (rc);
7132 #ifdef RSS
7133 					bus_bind_intr(sc->dev, irq->res,
7134 					    rss_getcpu(q % nbuckets));
7135 #endif
7136 					irq++;
7137 					rid++;
7138 					vi->nintr++;
7139 				}
7140 			}
7141 #ifdef TCP_OFFLOAD
7142 			for_each_ofld_rxq(vi, q, ofld_rxq) {
7143 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
7144 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
7145 				    ofld_rxq, s);
7146 				if (rc != 0)
7147 					return (rc);
7148 				irq++;
7149 				rid++;
7150 				vi->nintr++;
7151 			}
7152 #endif
7153 		}
7154 	}
7155 	MPASS(irq == &sc->irq[sc->intr_count]);
7156 
7157 	return (0);
7158 }
7159 
7160 static void
7161 write_global_rss_key(struct adapter *sc)
7162 {
7163 	int i;
7164 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7165 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7166 
7167 	CTASSERT(RSS_KEYSIZE == 40);
7168 
7169 	rss_getkey((void *)&raw_rss_key[0]);
7170 	for (i = 0; i < nitems(rss_key); i++) {
7171 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
7172 	}
7173 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
7174 }
7175 
7176 /*
7177  * Idempotent.
7178  */
7179 static int
7180 adapter_full_init(struct adapter *sc)
7181 {
7182 	int rc, i;
7183 
7184 	ASSERT_SYNCHRONIZED_OP(sc);
7185 
7186 	/*
7187 	 * queues that belong to the adapter (not any particular port).
7188 	 */
7189 	rc = t4_setup_adapter_queues(sc);
7190 	if (rc != 0)
7191 		return (rc);
7192 
7193 	MPASS(sc->params.nports <= nitems(sc->tq));
7194 	for (i = 0; i < sc->params.nports; i++) {
7195 		if (sc->tq[i] != NULL)
7196 			continue;
7197 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
7198 		    taskqueue_thread_enqueue, &sc->tq[i]);
7199 		if (sc->tq[i] == NULL) {
7200 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
7201 			return (ENOMEM);
7202 		}
7203 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
7204 		    device_get_nameunit(sc->dev), i);
7205 	}
7206 
7207 	if (!(sc->flags & IS_VF)) {
7208 		write_global_rss_key(sc);
7209 		t4_intr_enable(sc);
7210 	}
7211 	return (0);
7212 }
7213 
7214 int
7215 adapter_init(struct adapter *sc)
7216 {
7217 	int rc;
7218 
7219 	ASSERT_SYNCHRONIZED_OP(sc);
7220 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
7221 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
7222 	    ("%s: FULL_INIT_DONE already", __func__));
7223 
7224 	rc = adapter_full_init(sc);
7225 	if (rc != 0)
7226 		adapter_full_uninit(sc);
7227 	else
7228 		sc->flags |= FULL_INIT_DONE;
7229 
7230 	return (rc);
7231 }
7232 
7233 /*
7234  * Idempotent.
7235  */
7236 static void
7237 adapter_full_uninit(struct adapter *sc)
7238 {
7239 	int i;
7240 
7241 	t4_teardown_adapter_queues(sc);
7242 
7243 	for (i = 0; i < nitems(sc->tq); i++) {
7244 		if (sc->tq[i] == NULL)
7245 			continue;
7246 		taskqueue_free(sc->tq[i]);
7247 		sc->tq[i] = NULL;
7248 	}
7249 
7250 	sc->flags &= ~FULL_INIT_DONE;
7251 }
7252 
7253 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
7254     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
7255     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
7256     RSS_HASHTYPE_RSS_UDP_IPV6)
7257 
7258 /* Translates kernel hash types to hardware. */
7259 static int
7260 hashconfig_to_hashen(int hashconfig)
7261 {
7262 	int hashen = 0;
7263 
7264 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
7265 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
7266 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
7267 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
7268 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
7269 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7270 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7271 	}
7272 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
7273 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7274 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7275 	}
7276 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
7277 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7278 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
7279 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7280 
7281 	return (hashen);
7282 }
7283 
7284 /* Translates hardware hash types to kernel. */
7285 static int
7286 hashen_to_hashconfig(int hashen)
7287 {
7288 	int hashconfig = 0;
7289 
7290 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
7291 		/*
7292 		 * If UDP hashing was enabled it must have been enabled for
7293 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
7294 		 * enabling any 4-tuple hash is nonsense configuration.
7295 		 */
7296 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7297 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
7298 
7299 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7300 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
7301 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7302 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
7303 	}
7304 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7305 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
7306 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7307 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
7308 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
7309 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
7310 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
7311 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
7312 
7313 	return (hashconfig);
7314 }
7315 
7316 /*
7317  * Idempotent.
7318  */
7319 static int
7320 vi_full_init(struct vi_info *vi)
7321 {
7322 	struct adapter *sc = vi->adapter;
7323 	struct sge_rxq *rxq;
7324 	int rc, i, j, extra;
7325 	int hashconfig = rss_gethashconfig();
7326 #ifdef RSS
7327 	int nbuckets = rss_getnumbuckets();
7328 #endif
7329 
7330 	ASSERT_SYNCHRONIZED_OP(sc);
7331 
7332 	/*
7333 	 * Allocate tx/rx/fl queues for this VI.
7334 	 */
7335 	rc = t4_setup_vi_queues(vi);
7336 	if (rc != 0)
7337 		return (rc);
7338 
7339 	/*
7340 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
7341 	 */
7342 	if (vi->nrxq > vi->rss_size) {
7343 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
7344 		    "some queues will never receive traffic.\n", vi->nrxq,
7345 		    vi->rss_size);
7346 	} else if (vi->rss_size % vi->nrxq) {
7347 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
7348 		    "expect uneven traffic distribution.\n", vi->nrxq,
7349 		    vi->rss_size);
7350 	}
7351 #ifdef RSS
7352 	if (vi->nrxq != nbuckets) {
7353 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
7354 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
7355 	}
7356 #endif
7357 	if (vi->rss == NULL)
7358 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
7359 		    M_ZERO | M_WAITOK);
7360 	for (i = 0; i < vi->rss_size;) {
7361 #ifdef RSS
7362 		j = rss_get_indirection_to_bucket(i);
7363 		j %= vi->nrxq;
7364 		rxq = &sc->sge.rxq[vi->first_rxq + j];
7365 		vi->rss[i++] = rxq->iq.abs_id;
7366 #else
7367 		for_each_rxq(vi, j, rxq) {
7368 			vi->rss[i++] = rxq->iq.abs_id;
7369 			if (i == vi->rss_size)
7370 				break;
7371 		}
7372 #endif
7373 	}
7374 
7375 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
7376 	    vi->rss, vi->rss_size);
7377 	if (rc != 0) {
7378 		CH_ERR(vi, "rss_config failed: %d\n", rc);
7379 		return (rc);
7380 	}
7381 
7382 	vi->hashen = hashconfig_to_hashen(hashconfig);
7383 
7384 	/*
7385 	 * We may have had to enable some hashes even though the global config
7386 	 * wants them disabled.  This is a potential problem that must be
7387 	 * reported to the user.
7388 	 */
7389 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
7390 
7391 	/*
7392 	 * If we consider only the supported hash types, then the enabled hashes
7393 	 * are a superset of the requested hashes.  In other words, there cannot
7394 	 * be any supported hash that was requested but not enabled, but there
7395 	 * can be hashes that were not requested but had to be enabled.
7396 	 */
7397 	extra &= SUPPORTED_RSS_HASHTYPES;
7398 	MPASS((extra & hashconfig) == 0);
7399 
7400 	if (extra) {
7401 		CH_ALERT(vi,
7402 		    "global RSS config (0x%x) cannot be accommodated.\n",
7403 		    hashconfig);
7404 	}
7405 	if (extra & RSS_HASHTYPE_RSS_IPV4)
7406 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
7407 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
7408 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
7409 	if (extra & RSS_HASHTYPE_RSS_IPV6)
7410 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
7411 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
7412 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
7413 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
7414 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
7415 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
7416 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
7417 
7418 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
7419 	    0, 0);
7420 	if (rc != 0) {
7421 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
7422 		return (rc);
7423 	}
7424 
7425 	return (0);
7426 }
7427 
7428 int
7429 vi_init(struct vi_info *vi)
7430 {
7431 	int rc;
7432 
7433 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7434 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7435 	    ("%s: VI_INIT_DONE already", __func__));
7436 
7437 	rc = vi_full_init(vi);
7438 	if (rc != 0)
7439 		vi_full_uninit(vi);
7440 	else
7441 		vi->flags |= VI_INIT_DONE;
7442 
7443 	return (rc);
7444 }
7445 
7446 /*
7447  * Idempotent.
7448  */
7449 static void
7450 vi_full_uninit(struct vi_info *vi)
7451 {
7452 
7453 	if (vi->flags & VI_INIT_DONE) {
7454 		quiesce_vi(vi);
7455 		free(vi->rss, M_CXGBE);
7456 		free(vi->nm_rss, M_CXGBE);
7457 	}
7458 
7459 	t4_teardown_vi_queues(vi);
7460 	vi->flags &= ~VI_INIT_DONE;
7461 }
7462 
7463 static void
7464 quiesce_txq(struct sge_txq *txq)
7465 {
7466 	struct sge_eq *eq = &txq->eq;
7467 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7468 
7469 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7470 	MPASS(!(eq->flags & EQ_ENABLED));
7471 
7472 	/* Wait for the mp_ring to empty. */
7473 	while (!mp_ring_is_idle(txq->r)) {
7474 		mp_ring_check_drainage(txq->r, 4096);
7475 		pause("rquiesce", 1);
7476 	}
7477 	MPASS(txq->txp.npkt == 0);
7478 
7479 	if (eq->flags & EQ_HW_ALLOCATED) {
7480 		/*
7481 		 * Hardware is alive and working normally.  Wait for it to
7482 		 * finish and then wait for the driver to catch up and reclaim
7483 		 * all descriptors.
7484 		 */
7485 		while (spg->cidx != htobe16(eq->pidx))
7486 			pause("equiesce", 1);
7487 		while (eq->cidx != eq->pidx)
7488 			pause("dquiesce", 1);
7489 	} else {
7490 		/*
7491 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7492 		 * descriptors directly.
7493 		 */
7494 		TXQ_LOCK(txq);
7495 		while (eq->cidx != eq->pidx) {
7496 			struct mbuf *m, *nextpkt;
7497 			struct tx_sdesc *txsd;
7498 
7499 			txsd = &txq->sdesc[eq->cidx];
7500 			for (m = txsd->m; m != NULL; m = nextpkt) {
7501 				nextpkt = m->m_nextpkt;
7502 				m->m_nextpkt = NULL;
7503 				m_freem(m);
7504 			}
7505 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7506 		}
7507 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7508 		TXQ_UNLOCK(txq);
7509 	}
7510 }
7511 
7512 static void
7513 quiesce_wrq(struct sge_wrq *wrq)
7514 {
7515 	struct wrqe *wr;
7516 
7517 	TXQ_LOCK(wrq);
7518 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7519 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7520 #ifdef INVARIANTS
7521 		wrq->nwr_pending--;
7522 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7523 #endif
7524 		free(wr, M_CXGBE);
7525 	}
7526 	MPASS(wrq->nwr_pending == 0);
7527 	MPASS(wrq->ndesc_needed == 0);
7528 	wrq->nwr_pending = 0;
7529 	wrq->ndesc_needed = 0;
7530 	TXQ_UNLOCK(wrq);
7531 }
7532 
7533 static void
7534 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7535 {
7536 	/* Synchronize with the interrupt handler */
7537 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7538 		pause("iqfree", 1);
7539 
7540 	if (fl != NULL) {
7541 		MPASS(iq->flags & IQ_HAS_FL);
7542 
7543 		mtx_lock(&sc->sfl_lock);
7544 		FL_LOCK(fl);
7545 		fl->flags |= FL_DOOMED;
7546 		FL_UNLOCK(fl);
7547 		callout_stop(&sc->sfl_callout);
7548 		mtx_unlock(&sc->sfl_lock);
7549 
7550 		KASSERT((fl->flags & FL_STARVING) == 0,
7551 		    ("%s: still starving", __func__));
7552 
7553 		/* Release all buffers if hardware is no longer available. */
7554 		if (!(iq->flags & IQ_HW_ALLOCATED))
7555 			free_fl_buffers(sc, fl);
7556 	}
7557 }
7558 
7559 /*
7560  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7561  * that no new work is being enqueued by the hardware or the driver.  That part
7562  * should be arranged before calling this function.
7563  */
7564 static void
7565 quiesce_vi(struct vi_info *vi)
7566 {
7567 	int i;
7568 	struct adapter *sc = vi->adapter;
7569 	struct sge_rxq *rxq;
7570 	struct sge_txq *txq;
7571 #ifdef TCP_OFFLOAD
7572 	struct sge_ofld_rxq *ofld_rxq;
7573 #endif
7574 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7575 	struct sge_ofld_txq *ofld_txq;
7576 #endif
7577 
7578 	if (!(vi->flags & VI_INIT_DONE))
7579 		return;
7580 
7581 	for_each_txq(vi, i, txq) {
7582 		quiesce_txq(txq);
7583 	}
7584 
7585 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7586 	for_each_ofld_txq(vi, i, ofld_txq) {
7587 		quiesce_wrq(&ofld_txq->wrq);
7588 	}
7589 #endif
7590 
7591 	for_each_rxq(vi, i, rxq) {
7592 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7593 	}
7594 
7595 #ifdef TCP_OFFLOAD
7596 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7597 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7598 	}
7599 #endif
7600 }
7601 
7602 static int
7603 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7604     driver_intr_t *handler, void *arg, char *name)
7605 {
7606 	int rc;
7607 
7608 	irq->rid = rid;
7609 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7610 	    RF_SHAREABLE | RF_ACTIVE);
7611 	if (irq->res == NULL) {
7612 		device_printf(sc->dev,
7613 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7614 		return (ENOMEM);
7615 	}
7616 
7617 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7618 	    NULL, handler, arg, &irq->tag);
7619 	if (rc != 0) {
7620 		device_printf(sc->dev,
7621 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7622 		    rid, name, rc);
7623 	} else if (name)
7624 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7625 
7626 	return (rc);
7627 }
7628 
7629 static int
7630 t4_free_irq(struct adapter *sc, struct irq *irq)
7631 {
7632 	if (irq->tag)
7633 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7634 	if (irq->res)
7635 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7636 
7637 	bzero(irq, sizeof(*irq));
7638 
7639 	return (0);
7640 }
7641 
7642 static void
7643 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7644 {
7645 
7646 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7647 	t4_get_regs(sc, buf, regs->len);
7648 }
7649 
7650 #define	A_PL_INDIR_CMD	0x1f8
7651 
7652 #define	S_PL_AUTOINC	31
7653 #define	M_PL_AUTOINC	0x1U
7654 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7655 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7656 
7657 #define	S_PL_VFID	20
7658 #define	M_PL_VFID	0xffU
7659 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7660 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7661 
7662 #define	S_PL_ADDR	0
7663 #define	M_PL_ADDR	0xfffffU
7664 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7665 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7666 
7667 #define	A_PL_INDIR_DATA	0x1fc
7668 
7669 static uint64_t
7670 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7671 {
7672 	u32 stats[2];
7673 
7674 	if (sc->flags & IS_VF) {
7675 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7676 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7677 	} else {
7678 		mtx_assert(&sc->reg_lock, MA_OWNED);
7679 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7680 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7681 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7682 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7683 	}
7684 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7685 }
7686 
7687 static void
7688 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7689 {
7690 
7691 #define GET_STAT(name) \
7692 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7693 
7694 	if (!(sc->flags & IS_VF))
7695 		mtx_lock(&sc->reg_lock);
7696 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7697 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7698 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7699 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7700 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7701 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7702 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7703 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7704 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7705 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7706 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7707 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7708 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7709 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7710 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7711 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7712 	if (!(sc->flags & IS_VF))
7713 		mtx_unlock(&sc->reg_lock);
7714 
7715 #undef GET_STAT
7716 }
7717 
7718 static void
7719 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7720 {
7721 	int reg;
7722 
7723 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7724 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7725 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7726 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7727 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7728 }
7729 
7730 static void
7731 vi_refresh_stats(struct vi_info *vi)
7732 {
7733 	struct timeval tv;
7734 	const struct timeval interval = {0, 250000};	/* 250ms */
7735 
7736 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7737 
7738 	if (vi->flags & VI_SKIP_STATS)
7739 		return;
7740 
7741 	getmicrotime(&tv);
7742 	timevalsub(&tv, &interval);
7743 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7744 		return;
7745 
7746 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7747 	getmicrotime(&vi->last_refreshed);
7748 }
7749 
7750 static void
7751 cxgbe_refresh_stats(struct vi_info *vi)
7752 {
7753 	u_int i, v, tnl_cong_drops, chan_map;
7754 	struct timeval tv;
7755 	const struct timeval interval = {0, 250000};	/* 250ms */
7756 	struct port_info *pi;
7757 	struct adapter *sc;
7758 
7759 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7760 
7761 	if (vi->flags & VI_SKIP_STATS)
7762 		return;
7763 
7764 	getmicrotime(&tv);
7765 	timevalsub(&tv, &interval);
7766 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7767 		return;
7768 
7769 	pi = vi->pi;
7770 	sc = vi->adapter;
7771 	tnl_cong_drops = 0;
7772 	t4_get_port_stats(sc, pi->hw_port, &pi->stats);
7773 	chan_map = pi->rx_e_chan_map;
7774 	while (chan_map) {
7775 		i = ffs(chan_map) - 1;
7776 		mtx_lock(&sc->reg_lock);
7777 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7778 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7779 		mtx_unlock(&sc->reg_lock);
7780 		tnl_cong_drops += v;
7781 		chan_map &= ~(1 << i);
7782 	}
7783 	pi->tnl_cong_drops = tnl_cong_drops;
7784 	getmicrotime(&vi->last_refreshed);
7785 }
7786 
7787 static void
7788 cxgbe_tick(void *arg)
7789 {
7790 	struct vi_info *vi = arg;
7791 
7792 	MPASS(IS_MAIN_VI(vi));
7793 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7794 
7795 	cxgbe_refresh_stats(vi);
7796 	callout_schedule(&vi->tick, hz);
7797 }
7798 
7799 static void
7800 vi_tick(void *arg)
7801 {
7802 	struct vi_info *vi = arg;
7803 
7804 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7805 
7806 	vi_refresh_stats(vi);
7807 	callout_schedule(&vi->tick, hz);
7808 }
7809 
7810 /* CIM inbound queues */
7811 static const char *t4_ibq[CIM_NUM_IBQ] = {
7812 	"ibq_tp0", "ibq_tp1", "ibq_ulp", "ibq_sge0", "ibq_sge1", "ibq_ncsi"
7813 };
7814 static const char *t7_ibq[CIM_NUM_IBQ_T7] = {
7815 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7816 	"ibq_sge1", "ibq_ncsi", NULL, "ibq_ipc1", "ibq_ipc2", "ibq_ipc3",
7817 	"ibq_ipc4", "ibq_ipc5", "ibq_ipc6", "ibq_ipc7"
7818 };
7819 static const char *t7_ibq_sec[] = {
7820 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7821 	NULL, NULL, NULL, "ibq_ipc0"
7822 };
7823 
7824 /* CIM outbound queues */
7825 static const char *t4_obq[CIM_NUM_OBQ_T5] = {
7826 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7827 	"obq_sge_rx_q0", "obq_sge_rx_q1" /* These two are T5/T6 only */
7828 };
7829 static const char *t7_obq[CIM_NUM_OBQ_T7] = {
7830 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7831 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc1", "obq_ipc2", "obq_ipc3",
7832 	"obq_ipc4", "obq_ipc5", "obq_ipc6", "obq_ipc7"
7833 };
7834 static const char *t7_obq_sec[] = {
7835 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", NULL,
7836 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc0"
7837 };
7838 
7839 static void
7840 cim_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
7841     struct sysctl_oid_list *c0)
7842 {
7843 	struct sysctl_oid *oid;
7844 	struct sysctl_oid_list *children1;
7845 	int i, j, qcount;
7846 	char s[16];
7847 	const char **qname;
7848 
7849 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "cim",
7850 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM block");
7851 	c0 = SYSCTL_CHILDREN(oid);
7852 
7853 	SYSCTL_ADD_U8(ctx, c0, OID_AUTO, "ncores", CTLFLAG_RD, NULL,
7854 	    sc->params.ncores, "# of active CIM cores");
7855 
7856 	for (i = 0; i < sc->params.ncores; i++) {
7857 		snprintf(s, sizeof(s), "%u", i);
7858 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, s,
7859 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM core");
7860 		children1 = SYSCTL_CHILDREN(oid);
7861 
7862 		/*
7863 		 * CTLFLAG_SKIP because the misc.devlog sysctl already displays
7864 		 * the log for all cores.  Use this sysctl to get the log for a
7865 		 * particular core only.
7866 		 */
7867 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "devlog",
7868 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7869 		    sc, i, sysctl_devlog, "A", "firmware's device log");
7870 
7871 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "loadavg",
7872 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7873 		    sysctl_loadavg, "A",
7874 		    "microprocessor load averages (select firmwares only)");
7875 
7876 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "qcfg",
7877 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7878 		    chip_id(sc) > CHELSIO_T6 ? sysctl_cim_qcfg_t7 : sysctl_cim_qcfg,
7879 		    "A", "Queue configuration");
7880 
7881 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "la",
7882 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7883 		    sysctl_cim_la, "A", "Logic analyzer");
7884 
7885 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "ma_la",
7886 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7887 		    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7888 
7889 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "pif_la",
7890 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7891 		    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7892 
7893 		/* IBQs */
7894 		switch (chip_id(sc)) {
7895 		case CHELSIO_T4:
7896 		case CHELSIO_T5:
7897 		case CHELSIO_T6:
7898 			qname = &t4_ibq[0];
7899 			qcount = nitems(t4_ibq);
7900 			break;
7901 		case CHELSIO_T7:
7902 		default:
7903 			if (i == 0) {
7904 				qname = &t7_ibq[0];
7905 				qcount = nitems(t7_ibq);
7906 			} else {
7907 				qname = &t7_ibq_sec[0];
7908 				qcount = nitems(t7_ibq_sec);
7909 			}
7910 			break;
7911 		}
7912 		MPASS(qcount <= sc->chip_params->cim_num_ibq);
7913 		for (j = 0; j < qcount; j++) {
7914 			if (qname[j] == NULL)
7915 				continue;
7916 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7917 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7918 			    (i << 16) | j, sysctl_cim_ibq, "A", NULL);
7919 		}
7920 
7921 		/* OBQs */
7922 		switch (chip_id(sc)) {
7923 		case CHELSIO_T4:
7924 			qname = t4_obq;
7925 			qcount = CIM_NUM_OBQ;
7926 			break;
7927 		case CHELSIO_T5:
7928 		case CHELSIO_T6:
7929 			qname = t4_obq;
7930 			qcount = nitems(t4_obq);
7931 			break;
7932 		case CHELSIO_T7:
7933 		default:
7934 			if (i == 0) {
7935 				qname = t7_obq;
7936 				qcount = nitems(t7_obq);
7937 			} else {
7938 				qname = t7_obq_sec;
7939 				qcount = nitems(t7_obq_sec);
7940 			}
7941 			break;
7942 		}
7943 		MPASS(qcount <= sc->chip_params->cim_num_obq);
7944 		for (j = 0; j < qcount; j++) {
7945 			if (qname[j] == NULL)
7946 				continue;
7947 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7948 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7949 			    (i << 16) | j, sysctl_cim_obq, "A", NULL);
7950 		}
7951 	}
7952 }
7953 
7954 /*
7955  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7956  */
7957 static char *caps_decoder[] = {
7958 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7959 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7960 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7961 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7962 	    "\006HASHFILTER\007ETHOFLD",
7963 	"\20\001TOE\002SENDPATH",			/* 4: TOE */
7964 	"\20\001RDDP\002RDMAC\003ROCEv2",		/* 5: RDMA */
7965 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7966 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7967 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7968 	    "\007T10DIF"
7969 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7970 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7971 	    "\004TLS_HW,\005TOE_IPSEC",
7972 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7973 		    "\004PO_INITIATOR\005PO_TARGET",
7974 	"\20\001NVMe_TCP",				/* 9: NVMe */
7975 };
7976 
7977 void
7978 t4_sysctls(struct adapter *sc)
7979 {
7980 	struct sysctl_ctx_list *ctx = &sc->ctx;
7981 	struct sysctl_oid *oid;
7982 	struct sysctl_oid_list *children, *c0;
7983 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7984 
7985 	/*
7986 	 * dev.t4nex.X.
7987 	 */
7988 	oid = device_get_sysctl_tree(sc->dev);
7989 	c0 = children = SYSCTL_CHILDREN(oid);
7990 
7991 	sc->sc_do_rxcopy = 1;
7992 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7993 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7994 
7995 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7996 	    sc->params.nports, "# of ports");
7997 
7998 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7999 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
8000 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
8001 	    "available doorbells");
8002 
8003 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
8004 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
8005 
8006 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
8007 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
8008 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
8009 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
8010 
8011 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
8012 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
8013 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
8014 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
8015 
8016 	t4_sge_sysctls(sc, ctx, children);
8017 
8018 	sc->lro_timeout = 100;
8019 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
8020 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
8021 
8022 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
8023 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
8024 
8025 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iflags", CTLFLAG_RW,
8026 	    &sc->intr_flags, 0, "flags for the slow interrupt handler");
8027 
8028 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
8029 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
8030 
8031 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
8032 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
8033 
8034 	if (sc->flags & IS_VF)
8035 		return;
8036 
8037 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
8038 	    NULL, chip_rev(sc), "chip hardware revision");
8039 
8040 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
8041 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
8042 
8043 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
8044 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
8045 
8046 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
8047 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
8048 
8049 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
8050 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
8051 
8052 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
8053 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
8054 
8055 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
8056 	    sc->er_version, 0, "expansion ROM version");
8057 
8058 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
8059 	    sc->bs_version, 0, "bootstrap firmware version");
8060 
8061 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
8062 	    NULL, sc->params.scfg_vers, "serial config version");
8063 
8064 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
8065 	    NULL, sc->params.vpd_vers, "VPD version");
8066 
8067 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
8068 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
8069 
8070 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
8071 	    sc->cfcsum, "config file checksum");
8072 
8073 #define SYSCTL_CAP(name, n, text) \
8074 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
8075 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
8076 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
8077 	    "available " text " capabilities")
8078 
8079 	SYSCTL_CAP(nbmcaps, 0, "NBM");
8080 	SYSCTL_CAP(linkcaps, 1, "link");
8081 	SYSCTL_CAP(switchcaps, 2, "switch");
8082 	SYSCTL_CAP(nvmecaps, 9, "NVMe");
8083 	SYSCTL_CAP(niccaps, 3, "NIC");
8084 	SYSCTL_CAP(toecaps, 4, "TCP offload");
8085 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
8086 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
8087 	SYSCTL_CAP(cryptocaps, 7, "crypto");
8088 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
8089 #undef SYSCTL_CAP
8090 
8091 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
8092 	    NULL, sc->tids.nftids, "number of filters");
8093 
8094 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_tunnel", CTLFLAG_RD,
8095 	    NULL, sc->params.nipsec_tunnel, "max hw IPsec tunnels");
8096 
8097 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_transport", CTLFLAG_RD,
8098 	    NULL, sc->params.nipsec_transport, "max hw IPsec transport pairs");
8099 
8100 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nofld_ipsec_tunnel", CTLFLAG_RD,
8101 	    NULL, sc->params.nofld_ipsec_tunnel, "max hw IPsec tunnels (TOE)");
8102 
8103 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8104 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8105 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
8106 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
8107 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8108 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
8109 
8110 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
8111 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
8112 	    "I", "core Vdd (in mV)");
8113 
8114 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
8115 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
8116 	    sysctl_cpus, "A", "local CPUs");
8117 
8118 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
8119 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
8120 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
8121 
8122 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
8123 	    &sc->swintr, 0, "software triggered interrupts");
8124 
8125 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
8126 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
8127 	    "1 = reset adapter, 0 = zero reset counter");
8128 
8129 	/*
8130 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
8131 	 */
8132 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
8133 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
8134 	    "logs and miscellaneous information");
8135 	children = SYSCTL_CHILDREN(oid);
8136 
8137 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
8138 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8139 	    sysctl_cctrl, "A", "congestion control");
8140 
8141 	cim_sysctls(sc, ctx, children);
8142 
8143 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
8144 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8145 	    sysctl_cpl_stats, "A", "CPL statistics");
8146 
8147 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
8148 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8149 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
8150 
8151 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
8152 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8153 	    sysctl_tid_stats, "A", "tid stats");
8154 
8155 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
8156 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, -1,
8157 	    sysctl_devlog, "A", "firmware's device log (all cores)");
8158 
8159 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
8160 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8161 	    sysctl_fcoe_stats, "A", "FCoE statistics");
8162 
8163 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
8164 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8165 	    sysctl_hw_sched, "A", "hardware scheduler ");
8166 
8167 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
8168 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8169 	    sysctl_l2t, "A", "hardware L2 table");
8170 
8171 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
8172 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8173 	    sysctl_smt, "A", "hardware source MAC table");
8174 
8175 #ifdef INET6
8176 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
8177 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8178 	    sysctl_clip, "A", "active CLIP table entries");
8179 #endif
8180 
8181 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
8182 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8183 	    sysctl_lb_stats, "A", "loopback statistics");
8184 
8185 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
8186 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8187 	    sysctl_meminfo, "A", "memory regions");
8188 
8189 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
8190 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8191 	    chip_id(sc) >= CHELSIO_T7 ? sysctl_mps_tcam_t7 :
8192 	    (chip_id(sc) >= CHELSIO_T6 ? sysctl_mps_tcam_t6 : sysctl_mps_tcam),
8193 	    "A", "MPS TCAM entries");
8194 
8195 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
8196 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8197 	    sysctl_path_mtus, "A", "path MTUs");
8198 
8199 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
8200 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8201 	    sysctl_pm_stats, "A", "PM statistics");
8202 
8203 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
8204 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8205 	    sysctl_rdma_stats, "A", "RDMA statistics");
8206 
8207 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
8208 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8209 	    sysctl_tcp_stats, "A", "TCP statistics");
8210 
8211 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
8212 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8213 	    sysctl_tids, "A", "TID information");
8214 
8215 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
8216 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8217 	    sysctl_tp_err_stats, "A", "TP error statistics");
8218 
8219 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
8220 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8221 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
8222 
8223 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
8224 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8225 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
8226 
8227 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
8228 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8229 	    sysctl_tp_la, "A", "TP logic analyzer");
8230 
8231 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
8232 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8233 	    sysctl_tx_rate, "A", "Tx rate");
8234 
8235 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
8236 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8237 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
8238 
8239 	if (chip_id(sc) >= CHELSIO_T5) {
8240 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
8241 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8242 		    sysctl_wcwr_stats, "A", "write combined work requests");
8243 	}
8244 
8245 	if (chip_id(sc) >= CHELSIO_T7) {
8246 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcb_cache",
8247 		    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tcb_cache, "I",
8248 		    "1 = enabled (default), 0 = disabled (for debug only)");
8249 	}
8250 
8251 #ifdef KERN_TLS
8252 	if (is_ktls(sc)) {
8253 		/*
8254 		 * dev.t4nex.0.tls.
8255 		 */
8256 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
8257 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
8258 		children = SYSCTL_CHILDREN(oid);
8259 
8260 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cbc",
8261 		    CTLFLAG_RW, &sc->tlst.cbc, 0,
8262 		    "Enable offload of AES-CBC cipher suites.");
8263 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
8264 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
8265 		    "keys in work requests (1) or attempt to store TLS keys "
8266 		    "in card memory.");
8267 
8268 		if (is_t6(sc))
8269 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
8270 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
8271 			    "combine TCB field updates with TLS record work "
8272 			    "requests.");
8273 		else {
8274 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "short_records",
8275 			    CTLFLAG_RW, &sc->tlst.short_records, 0,
8276 			    "Use cipher-only mode for short records.");
8277 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "partial_ghash",
8278 			    CTLFLAG_RW, &sc->tlst.partial_ghash, 0,
8279 			    "Use partial GHASH for AES-GCM records.");
8280 		}
8281 	}
8282 #endif
8283 
8284 #ifdef TCP_OFFLOAD
8285 	if (is_offload(sc)) {
8286 		int i;
8287 		char s[4];
8288 
8289 		/*
8290 		 * dev.t4nex.X.toe.
8291 		 */
8292 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
8293 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
8294 		children = SYSCTL_CHILDREN(oid);
8295 
8296 		sc->tt.cong_algorithm = -1;
8297 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
8298 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
8299 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
8300 		    "3 = highspeed)");
8301 
8302 		sc->tt.sndbuf = -1;
8303 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
8304 		    &sc->tt.sndbuf, 0, "hardware send buffer");
8305 
8306 		sc->tt.ddp = 0;
8307 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
8308 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
8309 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
8310 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
8311 
8312 		sc->tt.rx_coalesce = -1;
8313 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
8314 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
8315 
8316 		sc->tt.tls = 1;
8317 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
8318 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
8319 		    "Inline TLS allowed");
8320 
8321 		sc->tt.tx_align = -1;
8322 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
8323 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
8324 
8325 		sc->tt.tx_zcopy = 0;
8326 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
8327 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
8328 		    "Enable zero-copy aio_write(2)");
8329 
8330 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
8331 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8332 		    "cop_managed_offloading", CTLFLAG_RW,
8333 		    &sc->tt.cop_managed_offloading, 0,
8334 		    "COP (Connection Offload Policy) controls all TOE offload");
8335 
8336 		sc->tt.autorcvbuf_inc = 16 * 1024;
8337 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
8338 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
8339 		    "autorcvbuf increment");
8340 
8341 		sc->tt.update_hc_on_pmtu_change = 1;
8342 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8343 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
8344 		    &sc->tt.update_hc_on_pmtu_change, 0,
8345 		    "Update hostcache entry if the PMTU changes");
8346 
8347 		sc->tt.iso = 1;
8348 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
8349 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
8350 
8351 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
8352 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8353 		    sysctl_tp_tick, "A", "TP timer tick (us)");
8354 
8355 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
8356 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
8357 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
8358 
8359 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
8360 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
8361 		    sysctl_tp_tick, "A", "DACK tick (us)");
8362 
8363 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
8364 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8365 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
8366 
8367 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
8368 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8369 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
8370 		    "Minimum retransmit interval (us)");
8371 
8372 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
8373 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8374 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
8375 		    "Maximum retransmit interval (us)");
8376 
8377 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
8378 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8379 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
8380 		    "Persist timer min (us)");
8381 
8382 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
8383 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8384 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
8385 		    "Persist timer max (us)");
8386 
8387 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
8388 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8389 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
8390 		    "Keepalive idle timer (us)");
8391 
8392 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
8393 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8394 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
8395 		    "Keepalive interval timer (us)");
8396 
8397 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
8398 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8399 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
8400 
8401 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
8402 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8403 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
8404 		    "FINWAIT2 timer (us)");
8405 
8406 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
8407 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8408 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
8409 		    "Number of SYN retransmissions before abort");
8410 
8411 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
8412 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8413 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
8414 		    "Number of retransmissions before abort");
8415 
8416 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
8417 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8418 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
8419 		    "Number of keepalive probes before abort");
8420 
8421 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
8422 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8423 		    "TOE retransmit backoffs");
8424 		children = SYSCTL_CHILDREN(oid);
8425 		for (i = 0; i < 16; i++) {
8426 			snprintf(s, sizeof(s), "%u", i);
8427 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
8428 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8429 			    i, sysctl_tp_backoff, "IU",
8430 			    "TOE retransmit backoff");
8431 		}
8432 	}
8433 #endif
8434 }
8435 
8436 void
8437 vi_sysctls(struct vi_info *vi)
8438 {
8439 	struct sysctl_ctx_list *ctx = &vi->ctx;
8440 	struct sysctl_oid *oid;
8441 	struct sysctl_oid_list *children;
8442 
8443 	/*
8444 	 * dev.v?(cxgbe|cxl).X.
8445 	 */
8446 	oid = device_get_sysctl_tree(vi->dev);
8447 	children = SYSCTL_CHILDREN(oid);
8448 
8449 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
8450 	    vi->viid, "VI identifer");
8451 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
8452 	    &vi->nrxq, 0, "# of rx queues");
8453 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
8454 	    &vi->ntxq, 0, "# of tx queues");
8455 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
8456 	    &vi->first_rxq, 0, "index of first rx queue");
8457 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
8458 	    &vi->first_txq, 0, "index of first tx queue");
8459 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
8460 	    vi->rss_base, "start of RSS indirection table");
8461 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
8462 	    vi->rss_size, "size of RSS indirection table");
8463 
8464 	if (IS_MAIN_VI(vi)) {
8465 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
8466 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8467 		    sysctl_noflowq, "IU",
8468 		    "Reserve queue 0 for non-flowid packets");
8469 	}
8470 
8471 	if (vi->adapter->flags & IS_VF) {
8472 		MPASS(vi->flags & TX_USES_VM_WR);
8473 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
8474 		    NULL, 1, "use VM work requests for transmit");
8475 	} else {
8476 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
8477 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8478 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
8479 	}
8480 
8481 #ifdef TCP_OFFLOAD
8482 	if (vi->nofldrxq != 0) {
8483 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
8484 		    &vi->nofldrxq, 0,
8485 		    "# of rx queues for offloaded TCP connections");
8486 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
8487 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
8488 		    "index of first TOE rx queue");
8489 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
8490 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8491 		    sysctl_holdoff_tmr_idx_ofld, "I",
8492 		    "holdoff timer index for TOE queues");
8493 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
8494 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8495 		    sysctl_holdoff_pktc_idx_ofld, "I",
8496 		    "holdoff packet counter index for TOE queues");
8497 	}
8498 #endif
8499 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
8500 	if (vi->nofldtxq != 0) {
8501 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
8502 		    &vi->nofldtxq, 0,
8503 		    "# of tx queues for TOE/ETHOFLD");
8504 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
8505 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
8506 		    "index of first TOE/ETHOFLD tx queue");
8507 	}
8508 #endif
8509 #ifdef DEV_NETMAP
8510 	if (vi->nnmrxq != 0) {
8511 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
8512 		    &vi->nnmrxq, 0, "# of netmap rx queues");
8513 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
8514 		    &vi->nnmtxq, 0, "# of netmap tx queues");
8515 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
8516 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
8517 		    "index of first netmap rx queue");
8518 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
8519 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
8520 		    "index of first netmap tx queue");
8521 	}
8522 #endif
8523 
8524 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8525 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8526 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8527 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8528 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8529 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8530 
8531 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8532 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8533 	    sysctl_qsize_rxq, "I", "rx queue size");
8534 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8535 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8536 	    sysctl_qsize_txq, "I", "tx queue size");
8537 }
8538 
8539 static void
8540 cxgbe_sysctls(struct port_info *pi)
8541 {
8542 	struct sysctl_ctx_list *ctx = &pi->ctx;
8543 	struct sysctl_oid *oid;
8544 	struct sysctl_oid_list *children, *children2;
8545 	struct adapter *sc = pi->adapter;
8546 	int i;
8547 	char name[16];
8548 	static char *tc_flags = {"\20\1USER"};
8549 
8550 	/*
8551 	 * dev.cxgbe.X.
8552 	 */
8553 	oid = device_get_sysctl_tree(pi->dev);
8554 	children = SYSCTL_CHILDREN(oid);
8555 
8556 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8557 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8558 	    sysctl_linkdnrc, "A", "reason why link is down");
8559 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8560 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8561 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8562 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8563 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8564 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8565 		    sysctl_btphy, "I", "PHY firmware version");
8566 	}
8567 
8568 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8569 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8570 	    sysctl_pause_settings, "A",
8571 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8572 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8573 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8574 	    "FEC in use on the link");
8575 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8576 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8577 	    sysctl_requested_fec, "A",
8578 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8579 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8580 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8581 	    "FEC recommended by the cable/transceiver");
8582 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8583 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8584 	    sysctl_autoneg, "I",
8585 	    "autonegotiation (-1 = not supported)");
8586 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8587 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8588 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8589 
8590 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8591 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8592 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8593 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8594 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8595 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8596 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8597 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8598 
8599 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8600 	    port_top_speed(pi), "max speed (in Gbps)");
8601 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8602 	    pi->mps_bg_map, "MPS buffer group map");
8603 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8604 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8605 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8606 	    pi->tx_chan, "TP tx c-channel");
8607 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8608 	    pi->rx_chan, "TP rx c-channel");
8609 
8610 	if (sc->flags & IS_VF)
8611 		return;
8612 
8613 	/*
8614 	 * dev.(cxgbe|cxl).X.tc.
8615 	 */
8616 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8617 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8618 	    "Tx scheduler traffic classes (cl_rl)");
8619 	children2 = SYSCTL_CHILDREN(oid);
8620 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8621 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8622 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8623 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8624 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8625 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8626 	for (i = 0; i < sc->params.nsched_cls; i++) {
8627 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8628 
8629 		snprintf(name, sizeof(name), "%d", i);
8630 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8631 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8632 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8633 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8634 		    CTLFLAG_RD, &tc->state, 0, "current state");
8635 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8636 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8637 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8638 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8639 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8640 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8641 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8642 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8643 		    "traffic class parameters");
8644 	}
8645 
8646 	/*
8647 	 * dev.cxgbe.X.stats.
8648 	 */
8649 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8650 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8651 	children = SYSCTL_CHILDREN(oid);
8652 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8653 	    &pi->tx_parse_error, 0,
8654 	    "# of tx packets with invalid length or # of segments");
8655 
8656 #define T4_LBSTAT(name, stat, desc) do { \
8657 	if (sc->params.tp.lb_mode) { \
8658 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8659 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, \
8660 		    A_MPS_PORT_STAT_##stat##_L, \
8661 		    sysctl_handle_t4_portstat64, "QU", desc); \
8662 	} else { \
8663 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8664 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8665 		    t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8666 		    sysctl_handle_t4_reg64, "QU", desc); \
8667 	} \
8668 } while (0)
8669 
8670 	T4_LBSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8671 	T4_LBSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8672 	T4_LBSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8673 	T4_LBSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8674 	T4_LBSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8675 	T4_LBSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8676 	T4_LBSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8677 	T4_LBSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8678 	T4_LBSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8679 	T4_LBSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8680 	T4_LBSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8681 	T4_LBSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8682 	T4_LBSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8683 	T4_LBSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8684 	T4_LBSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8685 	T4_LBSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8686 	T4_LBSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8687 	T4_LBSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8688 	T4_LBSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8689 	T4_LBSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8690 	T4_LBSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8691 	T4_LBSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8692 	T4_LBSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8693 
8694 	T4_LBSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8695 	T4_LBSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8696 	T4_LBSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8697 	T4_LBSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8698 	T4_LBSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8699 	T4_LBSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8700 	T4_LBSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8701 	if (is_t6(sc)) {
8702 		/* Read from port_stats and may be stale by up to 1s */
8703 		SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "rx_fcs_err",
8704 		    CTLFLAG_RD, &pi->stats.rx_fcs_err,
8705 		    "# of frames received with bad FCS since last link up");
8706 	} else {
8707 		T4_LBSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8708 		    "# of frames received with bad FCS");
8709 	}
8710 	T4_LBSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8711 	T4_LBSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8712 	T4_LBSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8713 	T4_LBSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8714 	T4_LBSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8715 	T4_LBSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8716 	T4_LBSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8717 	T4_LBSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8718 	T4_LBSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8719 	T4_LBSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8720 	T4_LBSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8721 	T4_LBSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8722 	T4_LBSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8723 	T4_LBSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8724 	T4_LBSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8725 	T4_LBSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8726 	T4_LBSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8727 	T4_LBSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8728 	T4_LBSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8729 #undef T4_LBSTAT
8730 
8731 #define T4_REGSTAT(name, stat, desc) do { \
8732 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8733 	    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8734 	    A_MPS_STAT_##stat##_L, sysctl_handle_t4_reg64, "QU", desc); \
8735 } while (0)
8736 
8737 	if (pi->mps_bg_map & 1) {
8738 		T4_REGSTAT(rx_ovflow0, RX_BG_0_MAC_DROP_FRAME,
8739 		    "# drops due to buffer-group 0 overflows");
8740 		T4_REGSTAT(rx_trunc0, RX_BG_0_MAC_TRUNC_FRAME,
8741 		    "# of buffer-group 0 truncated packets");
8742 	}
8743 	if (pi->mps_bg_map & 2) {
8744 		T4_REGSTAT(rx_ovflow1, RX_BG_1_MAC_DROP_FRAME,
8745 		    "# drops due to buffer-group 1 overflows");
8746 		T4_REGSTAT(rx_trunc1, RX_BG_1_MAC_TRUNC_FRAME,
8747 		    "# of buffer-group 1 truncated packets");
8748 	}
8749 	if (pi->mps_bg_map & 4) {
8750 		T4_REGSTAT(rx_ovflow2, RX_BG_2_MAC_DROP_FRAME,
8751 		    "# drops due to buffer-group 2 overflows");
8752 		T4_REGSTAT(rx_trunc2, RX_BG_2_MAC_TRUNC_FRAME,
8753 		    "# of buffer-group 2 truncated packets");
8754 	}
8755 	if (pi->mps_bg_map & 8) {
8756 		T4_REGSTAT(rx_ovflow3, RX_BG_3_MAC_DROP_FRAME,
8757 		    "# drops due to buffer-group 3 overflows");
8758 		T4_REGSTAT(rx_trunc3, RX_BG_3_MAC_TRUNC_FRAME,
8759 		    "# of buffer-group 3 truncated packets");
8760 	}
8761 #undef T4_REGSTAT
8762 }
8763 
8764 static int
8765 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8766 {
8767 	int rc, *i, space = 0;
8768 	struct sbuf sb;
8769 
8770 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8771 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8772 		if (space)
8773 			sbuf_printf(&sb, " ");
8774 		sbuf_printf(&sb, "%d", *i);
8775 		space = 1;
8776 	}
8777 	rc = sbuf_finish(&sb);
8778 	sbuf_delete(&sb);
8779 	return (rc);
8780 }
8781 
8782 static int
8783 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8784 {
8785 	int rc;
8786 	struct sbuf *sb;
8787 
8788 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8789 	if (sb == NULL)
8790 		return (ENOMEM);
8791 
8792 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8793 	rc = sbuf_finish(sb);
8794 	sbuf_delete(sb);
8795 
8796 	return (rc);
8797 }
8798 
8799 static int
8800 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8801 {
8802 	int rc;
8803 	struct sbuf *sb;
8804 
8805 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8806 	if (sb == NULL)
8807 		return (ENOMEM);
8808 
8809 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8810 	rc = sbuf_finish(sb);
8811 	sbuf_delete(sb);
8812 
8813 	return (rc);
8814 }
8815 
8816 static int
8817 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8818 {
8819 	struct port_info *pi = arg1;
8820 	int op = arg2;
8821 	struct adapter *sc = pi->adapter;
8822 	u_int v;
8823 	int rc;
8824 
8825 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8826 	if (rc)
8827 		return (rc);
8828 	if (!hw_all_ok(sc))
8829 		rc = ENXIO;
8830 	else {
8831 		/* XXX: magic numbers */
8832 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8833 		    op ? 0x20 : 0xc820, &v);
8834 	}
8835 	end_synchronized_op(sc, 0);
8836 	if (rc)
8837 		return (rc);
8838 	if (op == 0)
8839 		v /= 256;
8840 
8841 	rc = sysctl_handle_int(oidp, &v, 0, req);
8842 	return (rc);
8843 }
8844 
8845 static int
8846 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8847 {
8848 	struct vi_info *vi = arg1;
8849 	int rc, val;
8850 
8851 	val = vi->rsrv_noflowq;
8852 	rc = sysctl_handle_int(oidp, &val, 0, req);
8853 	if (rc != 0 || req->newptr == NULL)
8854 		return (rc);
8855 
8856 	if ((val >= 1) && (vi->ntxq > 1))
8857 		vi->rsrv_noflowq = 1;
8858 	else
8859 		vi->rsrv_noflowq = 0;
8860 
8861 	return (rc);
8862 }
8863 
8864 static int
8865 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8866 {
8867 	struct vi_info *vi = arg1;
8868 	struct adapter *sc = vi->adapter;
8869 	int rc, val, i;
8870 
8871 	MPASS(!(sc->flags & IS_VF));
8872 
8873 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8874 	rc = sysctl_handle_int(oidp, &val, 0, req);
8875 	if (rc != 0 || req->newptr == NULL)
8876 		return (rc);
8877 
8878 	if (val != 0 && val != 1)
8879 		return (EINVAL);
8880 
8881 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8882 	    "t4txvm");
8883 	if (rc)
8884 		return (rc);
8885 	if (!hw_all_ok(sc))
8886 		rc = ENXIO;
8887 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8888 		/*
8889 		 * We don't want parse_pkt to run with one setting (VF or PF)
8890 		 * and then eth_tx to see a different setting but still use
8891 		 * stale information calculated by parse_pkt.
8892 		 */
8893 		rc = EBUSY;
8894 	} else {
8895 		struct port_info *pi = vi->pi;
8896 		struct sge_txq *txq;
8897 		uint32_t ctrl0;
8898 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8899 
8900 		if (val) {
8901 			vi->flags |= TX_USES_VM_WR;
8902 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8903 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8904 			    V_TXPKT_INTF(pi->hw_port));
8905 			if (!(sc->flags & IS_VF))
8906 				npkt--;
8907 		} else {
8908 			vi->flags &= ~TX_USES_VM_WR;
8909 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8910 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8911 			    V_TXPKT_INTF(pi->hw_port) | V_TXPKT_PF(sc->pf) |
8912 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8913 		}
8914 		for_each_txq(vi, i, txq) {
8915 			txq->cpl_ctrl0 = ctrl0;
8916 			txq->txp.max_npkt = npkt;
8917 		}
8918 	}
8919 	end_synchronized_op(sc, LOCK_HELD);
8920 	return (rc);
8921 }
8922 
8923 static int
8924 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8925 {
8926 	struct vi_info *vi = arg1;
8927 	struct adapter *sc = vi->adapter;
8928 	int idx, rc, i;
8929 	struct sge_rxq *rxq;
8930 	uint8_t v;
8931 
8932 	idx = vi->tmr_idx;
8933 
8934 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8935 	if (rc != 0 || req->newptr == NULL)
8936 		return (rc);
8937 
8938 	if (idx < 0 || idx >= SGE_NTIMERS)
8939 		return (EINVAL);
8940 
8941 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8942 	    "t4tmr");
8943 	if (rc)
8944 		return (rc);
8945 
8946 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8947 	for_each_rxq(vi, i, rxq) {
8948 #ifdef atomic_store_rel_8
8949 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8950 #else
8951 		rxq->iq.intr_params = v;
8952 #endif
8953 	}
8954 	vi->tmr_idx = idx;
8955 
8956 	end_synchronized_op(sc, LOCK_HELD);
8957 	return (0);
8958 }
8959 
8960 static int
8961 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8962 {
8963 	struct vi_info *vi = arg1;
8964 	struct adapter *sc = vi->adapter;
8965 	int idx, rc;
8966 
8967 	idx = vi->pktc_idx;
8968 
8969 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8970 	if (rc != 0 || req->newptr == NULL)
8971 		return (rc);
8972 
8973 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8974 		return (EINVAL);
8975 
8976 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8977 	    "t4pktc");
8978 	if (rc)
8979 		return (rc);
8980 
8981 	if (vi->flags & VI_INIT_DONE)
8982 		rc = EBUSY; /* cannot be changed once the queues are created */
8983 	else
8984 		vi->pktc_idx = idx;
8985 
8986 	end_synchronized_op(sc, LOCK_HELD);
8987 	return (rc);
8988 }
8989 
8990 static int
8991 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8992 {
8993 	struct vi_info *vi = arg1;
8994 	struct adapter *sc = vi->adapter;
8995 	int qsize, rc;
8996 
8997 	qsize = vi->qsize_rxq;
8998 
8999 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
9000 	if (rc != 0 || req->newptr == NULL)
9001 		return (rc);
9002 
9003 	if (qsize < 128 || (qsize & 7))
9004 		return (EINVAL);
9005 
9006 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9007 	    "t4rxqs");
9008 	if (rc)
9009 		return (rc);
9010 
9011 	if (vi->flags & VI_INIT_DONE)
9012 		rc = EBUSY; /* cannot be changed once the queues are created */
9013 	else
9014 		vi->qsize_rxq = qsize;
9015 
9016 	end_synchronized_op(sc, LOCK_HELD);
9017 	return (rc);
9018 }
9019 
9020 static int
9021 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
9022 {
9023 	struct vi_info *vi = arg1;
9024 	struct adapter *sc = vi->adapter;
9025 	int qsize, rc;
9026 
9027 	qsize = vi->qsize_txq;
9028 
9029 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
9030 	if (rc != 0 || req->newptr == NULL)
9031 		return (rc);
9032 
9033 	if (qsize < 128 || qsize > 65536)
9034 		return (EINVAL);
9035 
9036 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9037 	    "t4txqs");
9038 	if (rc)
9039 		return (rc);
9040 
9041 	if (vi->flags & VI_INIT_DONE)
9042 		rc = EBUSY; /* cannot be changed once the queues are created */
9043 	else
9044 		vi->qsize_txq = qsize;
9045 
9046 	end_synchronized_op(sc, LOCK_HELD);
9047 	return (rc);
9048 }
9049 
9050 static int
9051 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
9052 {
9053 	struct port_info *pi = arg1;
9054 	struct adapter *sc = pi->adapter;
9055 	struct link_config *lc = &pi->link_cfg;
9056 	int rc;
9057 
9058 	if (req->newptr == NULL) {
9059 		struct sbuf *sb;
9060 		static char *bits = "\20\1RX\2TX\3AUTO";
9061 
9062 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9063 		if (sb == NULL)
9064 			return (ENOMEM);
9065 
9066 		if (lc->link_ok) {
9067 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
9068 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
9069 		} else {
9070 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
9071 			    PAUSE_RX | PAUSE_AUTONEG), bits);
9072 		}
9073 		rc = sbuf_finish(sb);
9074 		sbuf_delete(sb);
9075 	} else {
9076 		char s[2];
9077 		int n;
9078 
9079 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
9080 		    PAUSE_AUTONEG));
9081 		s[1] = 0;
9082 
9083 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9084 		if (rc != 0)
9085 			return(rc);
9086 
9087 		if (s[1] != 0)
9088 			return (EINVAL);
9089 		if (s[0] < '0' || s[0] > '9')
9090 			return (EINVAL);	/* not a number */
9091 		n = s[0] - '0';
9092 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
9093 			return (EINVAL);	/* some other bit is set too */
9094 
9095 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9096 		    "t4PAUSE");
9097 		if (rc)
9098 			return (rc);
9099 		if (hw_all_ok(sc)) {
9100 			PORT_LOCK(pi);
9101 			lc->requested_fc = n;
9102 			fixup_link_config(pi);
9103 			if (pi->up_vis > 0)
9104 				rc = apply_link_config(pi);
9105 			set_current_media(pi);
9106 			PORT_UNLOCK(pi);
9107 		}
9108 		end_synchronized_op(sc, 0);
9109 	}
9110 
9111 	return (rc);
9112 }
9113 
9114 static int
9115 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
9116 {
9117 	struct port_info *pi = arg1;
9118 	struct link_config *lc = &pi->link_cfg;
9119 	int rc;
9120 	struct sbuf *sb;
9121 
9122 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9123 	if (sb == NULL)
9124 		return (ENOMEM);
9125 	if (lc->link_ok)
9126 		sbuf_printf(sb, "%b", lc->fec, t4_fec_bits);
9127 	else
9128 		sbuf_printf(sb, "no link");
9129 	rc = sbuf_finish(sb);
9130 	sbuf_delete(sb);
9131 
9132 	return (rc);
9133 }
9134 
9135 static int
9136 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
9137 {
9138 	struct port_info *pi = arg1;
9139 	struct adapter *sc = pi->adapter;
9140 	struct link_config *lc = &pi->link_cfg;
9141 	int rc;
9142 	int8_t old = lc->requested_fec;
9143 
9144 	if (req->newptr == NULL) {
9145 		struct sbuf *sb;
9146 
9147 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9148 		if (sb == NULL)
9149 			return (ENOMEM);
9150 
9151 		sbuf_printf(sb, "%b", old, t4_fec_bits);
9152 		rc = sbuf_finish(sb);
9153 		sbuf_delete(sb);
9154 	} else {
9155 		char s[8];
9156 		int n;
9157 
9158 		snprintf(s, sizeof(s), "%d", old == FEC_AUTO ? -1 :
9159 		    old & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
9160 
9161 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9162 		if (rc != 0)
9163 			return(rc);
9164 
9165 		n = strtol(&s[0], NULL, 0);
9166 		if (n < 0 || n & FEC_AUTO)
9167 			n = FEC_AUTO;
9168 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
9169 			return (EINVAL);/* some other bit is set too */
9170 
9171 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9172 		    "t4reqf");
9173 		if (rc)
9174 			return (rc);
9175 		PORT_LOCK(pi);
9176 		if (lc->requested_fec != old) {
9177 			rc = EBUSY;
9178 			goto done;
9179 		}
9180 		if (n == FEC_AUTO)
9181 			lc->requested_fec = FEC_AUTO;
9182 		else if (n == 0 || n == FEC_NONE)
9183 			lc->requested_fec = FEC_NONE;
9184 		else {
9185 			if ((lc->pcaps |
9186 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
9187 			    lc->pcaps) {
9188 				rc = ENOTSUP;
9189 				goto done;
9190 			}
9191 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
9192 			    FEC_MODULE);
9193 		}
9194 		if (hw_all_ok(sc)) {
9195 			fixup_link_config(pi);
9196 			if (pi->up_vis > 0) {
9197 				rc = apply_link_config(pi);
9198 				if (rc != 0) {
9199 					lc->requested_fec = old;
9200 					if (rc == FW_EPROTO)
9201 						rc = ENOTSUP;
9202 				}
9203 			}
9204 		}
9205 done:
9206 		PORT_UNLOCK(pi);
9207 		end_synchronized_op(sc, 0);
9208 	}
9209 
9210 	return (rc);
9211 }
9212 
9213 static int
9214 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
9215 {
9216 	struct port_info *pi = arg1;
9217 	struct adapter *sc = pi->adapter;
9218 	struct link_config *lc = &pi->link_cfg;
9219 	int rc;
9220 	int8_t fec;
9221 	struct sbuf *sb;
9222 
9223 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9224 	if (sb == NULL)
9225 		return (ENOMEM);
9226 
9227 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
9228 		rc = EBUSY;
9229 		goto done;
9230 	}
9231 	if (!hw_all_ok(sc)) {
9232 		rc = ENXIO;
9233 		goto done;
9234 	}
9235 	PORT_LOCK(pi);
9236 	if (pi->up_vis == 0) {
9237 		/*
9238 		 * If all the interfaces are administratively down the firmware
9239 		 * does not report transceiver changes.  Refresh port info here.
9240 		 * This is the only reason we have a synchronized op in this
9241 		 * function.  Just PORT_LOCK would have been enough otherwise.
9242 		 */
9243 		t4_update_port_info(pi);
9244 	}
9245 
9246 	fec = lc->fec_hint;
9247 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
9248 	    !fec_supported(lc->pcaps)) {
9249 		PORT_UNLOCK(pi);
9250 		sbuf_printf(sb, "n/a");
9251 	} else {
9252 		if (fec == 0)
9253 			fec = FEC_NONE;
9254 		PORT_UNLOCK(pi);
9255 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, t4_fec_bits);
9256 	}
9257 	rc = sbuf_finish(sb);
9258 done:
9259 	sbuf_delete(sb);
9260 	end_synchronized_op(sc, 0);
9261 
9262 	return (rc);
9263 }
9264 
9265 static int
9266 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
9267 {
9268 	struct port_info *pi = arg1;
9269 	struct adapter *sc = pi->adapter;
9270 	struct link_config *lc = &pi->link_cfg;
9271 	int rc, val;
9272 
9273 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
9274 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
9275 	else
9276 		val = -1;
9277 	rc = sysctl_handle_int(oidp, &val, 0, req);
9278 	if (rc != 0 || req->newptr == NULL)
9279 		return (rc);
9280 	if (val == 0)
9281 		val = AUTONEG_DISABLE;
9282 	else if (val == 1)
9283 		val = AUTONEG_ENABLE;
9284 	else
9285 		val = AUTONEG_AUTO;
9286 
9287 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9288 	    "t4aneg");
9289 	if (rc)
9290 		return (rc);
9291 	PORT_LOCK(pi);
9292 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
9293 		rc = ENOTSUP;
9294 		goto done;
9295 	}
9296 	lc->requested_aneg = val;
9297 	if (hw_all_ok(sc)) {
9298 		fixup_link_config(pi);
9299 		if (pi->up_vis > 0)
9300 			rc = apply_link_config(pi);
9301 		set_current_media(pi);
9302 	}
9303 done:
9304 	PORT_UNLOCK(pi);
9305 	end_synchronized_op(sc, 0);
9306 	return (rc);
9307 }
9308 
9309 static int
9310 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
9311 {
9312 	struct port_info *pi = arg1;
9313 	struct adapter *sc = pi->adapter;
9314 	struct link_config *lc = &pi->link_cfg;
9315 	int rc, val;
9316 
9317 	val = lc->force_fec;
9318 	MPASS(val >= -1 && val <= 1);
9319 	rc = sysctl_handle_int(oidp, &val, 0, req);
9320 	if (rc != 0 || req->newptr == NULL)
9321 		return (rc);
9322 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
9323 		return (ENOTSUP);
9324 	if (val < -1 || val > 1)
9325 		return (EINVAL);
9326 
9327 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
9328 	if (rc)
9329 		return (rc);
9330 	PORT_LOCK(pi);
9331 	lc->force_fec = val;
9332 	if (hw_all_ok(sc)) {
9333 		fixup_link_config(pi);
9334 		if (pi->up_vis > 0)
9335 			rc = apply_link_config(pi);
9336 	}
9337 	PORT_UNLOCK(pi);
9338 	end_synchronized_op(sc, 0);
9339 	return (rc);
9340 }
9341 
9342 static int
9343 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
9344 {
9345 	struct adapter *sc = arg1;
9346 	int rc, reg = arg2;
9347 	uint64_t val;
9348 
9349 	mtx_lock(&sc->reg_lock);
9350 	if (hw_off_limits(sc))
9351 		rc = ENXIO;
9352 	else {
9353 		rc = 0;
9354 		val = t4_read_reg64(sc, reg);
9355 	}
9356 	mtx_unlock(&sc->reg_lock);
9357 	if (rc == 0)
9358 		rc = sysctl_handle_64(oidp, &val, 0, req);
9359 	return (rc);
9360 }
9361 
9362 static int
9363 sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS)
9364 {
9365 	struct port_info *pi = arg1;
9366 	struct adapter *sc = pi->adapter;
9367 	int rc, i, reg = arg2;
9368 	uint64_t val;
9369 
9370 	mtx_lock(&sc->reg_lock);
9371 	if (hw_off_limits(sc))
9372 		rc = ENXIO;
9373 	else {
9374 		val = 0;
9375 		for (i = 0; i < sc->params.tp.lb_nchan; i++) {
9376 			val += t4_read_reg64(sc,
9377 			    t4_port_reg(sc, pi->tx_chan + i, reg));
9378 		}
9379 		rc = 0;
9380 	}
9381 	mtx_unlock(&sc->reg_lock);
9382 	if (rc == 0)
9383 		rc = sysctl_handle_64(oidp, &val, 0, req);
9384 	return (rc);
9385 }
9386 
9387 static int
9388 sysctl_temperature(SYSCTL_HANDLER_ARGS)
9389 {
9390 	struct adapter *sc = arg1;
9391 	int rc, t;
9392 	uint32_t param, val;
9393 
9394 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
9395 	if (rc)
9396 		return (rc);
9397 	if (!hw_all_ok(sc))
9398 		rc = ENXIO;
9399 	else {
9400 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9401 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9402 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
9403 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9404 	}
9405 	end_synchronized_op(sc, 0);
9406 	if (rc)
9407 		return (rc);
9408 
9409 	/* unknown is returned as 0 but we display -1 in that case */
9410 	t = val == 0 ? -1 : val;
9411 
9412 	rc = sysctl_handle_int(oidp, &t, 0, req);
9413 	return (rc);
9414 }
9415 
9416 static int
9417 sysctl_vdd(SYSCTL_HANDLER_ARGS)
9418 {
9419 	struct adapter *sc = arg1;
9420 	int rc;
9421 	uint32_t param, val;
9422 
9423 	if (sc->params.core_vdd == 0) {
9424 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9425 		    "t4vdd");
9426 		if (rc)
9427 			return (rc);
9428 		if (!hw_all_ok(sc))
9429 			rc = ENXIO;
9430 		else {
9431 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9432 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9433 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
9434 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
9435 			    &param, &val);
9436 		}
9437 		end_synchronized_op(sc, 0);
9438 		if (rc)
9439 			return (rc);
9440 		sc->params.core_vdd = val;
9441 	}
9442 
9443 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
9444 }
9445 
9446 static int
9447 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
9448 {
9449 	struct adapter *sc = arg1;
9450 	int rc, v;
9451 	uint32_t param, val;
9452 
9453 	v = sc->sensor_resets;
9454 	rc = sysctl_handle_int(oidp, &v, 0, req);
9455 	if (rc != 0 || req->newptr == NULL || v <= 0)
9456 		return (rc);
9457 
9458 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
9459 	    chip_id(sc) < CHELSIO_T5)
9460 		return (ENOTSUP);
9461 
9462 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
9463 	if (rc)
9464 		return (rc);
9465 	if (!hw_all_ok(sc))
9466 		rc = ENXIO;
9467 	else {
9468 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9469 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9470 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
9471 		val = 1;
9472 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9473 	}
9474 	end_synchronized_op(sc, 0);
9475 	if (rc == 0)
9476 		sc->sensor_resets++;
9477 	return (rc);
9478 }
9479 
9480 static int
9481 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
9482 {
9483 	struct adapter *sc = arg1;
9484 	struct sbuf *sb;
9485 	int rc;
9486 	uint32_t param, val;
9487 	uint8_t coreid = (uint8_t)arg2;
9488 
9489 	KASSERT(coreid < sc->params.ncores,
9490 	    ("%s: bad coreid %u\n", __func__, coreid));
9491 
9492 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
9493 	if (rc)
9494 		return (rc);
9495 	if (!hw_all_ok(sc))
9496 		rc = ENXIO;
9497 	else {
9498 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9499 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD) |
9500 		    V_FW_PARAMS_PARAM_Y(coreid);
9501 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9502 	}
9503 	end_synchronized_op(sc, 0);
9504 	if (rc)
9505 		return (rc);
9506 
9507 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9508 	if (sb == NULL)
9509 		return (ENOMEM);
9510 
9511 	if (val == 0xffffffff) {
9512 		/* Only debug and custom firmwares report load averages. */
9513 		sbuf_printf(sb, "not available");
9514 	} else {
9515 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
9516 		    (val >> 16) & 0xff);
9517 	}
9518 	rc = sbuf_finish(sb);
9519 	sbuf_delete(sb);
9520 
9521 	return (rc);
9522 }
9523 
9524 static int
9525 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
9526 {
9527 	struct adapter *sc = arg1;
9528 	struct sbuf *sb;
9529 	int rc, i;
9530 	uint16_t incr[NMTUS][NCCTRL_WIN];
9531 	static const char *dec_fac[] = {
9532 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
9533 		"0.9375"
9534 	};
9535 
9536 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9537 	if (sb == NULL)
9538 		return (ENOMEM);
9539 
9540 	rc = 0;
9541 	mtx_lock(&sc->reg_lock);
9542 	if (hw_off_limits(sc))
9543 		rc = ENXIO;
9544 	else
9545 		t4_read_cong_tbl(sc, incr);
9546 	mtx_unlock(&sc->reg_lock);
9547 	if (rc)
9548 		goto done;
9549 
9550 	for (i = 0; i < NCCTRL_WIN; ++i) {
9551 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
9552 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
9553 		    incr[5][i], incr[6][i], incr[7][i]);
9554 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
9555 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
9556 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
9557 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
9558 	}
9559 
9560 	rc = sbuf_finish(sb);
9561 done:
9562 	sbuf_delete(sb);
9563 	return (rc);
9564 }
9565 
9566 static int
9567 sysctl_cim_ibq(SYSCTL_HANDLER_ARGS)
9568 {
9569 	struct adapter *sc = arg1;
9570 	struct sbuf *sb;
9571 	int rc, i, n, qid, coreid;
9572 	uint32_t *buf, *p;
9573 
9574 	qid = arg2 & 0xffff;
9575 	coreid = arg2 >> 16;
9576 
9577 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_ibq,
9578 	    ("%s: bad ibq qid %d\n", __func__, qid));
9579 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9580 	    ("%s: bad coreid %d\n", __func__, coreid));
9581 
9582 	n = 4 * CIM_IBQ_SIZE;
9583 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9584 	mtx_lock(&sc->reg_lock);
9585 	if (hw_off_limits(sc))
9586 		rc = -ENXIO;
9587 	else
9588 		rc = t4_read_cim_ibq_core(sc, coreid, qid, buf, n);
9589 	mtx_unlock(&sc->reg_lock);
9590 	if (rc < 0) {
9591 		rc = -rc;
9592 		goto done;
9593 	}
9594 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9595 
9596 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9597 	if (sb == NULL) {
9598 		rc = ENOMEM;
9599 		goto done;
9600 	}
9601 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9602 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9603 		    p[2], p[3]);
9604 	rc = sbuf_finish(sb);
9605 	sbuf_delete(sb);
9606 done:
9607 	free(buf, M_CXGBE);
9608 	return (rc);
9609 }
9610 
9611 static int
9612 sysctl_cim_obq(SYSCTL_HANDLER_ARGS)
9613 {
9614 	struct adapter *sc = arg1;
9615 	struct sbuf *sb;
9616 	int rc, i, n, qid, coreid;
9617 	uint32_t *buf, *p;
9618 
9619 	qid = arg2 & 0xffff;
9620 	coreid = arg2 >> 16;
9621 
9622 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_obq,
9623 	    ("%s: bad obq qid %d\n", __func__, qid));
9624 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9625 	    ("%s: bad coreid %d\n", __func__, coreid));
9626 
9627 	n = 6 * CIM_OBQ_SIZE * 4;
9628 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9629 	mtx_lock(&sc->reg_lock);
9630 	if (hw_off_limits(sc))
9631 		rc = -ENXIO;
9632 	else
9633 		rc = t4_read_cim_obq_core(sc, coreid, qid, buf, n);
9634 	mtx_unlock(&sc->reg_lock);
9635 	if (rc < 0) {
9636 		rc = -rc;
9637 		goto done;
9638 	}
9639 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9640 
9641 	rc = sysctl_wire_old_buffer(req, 0);
9642 	if (rc != 0)
9643 		goto done;
9644 
9645 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9646 	if (sb == NULL) {
9647 		rc = ENOMEM;
9648 		goto done;
9649 	}
9650 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9651 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9652 		    p[2], p[3]);
9653 	rc = sbuf_finish(sb);
9654 	sbuf_delete(sb);
9655 done:
9656 	free(buf, M_CXGBE);
9657 	return (rc);
9658 }
9659 
9660 static void
9661 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9662 {
9663 	uint32_t *p;
9664 
9665 	sbuf_printf(sb, "Status   Data      PC%s",
9666 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9667 	    "     LS0Stat  LS0Addr             LS0Data");
9668 
9669 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9670 		if (cfg & F_UPDBGLACAPTPCONLY) {
9671 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9672 			    p[6], p[7]);
9673 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9674 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9675 			    p[4] & 0xff, p[5] >> 8);
9676 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9677 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9678 			    p[1] & 0xf, p[2] >> 4);
9679 		} else {
9680 			sbuf_printf(sb,
9681 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9682 			    "%08x%08x%08x%08x",
9683 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9684 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9685 			    p[6], p[7]);
9686 		}
9687 	}
9688 }
9689 
9690 static void
9691 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9692 {
9693 	uint32_t *p;
9694 
9695 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9696 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9697 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9698 
9699 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9700 		if (cfg & F_UPDBGLACAPTPCONLY) {
9701 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9702 			    p[3] & 0xff, p[2], p[1], p[0]);
9703 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9704 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9705 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9706 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9707 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9708 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9709 			    p[6] >> 16);
9710 		} else {
9711 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9712 			    "%08x %08x %08x %08x %08x %08x",
9713 			    (p[9] >> 16) & 0xff,
9714 			    p[9] & 0xffff, p[8] >> 16,
9715 			    p[8] & 0xffff, p[7] >> 16,
9716 			    p[7] & 0xffff, p[6] >> 16,
9717 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9718 		}
9719 	}
9720 }
9721 
9722 static int
9723 sbuf_cim_la(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
9724 {
9725 	uint32_t cfg, *buf;
9726 	int rc;
9727 
9728 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9729 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9730 	    M_ZERO | flags);
9731 	if (buf == NULL)
9732 		return (ENOMEM);
9733 
9734 	mtx_lock(&sc->reg_lock);
9735 	if (hw_off_limits(sc))
9736 		rc = ENXIO;
9737 	else {
9738 		rc = -t4_cim_read_core(sc, 1, coreid, A_UP_UP_DBG_LA_CFG, 1,
9739 		    &cfg);
9740 		if (rc == 0)
9741 			rc = -t4_cim_read_la_core(sc, coreid, buf, NULL);
9742 	}
9743 	mtx_unlock(&sc->reg_lock);
9744 	if (rc == 0) {
9745 		if (chip_id(sc) < CHELSIO_T6)
9746 			sbuf_cim_la4(sc, sb, buf, cfg);
9747 		else
9748 			sbuf_cim_la6(sc, sb, buf, cfg);
9749 	}
9750 	free(buf, M_CXGBE);
9751 	return (rc);
9752 }
9753 
9754 static int
9755 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9756 {
9757 	struct adapter *sc = arg1;
9758 	int coreid = arg2;
9759 	struct sbuf *sb;
9760 	int rc;
9761 
9762 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9763 	if (sb == NULL)
9764 		return (ENOMEM);
9765 
9766 	rc = sbuf_cim_la(sc, coreid, sb, M_WAITOK);
9767 	if (rc == 0)
9768 		rc = sbuf_finish(sb);
9769 	sbuf_delete(sb);
9770 	return (rc);
9771 }
9772 
9773 static void
9774 dump_cim_regs(struct adapter *sc)
9775 {
9776 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9777 	    device_get_nameunit(sc->dev),
9778 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9779 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9780 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9781 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9782 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9783 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9784 	    device_get_nameunit(sc->dev),
9785 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9786 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9787 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9788 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9789 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9790 }
9791 
9792 static void
9793 dump_cimla(struct adapter *sc)
9794 {
9795 	struct sbuf sb;
9796 	int rc;
9797 
9798 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9799 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9800 		    device_get_nameunit(sc->dev));
9801 		return;
9802 	}
9803 	rc = sbuf_cim_la(sc, 0, &sb, M_WAITOK);
9804 	if (rc == 0) {
9805 		rc = sbuf_finish(&sb);
9806 		if (rc == 0) {
9807 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9808 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9809 		}
9810 	}
9811 	sbuf_delete(&sb);
9812 }
9813 
9814 void
9815 t4_os_cim_err(struct adapter *sc)
9816 {
9817 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9818 }
9819 
9820 static int
9821 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9822 {
9823 	struct adapter *sc = arg1;
9824 	u_int i;
9825 	struct sbuf *sb;
9826 	uint32_t *buf, *p;
9827 	int rc;
9828 
9829 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9830 	if (sb == NULL)
9831 		return (ENOMEM);
9832 
9833 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9834 	    M_ZERO | M_WAITOK);
9835 
9836 	rc = 0;
9837 	mtx_lock(&sc->reg_lock);
9838 	if (hw_off_limits(sc))
9839 		rc = ENXIO;
9840 	else
9841 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9842 	mtx_unlock(&sc->reg_lock);
9843 	if (rc)
9844 		goto done;
9845 
9846 	p = buf;
9847 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9848 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9849 		    p[1], p[0]);
9850 	}
9851 
9852 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9853 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9854 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9855 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9856 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9857 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9858 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9859 		    p[0] & 1);
9860 	}
9861 	rc = sbuf_finish(sb);
9862 done:
9863 	sbuf_delete(sb);
9864 	free(buf, M_CXGBE);
9865 	return (rc);
9866 }
9867 
9868 static int
9869 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9870 {
9871 	struct adapter *sc = arg1;
9872 	u_int i;
9873 	struct sbuf *sb;
9874 	uint32_t *buf, *p;
9875 	int rc;
9876 
9877 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9878 	if (sb == NULL)
9879 		return (ENOMEM);
9880 
9881 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9882 	    M_ZERO | M_WAITOK);
9883 
9884 	rc = 0;
9885 	mtx_lock(&sc->reg_lock);
9886 	if (hw_off_limits(sc))
9887 		rc = ENXIO;
9888 	else
9889 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9890 	mtx_unlock(&sc->reg_lock);
9891 	if (rc)
9892 		goto done;
9893 
9894 	p = buf;
9895 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9896 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9897 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9898 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9899 		    p[4], p[3], p[2], p[1], p[0]);
9900 	}
9901 
9902 	sbuf_printf(sb, "\n\nCntl ID               Data");
9903 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9904 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9905 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9906 	}
9907 
9908 	rc = sbuf_finish(sb);
9909 done:
9910 	sbuf_delete(sb);
9911 	free(buf, M_CXGBE);
9912 	return (rc);
9913 }
9914 
9915 static int
9916 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9917 {
9918 	struct adapter *sc = arg1;
9919 	struct sbuf *sb;
9920 	int rc, i;
9921 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9922 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9923 	uint16_t thres[CIM_NUM_IBQ];
9924 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9925 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9926 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9927 	static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
9928 		"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
9929 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
9930 		"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
9931 	};
9932 
9933 	MPASS(chip_id(sc) < CHELSIO_T7);
9934 
9935 	cim_num_obq = sc->chip_params->cim_num_obq;
9936 	if (is_t4(sc)) {
9937 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9938 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9939 	} else {
9940 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9941 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9942 	}
9943 	nq = CIM_NUM_IBQ + cim_num_obq;
9944 
9945 	mtx_lock(&sc->reg_lock);
9946 	if (hw_off_limits(sc))
9947 		rc = ENXIO;
9948 	else {
9949 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9950 		if (rc == 0) {
9951 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9952 			    obq_wr);
9953 			if (rc == 0)
9954 				t4_read_cimq_cfg(sc, base, size, thres);
9955 		}
9956 	}
9957 	mtx_unlock(&sc->reg_lock);
9958 	if (rc)
9959 		return (rc);
9960 
9961 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9962 	if (sb == NULL)
9963 		return (ENOMEM);
9964 
9965 	sbuf_printf(sb,
9966 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9967 
9968 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9969 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9970 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9971 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9972 		    G_QUEREMFLITS(p[2]) * 16);
9973 	for ( ; i < nq; i++, p += 4, wr += 2)
9974 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9975 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9976 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9977 		    G_QUEREMFLITS(p[2]) * 16);
9978 
9979 	rc = sbuf_finish(sb);
9980 	sbuf_delete(sb);
9981 
9982 	return (rc);
9983 }
9984 
9985 static int
9986 sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS)
9987 {
9988 	struct adapter *sc = arg1;
9989 	u_int coreid = arg2;
9990 	struct sbuf *sb;
9991 	int rc, i;
9992 	u_int addr;
9993 	uint16_t base[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9994 	uint16_t size[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9995 	uint16_t thres[CIM_NUM_IBQ_T7];
9996 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T7], *wr = obq_wr;
9997 	uint32_t stat[4 * (CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7)], *p = stat;
9998 	static const char * const qname_ibq_t7[] = {
9999 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "SGE1", "NC-SI",
10000 		"RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5", "IPC6", "IPC7",
10001 	};
10002 	static const char * const qname_obq_t7[] = {
10003 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", "SGE0-RX",
10004 		"RSVD", "RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5",
10005 		"IPC6", "IPC7"
10006 	};
10007 	static const char * const qname_ibq_sec_t7[] = {
10008 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "RSVD", "RSVD",
10009 		"RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",	"RSVD", "RSVD",
10010 	};
10011 	static const char * const qname_obq_sec_t7[] = {
10012 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "RSVD", "SGE0-RX",
10013 		"RSVD", "RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",
10014 		"RSVD", "RSVD",
10015 	};
10016 
10017 	MPASS(chip_id(sc) >= CHELSIO_T7);
10018 
10019 	mtx_lock(&sc->reg_lock);
10020 	if (hw_off_limits(sc))
10021 		rc = ENXIO;
10022 	else {
10023 		rc = -t4_cim_read_core(sc, 1, coreid,
10024 		    A_T7_UP_IBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_IBQ_T7, stat);
10025 		if (rc != 0)
10026 			goto unlock;
10027 
10028 		rc = -t4_cim_read_core(sc, 1, coreid,
10029 		    A_T7_UP_OBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_OBQ_T7,
10030 		    &stat[4 * CIM_NUM_IBQ_T7]);
10031 		if (rc != 0)
10032 			goto unlock;
10033 
10034 		addr = A_T7_UP_OBQ_0_SHADOW_REALADDR;
10035 		for (i = 0; i < CIM_NUM_OBQ_T7 * 2; i++, addr += 8) {
10036 			rc = -t4_cim_read_core(sc, 1, coreid, addr, 1,
10037 			    &obq_wr[i]);
10038 			if (rc != 0)
10039 				goto unlock;
10040 		}
10041 		t4_read_cimq_cfg_core(sc, coreid, base, size, thres);
10042 	}
10043 unlock:
10044 	mtx_unlock(&sc->reg_lock);
10045 	if (rc)
10046 		return (rc);
10047 
10048 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
10049 	if (sb == NULL)
10050 		return (ENOMEM);
10051 
10052 	sbuf_printf(sb,
10053 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
10054 
10055 	for (i = 0; i < CIM_NUM_IBQ_T7; i++, p += 4) {
10056 		if (!size[i])
10057 			continue;
10058 
10059 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
10060 		    coreid == 0 ? qname_ibq_t7[i] : qname_ibq_sec_t7[i],
10061 		    base[i], size[i], thres[i], G_IBQRDADDR(p[0]) & 0xfff,
10062 		    G_IBQWRADDR(p[1]) & 0xfff, G_QUESOPCNT(p[3]),
10063 		    G_QUEEOPCNT(p[3]), G_T7_QUEREMFLITS(p[2]) * 16);
10064 	}
10065 
10066 	for ( ; i < CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7; i++, p += 4, wr += 2) {
10067 		if (!size[i])
10068 			continue;
10069 
10070 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u",
10071 		    coreid == 0 ? qname_obq_t7[i - CIM_NUM_IBQ_T7] :
10072 		    qname_obq_sec_t7[i - CIM_NUM_IBQ_T7],
10073 		    base[i], size[i], G_QUERDADDR(p[0]) & 0xfff,
10074 		    wr[0] << 1, G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
10075 		    G_T7_QUEREMFLITS(p[2]) * 16);
10076 	}
10077 
10078 	rc = sbuf_finish(sb);
10079 	sbuf_delete(sb);
10080 	return (rc);
10081 }
10082 
10083 static int
10084 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
10085 {
10086 	struct adapter *sc = arg1;
10087 	struct sbuf *sb;
10088 	int rc;
10089 	struct tp_cpl_stats stats;
10090 
10091 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10092 	if (sb == NULL)
10093 		return (ENOMEM);
10094 
10095 	rc = 0;
10096 	mtx_lock(&sc->reg_lock);
10097 	if (hw_off_limits(sc))
10098 		rc = ENXIO;
10099 	else
10100 		t4_tp_get_cpl_stats(sc, &stats, 0);
10101 	mtx_unlock(&sc->reg_lock);
10102 	if (rc)
10103 		goto done;
10104 
10105 	if (sc->chip_params->nchan > 2) {
10106 		sbuf_printf(sb, "                 channel 0  channel 1"
10107 		    "  channel 2  channel 3");
10108 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
10109 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
10110 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
10111 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
10112 	} else {
10113 		sbuf_printf(sb, "                 channel 0  channel 1");
10114 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
10115 		    stats.req[0], stats.req[1]);
10116 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
10117 		    stats.rsp[0], stats.rsp[1]);
10118 	}
10119 
10120 	rc = sbuf_finish(sb);
10121 done:
10122 	sbuf_delete(sb);
10123 	return (rc);
10124 }
10125 
10126 static int
10127 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
10128 {
10129 	struct adapter *sc = arg1;
10130 	struct sbuf *sb;
10131 	int rc;
10132 	struct tp_usm_stats stats;
10133 
10134 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10135 	if (sb == NULL)
10136 		return (ENOMEM);
10137 
10138 	rc = 0;
10139 	mtx_lock(&sc->reg_lock);
10140 	if (hw_off_limits(sc))
10141 		rc = ENXIO;
10142 	else
10143 		t4_get_usm_stats(sc, &stats, 1);
10144 	mtx_unlock(&sc->reg_lock);
10145 	if (rc == 0) {
10146 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
10147 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
10148 		sbuf_printf(sb, "Drops:  %u", stats.drops);
10149 		rc = sbuf_finish(sb);
10150 	}
10151 	sbuf_delete(sb);
10152 
10153 	return (rc);
10154 }
10155 
10156 static int
10157 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
10158 {
10159 	struct adapter *sc = arg1;
10160 	struct sbuf *sb;
10161 	int rc;
10162 	struct tp_tid_stats stats;
10163 
10164 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10165 	if (sb == NULL)
10166 		return (ENOMEM);
10167 
10168 	rc = 0;
10169 	mtx_lock(&sc->reg_lock);
10170 	if (hw_off_limits(sc))
10171 		rc = ENXIO;
10172 	else
10173 		t4_tp_get_tid_stats(sc, &stats, 1);
10174 	mtx_unlock(&sc->reg_lock);
10175 	if (rc == 0) {
10176 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
10177 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
10178 		sbuf_printf(sb, "Active:     %u\n", stats.act);
10179 		sbuf_printf(sb, "Passive:    %u", stats.pas);
10180 		rc = sbuf_finish(sb);
10181 	}
10182 	sbuf_delete(sb);
10183 
10184 	return (rc);
10185 }
10186 
10187 static const char * const devlog_level_strings[] = {
10188 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
10189 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
10190 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
10191 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
10192 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
10193 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
10194 };
10195 
10196 static const char * const devlog_facility_strings[] = {
10197 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
10198 	[FW_DEVLOG_FACILITY_CF]		= "CF",
10199 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
10200 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
10201 	[FW_DEVLOG_FACILITY_RES]	= "RES",
10202 	[FW_DEVLOG_FACILITY_HW]		= "HW",
10203 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
10204 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
10205 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
10206 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
10207 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
10208 	[FW_DEVLOG_FACILITY_VI]		= "VI",
10209 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
10210 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
10211 	[FW_DEVLOG_FACILITY_TM]		= "TM",
10212 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
10213 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
10214 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
10215 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
10216 	[FW_DEVLOG_FACILITY_RI]		= "RI",
10217 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
10218 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
10219 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
10220 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
10221 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
10222 };
10223 
10224 static int
10225 sbuf_devlog(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
10226 {
10227 	int i, j, rc, nentries, first = 0;
10228 	struct devlog_params *dparams = &sc->params.devlog;
10229 	struct fw_devlog_e *buf, *e;
10230 	uint32_t addr, size;
10231 	uint64_t ftstamp = UINT64_MAX;
10232 
10233 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10234 	    ("%s: bad coreid %d\n", __func__, coreid));
10235 
10236 	if (dparams->addr == 0)
10237 		return (ENXIO);
10238 
10239 	size = dparams->size / sc->params.ncores;
10240 	addr = dparams->addr + coreid * size;
10241 
10242 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
10243 	buf = malloc(size, M_CXGBE, M_ZERO | flags);
10244 	if (buf == NULL)
10245 		return (ENOMEM);
10246 
10247 	mtx_lock(&sc->reg_lock);
10248 	if (hw_off_limits(sc))
10249 		rc = ENXIO;
10250 	else
10251 		rc = read_via_memwin(sc, 1, addr, (void *)buf, size);
10252 	mtx_unlock(&sc->reg_lock);
10253 	if (rc != 0)
10254 		goto done;
10255 
10256 	nentries = size / sizeof(struct fw_devlog_e);
10257 	for (i = 0; i < nentries; i++) {
10258 		e = &buf[i];
10259 
10260 		if (e->timestamp == 0)
10261 			break;	/* end */
10262 
10263 		e->timestamp = be64toh(e->timestamp);
10264 		e->seqno = be32toh(e->seqno);
10265 		for (j = 0; j < 8; j++)
10266 			e->params[j] = be32toh(e->params[j]);
10267 
10268 		if (e->timestamp < ftstamp) {
10269 			ftstamp = e->timestamp;
10270 			first = i;
10271 		}
10272 	}
10273 
10274 	if (buf[first].timestamp == 0)
10275 		goto done;	/* nothing in the log */
10276 
10277 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
10278 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
10279 
10280 	i = first;
10281 	do {
10282 		e = &buf[i];
10283 		if (e->timestamp == 0)
10284 			break;	/* end */
10285 
10286 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
10287 		    e->seqno, e->timestamp,
10288 		    (e->level < nitems(devlog_level_strings) ?
10289 			devlog_level_strings[e->level] : "UNKNOWN"),
10290 		    (e->facility < nitems(devlog_facility_strings) ?
10291 			devlog_facility_strings[e->facility] : "UNKNOWN"));
10292 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
10293 		    e->params[2], e->params[3], e->params[4],
10294 		    e->params[5], e->params[6], e->params[7]);
10295 
10296 		if (++i == nentries)
10297 			i = 0;
10298 	} while (i != first);
10299 done:
10300 	free(buf, M_CXGBE);
10301 	return (rc);
10302 }
10303 
10304 static int
10305 sysctl_devlog(SYSCTL_HANDLER_ARGS)
10306 {
10307 	struct adapter *sc = arg1;
10308 	int rc, i, coreid = arg2;
10309 	struct sbuf *sb;
10310 
10311 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10312 	if (sb == NULL)
10313 		return (ENOMEM);
10314 	if (coreid == -1) {
10315 		/* -1 means all cores */
10316 		for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10317 			if (sc->params.ncores > 0)
10318 				sbuf_printf(sb, "=== CIM core %u ===\n", i);
10319 			rc = sbuf_devlog(sc, i, sb, M_WAITOK);
10320 		}
10321 	} else {
10322 		KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10323 		    ("%s: bad coreid %d\n", __func__, coreid));
10324 		rc = sbuf_devlog(sc, coreid, sb, M_WAITOK);
10325 	}
10326 	if (rc == 0)
10327 		rc = sbuf_finish(sb);
10328 	sbuf_delete(sb);
10329 	return (rc);
10330 }
10331 
10332 static void
10333 dump_devlog(struct adapter *sc)
10334 {
10335 	int rc, i;
10336 	struct sbuf sb;
10337 
10338 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
10339 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
10340 		    device_get_nameunit(sc->dev));
10341 		return;
10342 	}
10343 	for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10344 		if (sc->params.ncores > 0)
10345 			sbuf_printf(&sb, "=== CIM core %u ===\n", i);
10346 		rc = sbuf_devlog(sc, i, &sb, M_WAITOK);
10347 	}
10348 	if (rc == 0) {
10349 		sbuf_finish(&sb);
10350 		log(LOG_DEBUG, "%s: device log follows.\n%s",
10351 		    device_get_nameunit(sc->dev), sbuf_data(&sb));
10352 	}
10353 	sbuf_delete(&sb);
10354 }
10355 
10356 static int
10357 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
10358 {
10359 	struct adapter *sc = arg1;
10360 	struct sbuf *sb;
10361 	int rc;
10362 	struct tp_fcoe_stats stats[MAX_NCHAN];
10363 	int i, nchan = sc->chip_params->nchan;
10364 
10365 	rc = 0;
10366 	mtx_lock(&sc->reg_lock);
10367 	if (hw_off_limits(sc))
10368 		rc = ENXIO;
10369 	else {
10370 		for (i = 0; i < nchan; i++)
10371 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
10372 	}
10373 	mtx_unlock(&sc->reg_lock);
10374 	if (rc != 0)
10375 		return (rc);
10376 
10377 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10378 	if (sb == NULL)
10379 		return (ENOMEM);
10380 
10381 	if (nchan > 2) {
10382 		sbuf_printf(sb, "                   channel 0        channel 1"
10383 		    "        channel 2        channel 3");
10384 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
10385 		    stats[0].octets_ddp, stats[1].octets_ddp,
10386 		    stats[2].octets_ddp, stats[3].octets_ddp);
10387 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
10388 		    stats[0].frames_ddp, stats[1].frames_ddp,
10389 		    stats[2].frames_ddp, stats[3].frames_ddp);
10390 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
10391 		    stats[0].frames_drop, stats[1].frames_drop,
10392 		    stats[2].frames_drop, stats[3].frames_drop);
10393 	} else {
10394 		sbuf_printf(sb, "                   channel 0        channel 1");
10395 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
10396 		    stats[0].octets_ddp, stats[1].octets_ddp);
10397 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
10398 		    stats[0].frames_ddp, stats[1].frames_ddp);
10399 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
10400 		    stats[0].frames_drop, stats[1].frames_drop);
10401 	}
10402 
10403 	rc = sbuf_finish(sb);
10404 	sbuf_delete(sb);
10405 
10406 	return (rc);
10407 }
10408 
10409 static int
10410 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
10411 {
10412 	struct adapter *sc = arg1;
10413 	struct sbuf *sb;
10414 	int rc, i;
10415 	unsigned int map, kbps, ipg, mode;
10416 	unsigned int pace_tab[NTX_SCHED];
10417 
10418 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
10419 	if (sb == NULL)
10420 		return (ENOMEM);
10421 
10422 	mtx_lock(&sc->reg_lock);
10423 	if (hw_off_limits(sc)) {
10424 		mtx_unlock(&sc->reg_lock);
10425 		rc = ENXIO;
10426 		goto done;
10427 	}
10428 
10429 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
10430 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
10431 	t4_read_pace_tbl(sc, pace_tab);
10432 	mtx_unlock(&sc->reg_lock);
10433 
10434 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
10435 	    "Class IPG (0.1 ns)   Flow IPG (us)");
10436 
10437 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
10438 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
10439 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
10440 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
10441 		if (kbps)
10442 			sbuf_printf(sb, "%9u     ", kbps);
10443 		else
10444 			sbuf_printf(sb, " disabled     ");
10445 
10446 		if (ipg)
10447 			sbuf_printf(sb, "%13u        ", ipg);
10448 		else
10449 			sbuf_printf(sb, "     disabled        ");
10450 
10451 		if (pace_tab[i])
10452 			sbuf_printf(sb, "%10u", pace_tab[i]);
10453 		else
10454 			sbuf_printf(sb, "  disabled");
10455 	}
10456 	rc = sbuf_finish(sb);
10457 done:
10458 	sbuf_delete(sb);
10459 	return (rc);
10460 }
10461 
10462 static int
10463 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
10464 {
10465 	struct adapter *sc = arg1;
10466 	struct sbuf *sb;
10467 	int rc, i, j;
10468 	uint64_t *p0, *p1;
10469 	struct lb_port_stats s[2];
10470 	static const char *stat_name[] = {
10471 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
10472 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
10473 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
10474 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
10475 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
10476 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
10477 		"BG2FramesTrunc:", "BG3FramesTrunc:"
10478 	};
10479 
10480 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10481 	if (sb == NULL)
10482 		return (ENOMEM);
10483 
10484 	memset(s, 0, sizeof(s));
10485 
10486 	rc = 0;
10487 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
10488 		mtx_lock(&sc->reg_lock);
10489 		if (hw_off_limits(sc))
10490 			rc = ENXIO;
10491 		else {
10492 			t4_get_lb_stats(sc, i, &s[0]);
10493 			t4_get_lb_stats(sc, i + 1, &s[1]);
10494 		}
10495 		mtx_unlock(&sc->reg_lock);
10496 		if (rc != 0)
10497 			break;
10498 
10499 		p0 = &s[0].octets;
10500 		p1 = &s[1].octets;
10501 		sbuf_printf(sb, "%s                       Loopback %u"
10502 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
10503 
10504 		for (j = 0; j < nitems(stat_name); j++)
10505 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
10506 				   *p0++, *p1++);
10507 	}
10508 
10509 	if (rc == 0)
10510 		rc = sbuf_finish(sb);
10511 	sbuf_delete(sb);
10512 
10513 	return (rc);
10514 }
10515 
10516 static int
10517 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
10518 {
10519 	int rc = 0;
10520 	struct port_info *pi = arg1;
10521 	struct link_config *lc = &pi->link_cfg;
10522 	struct sbuf *sb;
10523 
10524 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
10525 	if (sb == NULL)
10526 		return (ENOMEM);
10527 
10528 	if (lc->link_ok || lc->link_down_rc == 255)
10529 		sbuf_printf(sb, "n/a");
10530 	else
10531 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
10532 
10533 	rc = sbuf_finish(sb);
10534 	sbuf_delete(sb);
10535 
10536 	return (rc);
10537 }
10538 
10539 struct mem_desc {
10540 	uint64_t base;
10541 	uint64_t limit;
10542 	u_int idx;
10543 };
10544 
10545 static int
10546 mem_desc_cmp(const void *a, const void *b)
10547 {
10548 	const uint64_t v1 = ((const struct mem_desc *)a)->base;
10549 	const uint64_t v2 = ((const struct mem_desc *)b)->base;
10550 
10551 	if (v1 < v2)
10552 		return (-1);
10553 	else if (v1 > v2)
10554 		return (1);
10555 
10556 	return (0);
10557 }
10558 
10559 static void
10560 mem_region_show(struct sbuf *sb, const char *name, uint64_t from, uint64_t to)
10561 {
10562 	uintmax_t size;
10563 
10564 	if (from == to)
10565 		return;
10566 
10567 	size = to - from + 1;
10568 	if (size == 0)
10569 		return;
10570 
10571 	if (from > UINT32_MAX || to > UINT32_MAX)
10572 		sbuf_printf(sb, "%-18s 0x%012jx-0x%012jx [%ju]\n", name,
10573 		    (uintmax_t)from, (uintmax_t)to, size);
10574 	else
10575 		sbuf_printf(sb, "%-18s 0x%08jx-0x%08jx [%ju]\n", name,
10576 		    (uintmax_t)from, (uintmax_t)to, size);
10577 }
10578 
10579 static int
10580 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
10581 {
10582 	struct adapter *sc = arg1;
10583 	struct sbuf *sb;
10584 	int rc, i, n, nchan;
10585 	uint32_t lo, hi, used, free, alloc;
10586 	static const char *memory[] = {
10587 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
10588 	};
10589 	static const char *region[] = {
10590 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
10591 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
10592 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
10593 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
10594 		"RQUDP region:", "PBL region:", "TXPBL region:",
10595 		"TLSKey region:", "RRQ region:", "NVMe STAG region:",
10596 		"NVMe RQ region:", "NVMe RXPBL region:", "NVMe TPT region:",
10597 		"NVMe TXPBL region:", "DBVFIFO region:", "ULPRX state:",
10598 		"ULPTX state:", "RoCE RRQ region:", "On-chip queues:",
10599 	};
10600 	struct mem_desc avail[4];
10601 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
10602 	struct mem_desc *md;
10603 
10604 	rc = sysctl_wire_old_buffer(req, 0);
10605 	if (rc != 0)
10606 		return (rc);
10607 
10608 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10609 	if (sb == NULL)
10610 		return (ENOMEM);
10611 
10612 	for (i = 0; i < nitems(mem); i++) {
10613 		mem[i].limit = 0;
10614 		mem[i].idx = i;
10615 	}
10616 
10617 	mtx_lock(&sc->reg_lock);
10618 	if (hw_off_limits(sc)) {
10619 		rc = ENXIO;
10620 		goto done;
10621 	}
10622 
10623 	/* Find and sort the populated memory ranges */
10624 	i = 0;
10625 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
10626 	if (lo & F_EDRAM0_ENABLE) {
10627 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
10628 		if (chip_id(sc) >= CHELSIO_T7) {
10629 			avail[i].base = (uint64_t)G_T7_EDRAM0_BASE(hi) << 20;
10630 			avail[i].limit = avail[i].base +
10631 			    (G_T7_EDRAM0_SIZE(hi) << 20);
10632 		} else {
10633 			avail[i].base = (uint64_t)G_EDRAM0_BASE(hi) << 20;
10634 			avail[i].limit = avail[i].base +
10635 			    (G_EDRAM0_SIZE(hi) << 20);
10636 		}
10637 		avail[i].idx = 0;
10638 		i++;
10639 	}
10640 	if (lo & F_EDRAM1_ENABLE) {
10641 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
10642 		if (chip_id(sc) >= CHELSIO_T7) {
10643 			avail[i].base = (uint64_t)G_T7_EDRAM1_BASE(hi) << 20;
10644 			avail[i].limit = avail[i].base +
10645 			    (G_T7_EDRAM1_SIZE(hi) << 20);
10646 		} else {
10647 			avail[i].base = (uint64_t)G_EDRAM1_BASE(hi) << 20;
10648 			avail[i].limit = avail[i].base +
10649 			    (G_EDRAM1_SIZE(hi) << 20);
10650 		}
10651 		avail[i].idx = 1;
10652 		i++;
10653 	}
10654 	if (lo & F_EXT_MEM_ENABLE) {
10655 		switch (chip_id(sc)) {
10656 		case CHELSIO_T4:
10657 		case CHELSIO_T6:
10658 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
10659 			avail[i].base = (uint64_t)G_EXT_MEM_BASE(hi) << 20;
10660 			avail[i].limit = avail[i].base +
10661 			    (G_EXT_MEM_SIZE(hi) << 20);
10662 			avail[i].idx = 2;
10663 			break;
10664 		case CHELSIO_T5:
10665 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10666 			avail[i].base = (uint64_t)G_EXT_MEM0_BASE(hi) << 20;
10667 			avail[i].limit = avail[i].base +
10668 			    (G_EXT_MEM0_SIZE(hi) << 20);
10669 			avail[i].idx = 3;	/* Call it MC0 for T5 */
10670 			break;
10671 		default:
10672 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10673 			avail[i].base = (uint64_t)G_T7_EXT_MEM0_BASE(hi) << 20;
10674 			avail[i].limit = avail[i].base +
10675 			    (G_T7_EXT_MEM0_SIZE(hi) << 20);
10676 			avail[i].idx = 3;	/* Call it MC0 for T7+ */
10677 			break;
10678 		}
10679 		i++;
10680 	}
10681 	if (lo & F_EXT_MEM1_ENABLE && !(lo & F_MC_SPLIT)) {
10682 		/* Only T5 and T7+ have 2 MCs. */
10683 		MPASS(is_t5(sc) || chip_id(sc) >= CHELSIO_T7);
10684 
10685 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10686 		if (chip_id(sc) >= CHELSIO_T7) {
10687 			avail[i].base = (uint64_t)G_T7_EXT_MEM1_BASE(hi) << 20;
10688 			avail[i].limit = avail[i].base +
10689 			    (G_T7_EXT_MEM1_SIZE(hi) << 20);
10690 		} else {
10691 			avail[i].base = (uint64_t)G_EXT_MEM1_BASE(hi) << 20;
10692 			avail[i].limit = avail[i].base +
10693 			    (G_EXT_MEM1_SIZE(hi) << 20);
10694 		}
10695 		avail[i].idx = 4;
10696 		i++;
10697 	}
10698 	if (lo & F_HMA_MUX) {
10699 		/* Only T6+ have HMA. */
10700 		MPASS(chip_id(sc) >= CHELSIO_T6);
10701 
10702 		if (chip_id(sc) >= CHELSIO_T7) {
10703 			hi = t4_read_reg(sc, A_MA_HOST_MEMORY_BAR);
10704 			avail[i].base = (uint64_t)G_HMATARGETBASE(hi) << 20;
10705 			avail[i].limit = avail[i].base +
10706 			    (G_T7_HMA_SIZE(hi) << 20);
10707 		} else {
10708 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10709 			avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
10710 			avail[i].limit = avail[i].base +
10711 			    (G_EXT_MEM1_SIZE(hi) << 20);
10712 		}
10713 		avail[i].idx = 5;
10714 		i++;
10715 	}
10716 	MPASS(i <= nitems(avail));
10717 	if (!i)                                    /* no memory available */
10718 		goto done;
10719 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
10720 
10721 	md = &mem[0];
10722 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
10723 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
10724 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
10725 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10726 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
10727 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
10728 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
10729 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
10730 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
10731 
10732 	/* the next few have explicit upper bounds */
10733 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
10734 	md->limit = md->base - 1 +
10735 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
10736 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
10737 	md++;
10738 
10739 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
10740 	md->limit = md->base - 1 +
10741 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
10742 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
10743 	md++;
10744 
10745 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10746 		if (chip_id(sc) <= CHELSIO_T5)
10747 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
10748 		else
10749 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
10750 		md->limit = 0;
10751 	} else {
10752 		md->base = 0;
10753 		md->idx = nitems(region);  /* hide it */
10754 	}
10755 	md++;
10756 
10757 #define ulp_region(reg) do {\
10758 		const u_int shift = chip_id(sc) >= CHELSIO_T7 ? 4 : 0; \
10759 		md->base = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT) << shift; \
10760 		md->limit = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT) << shift; \
10761 		md->limit += (1 << shift) - 1; \
10762 		md++; \
10763 	} while (0)
10764 
10765 #define	hide_ulp_region() do { \
10766 		md->base = 0; \
10767 		md->idx = nitems(region); \
10768 		md++; \
10769 	} while (0)
10770 
10771 	ulp_region(RX_ISCSI);
10772 	ulp_region(RX_TDDP);
10773 	ulp_region(TX_TPT);
10774 	ulp_region(RX_STAG);
10775 	ulp_region(RX_RQ);
10776 	if (chip_id(sc) < CHELSIO_T7)
10777 		ulp_region(RX_RQUDP);
10778 	else
10779 		hide_ulp_region();
10780 	ulp_region(RX_PBL);
10781 	ulp_region(TX_PBL);
10782 	if (chip_id(sc) >= CHELSIO_T6)
10783 		ulp_region(RX_TLS_KEY);
10784 	else
10785 		hide_ulp_region();
10786 	if (chip_id(sc) >= CHELSIO_T7) {
10787 		ulp_region(RX_RRQ);
10788 		ulp_region(RX_NVME_TCP_STAG);
10789 		ulp_region(RX_NVME_TCP_RQ);
10790 		ulp_region(RX_NVME_TCP_PBL);
10791 		ulp_region(TX_NVME_TCP_TPT);
10792 		ulp_region(TX_NVME_TCP_PBL);
10793 	} else {
10794 		hide_ulp_region();
10795 		hide_ulp_region();
10796 		hide_ulp_region();
10797 		hide_ulp_region();
10798 		hide_ulp_region();
10799 		hide_ulp_region();
10800 	}
10801 #undef ulp_region
10802 #undef hide_ulp_region
10803 
10804 	md->base = 0;
10805 	if (is_t4(sc))
10806 		md->idx = nitems(region);
10807 	else {
10808 		uint32_t size = 0;
10809 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
10810 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
10811 
10812 		if (is_t5(sc)) {
10813 			if (sge_ctrl & F_VFIFO_ENABLE)
10814 				size = fifo_size << 2;
10815 		} else
10816 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
10817 
10818 		if (size) {
10819 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10820 			md->limit = md->base + size - 1;
10821 		} else
10822 			md->idx = nitems(region);
10823 	}
10824 	md++;
10825 
10826 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10827 	md->limit = 0;
10828 	md++;
10829 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10830 	md->limit = 0;
10831 	md++;
10832 
10833 	if (chip_id(sc) >= CHELSIO_T7) {
10834 		t4_tp_pio_read(sc, &lo, 1, A_TP_ROCE_RRQ_BASE, false);
10835 		md->base = lo;
10836 	} else {
10837 		md->base = 0;
10838 		md->idx = nitems(region);
10839 	}
10840 	md++;
10841 
10842 	md->base = sc->vres.ocq.start;
10843 	if (sc->vres.ocq.size)
10844 		md->limit = md->base + sc->vres.ocq.size - 1;
10845 	else
10846 		md->idx = nitems(region);  /* hide it */
10847 	md++;
10848 
10849 	/* add any address-space holes, there can be up to 3 */
10850 	for (n = 0; n < i - 1; n++)
10851 		if (avail[n].limit < avail[n + 1].base)
10852 			(md++)->base = avail[n].limit;
10853 	if (avail[n].limit)
10854 		(md++)->base = avail[n].limit;
10855 
10856 	n = md - mem;
10857 	MPASS(n <= nitems(mem));
10858 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10859 
10860 	for (lo = 0; lo < i; lo++)
10861 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10862 				avail[lo].limit - 1);
10863 
10864 	sbuf_printf(sb, "\n");
10865 	for (i = 0; i < n; i++) {
10866 		if (mem[i].idx >= nitems(region))
10867 			continue;                        /* skip holes */
10868 		if (!mem[i].limit)
10869 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10870 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10871 				mem[i].limit);
10872 	}
10873 
10874 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10875 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10876 	if (hi != lo  - 1) {
10877 		sbuf_printf(sb, "\n");
10878 		mem_region_show(sb, "uP RAM:", lo, hi);
10879 	}
10880 
10881 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10882 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10883 	if (hi != lo  - 1)
10884 		mem_region_show(sb, "uP Extmem2:", lo, hi);
10885 
10886 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10887 	if (chip_id(sc) >= CHELSIO_T7)
10888 		nchan = 1 << G_T7_PMRXNUMCHN(lo);
10889 	else
10890 		nchan = lo & F_PMRXNUMCHN ? 2 : 1;
10891 	for (i = 0, free = 0; i < nchan; i++)
10892 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10893 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10894 		   G_PMRXMAXPAGE(lo), free,
10895 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10, nchan);
10896 
10897 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10898 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10899 	if (chip_id(sc) >= CHELSIO_T7)
10900 		nchan = 1 << G_T7_PMTXNUMCHN(lo);
10901 	else
10902 		nchan = 1 << G_PMTXNUMCHN(lo);
10903 	for (i = 0, free = 0; i < nchan; i++)
10904 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10905 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10906 		   G_PMTXMAXPAGE(lo), free,
10907 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10908 		   hi >= (1 << 20) ? 'M' : 'K', nchan);
10909 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10910 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10911 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10912 
10913 	for (i = 0; i < 4; i++) {
10914 		if (chip_id(sc) > CHELSIO_T5)
10915 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10916 		else
10917 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10918 		if (is_t5(sc)) {
10919 			used = G_T5_USED(lo);
10920 			alloc = G_T5_ALLOC(lo);
10921 		} else {
10922 			used = G_USED(lo);
10923 			alloc = G_ALLOC(lo);
10924 		}
10925 		/* For T6+ these are MAC buffer groups */
10926 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10927 		    i, used, alloc);
10928 	}
10929 	for (i = 0; i < sc->chip_params->nchan; i++) {
10930 		if (chip_id(sc) > CHELSIO_T5)
10931 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10932 		else
10933 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10934 		if (is_t5(sc)) {
10935 			used = G_T5_USED(lo);
10936 			alloc = G_T5_ALLOC(lo);
10937 		} else {
10938 			used = G_USED(lo);
10939 			alloc = G_ALLOC(lo);
10940 		}
10941 		/* For T6+ these are MAC buffer groups */
10942 		sbuf_printf(sb,
10943 		    "\nLoopback %d using %u pages out of %u allocated",
10944 		    i, used, alloc);
10945 	}
10946 done:
10947 	mtx_unlock(&sc->reg_lock);
10948 	if (rc == 0)
10949 		rc = sbuf_finish(sb);
10950 	sbuf_delete(sb);
10951 	return (rc);
10952 }
10953 
10954 static inline void
10955 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10956 {
10957 	*mask = x | y;
10958 	y = htobe64(y);
10959 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10960 }
10961 
10962 static int
10963 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10964 {
10965 	struct adapter *sc = arg1;
10966 	struct sbuf *sb;
10967 	int rc, i;
10968 
10969 	MPASS(chip_id(sc) <= CHELSIO_T5);
10970 
10971 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10972 	if (sb == NULL)
10973 		return (ENOMEM);
10974 
10975 	sbuf_printf(sb,
10976 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10977 	    "  VF              Replication             P0 P1 P2 P3  ML");
10978 	rc = 0;
10979 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10980 		uint64_t tcamx, tcamy, mask;
10981 		uint32_t cls_lo, cls_hi;
10982 		uint8_t addr[ETHER_ADDR_LEN];
10983 
10984 		mtx_lock(&sc->reg_lock);
10985 		if (hw_off_limits(sc))
10986 			rc = ENXIO;
10987 		else {
10988 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10989 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10990 		}
10991 		mtx_unlock(&sc->reg_lock);
10992 		if (rc != 0)
10993 			break;
10994 		if (tcamx & tcamy)
10995 			continue;
10996 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10997 		mtx_lock(&sc->reg_lock);
10998 		if (hw_off_limits(sc))
10999 			rc = ENXIO;
11000 		else {
11001 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11002 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11003 		}
11004 		mtx_unlock(&sc->reg_lock);
11005 		if (rc != 0)
11006 			break;
11007 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
11008 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
11009 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
11010 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
11011 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
11012 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
11013 
11014 		if (cls_lo & F_REPLICATE) {
11015 			struct fw_ldst_cmd ldst_cmd;
11016 
11017 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11018 			ldst_cmd.op_to_addrspace =
11019 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11020 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11021 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11022 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11023 			ldst_cmd.u.mps.rplc.fid_idx =
11024 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11025 				V_FW_LDST_CMD_IDX(i));
11026 
11027 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11028 			    "t4mps");
11029 			if (rc)
11030 				break;
11031 			if (hw_off_limits(sc))
11032 				rc = ENXIO;
11033 			else
11034 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11035 				    sizeof(ldst_cmd), &ldst_cmd);
11036 			end_synchronized_op(sc, 0);
11037 			if (rc != 0)
11038 				break;
11039 			else {
11040 				sbuf_printf(sb, " %08x %08x %08x %08x",
11041 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11042 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11043 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11044 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11045 			}
11046 		} else
11047 			sbuf_printf(sb, "%36s", "");
11048 
11049 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
11050 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
11051 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
11052 	}
11053 
11054 	if (rc)
11055 		(void) sbuf_finish(sb);
11056 	else
11057 		rc = sbuf_finish(sb);
11058 	sbuf_delete(sb);
11059 
11060 	return (rc);
11061 }
11062 
11063 static int
11064 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
11065 {
11066 	struct adapter *sc = arg1;
11067 	struct sbuf *sb;
11068 	int rc, i;
11069 
11070 	MPASS(chip_id(sc) == CHELSIO_T6);
11071 
11072 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11073 	if (sb == NULL)
11074 		return (ENOMEM);
11075 
11076 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11077 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11078 	    "                           Replication"
11079 	    "                                    P0 P1 P2 P3  ML");
11080 
11081 	rc = 0;
11082 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11083 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11084 		uint16_t ivlan;
11085 		uint64_t tcamx, tcamy, val, mask;
11086 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11087 		uint8_t addr[ETHER_ADDR_LEN];
11088 
11089 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
11090 		if (i < 256)
11091 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
11092 		else
11093 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
11094 		mtx_lock(&sc->reg_lock);
11095 		if (hw_off_limits(sc))
11096 			rc = ENXIO;
11097 		else {
11098 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11099 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11100 			tcamy = G_DMACH(val) << 32;
11101 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11102 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11103 		}
11104 		mtx_unlock(&sc->reg_lock);
11105 		if (rc != 0)
11106 			break;
11107 
11108 		lookup_type = G_DATALKPTYPE(data2);
11109 		port_num = G_DATAPORTNUM(data2);
11110 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11111 			/* Inner header VNI */
11112 			vniy = ((data2 & F_DATAVIDH2) << 23) |
11113 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11114 			dip_hit = data2 & F_DATADIPHIT;
11115 			vlan_vld = 0;
11116 		} else {
11117 			vniy = 0;
11118 			dip_hit = 0;
11119 			vlan_vld = data2 & F_DATAVIDH2;
11120 			ivlan = G_VIDL(val);
11121 		}
11122 
11123 		ctl |= V_CTLXYBITSEL(1);
11124 		mtx_lock(&sc->reg_lock);
11125 		if (hw_off_limits(sc))
11126 			rc = ENXIO;
11127 		else {
11128 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11129 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11130 			tcamx = G_DMACH(val) << 32;
11131 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11132 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11133 		}
11134 		mtx_unlock(&sc->reg_lock);
11135 		if (rc != 0)
11136 			break;
11137 
11138 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11139 			/* Inner header VNI mask */
11140 			vnix = ((data2 & F_DATAVIDH2) << 23) |
11141 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11142 		} else
11143 			vnix = 0;
11144 
11145 		if (tcamx & tcamy)
11146 			continue;
11147 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11148 
11149 		mtx_lock(&sc->reg_lock);
11150 		if (hw_off_limits(sc))
11151 			rc = ENXIO;
11152 		else {
11153 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11154 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11155 		}
11156 		mtx_unlock(&sc->reg_lock);
11157 		if (rc != 0)
11158 			break;
11159 
11160 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11161 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11162 			    "%012jx %06x %06x    -    -   %3c"
11163 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11164 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11165 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11166 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11167 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11168 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11169 		} else {
11170 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11171 			    "%012jx    -       -   ", i, addr[0], addr[1],
11172 			    addr[2], addr[3], addr[4], addr[5],
11173 			    (uintmax_t)mask);
11174 
11175 			if (vlan_vld)
11176 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11177 			else
11178 				sbuf_printf(sb, "  -    N     ");
11179 
11180 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11181 			    lookup_type ? 'I' : 'O', port_num,
11182 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11183 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11184 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11185 		}
11186 
11187 
11188 		if (cls_lo & F_T6_REPLICATE) {
11189 			struct fw_ldst_cmd ldst_cmd;
11190 
11191 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11192 			ldst_cmd.op_to_addrspace =
11193 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11194 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11195 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11196 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11197 			ldst_cmd.u.mps.rplc.fid_idx =
11198 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11199 				V_FW_LDST_CMD_IDX(i));
11200 
11201 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11202 			    "t6mps");
11203 			if (rc)
11204 				break;
11205 			if (hw_off_limits(sc))
11206 				rc = ENXIO;
11207 			else
11208 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11209 				    sizeof(ldst_cmd), &ldst_cmd);
11210 			end_synchronized_op(sc, 0);
11211 			if (rc != 0)
11212 				break;
11213 			else {
11214 				sbuf_printf(sb, " %08x %08x %08x %08x"
11215 				    " %08x %08x %08x %08x",
11216 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11217 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11218 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11219 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11220 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11221 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11222 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11223 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11224 			}
11225 		} else
11226 			sbuf_printf(sb, "%72s", "");
11227 
11228 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11229 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11230 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11231 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11232 	}
11233 
11234 	if (rc)
11235 		(void) sbuf_finish(sb);
11236 	else
11237 		rc = sbuf_finish(sb);
11238 	sbuf_delete(sb);
11239 
11240 	return (rc);
11241 }
11242 
11243 static int
11244 sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS)
11245 {
11246 	struct adapter *sc = arg1;
11247 	struct sbuf *sb;
11248 	int rc, i;
11249 
11250 	MPASS(chip_id(sc) >= CHELSIO_T7);
11251 
11252 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11253 	if (sb == NULL)
11254 		return (ENOMEM);
11255 
11256 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11257 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11258 	    "                           Replication"
11259 	    "                                    P0 P1 P2 P3  ML");
11260 
11261 	rc = 0;
11262 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11263 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11264 		uint16_t ivlan;
11265 		uint64_t tcamx, tcamy, val, mask;
11266 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11267 		uint8_t addr[ETHER_ADDR_LEN];
11268 
11269 		/* Read tcamy */
11270 		ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11271 		if (chip_rev(sc) == 0) {
11272 			if (i < 256)
11273 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11274 			else
11275 				ctl |= V_CTLTCAMINDEX(i - 256) | V_T7_CTLTCAMSEL(1);
11276 		} else {
11277 #if 0
11278 			ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11279 #endif
11280 			if (i < 512)
11281 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11282 			else if (i < 1024)
11283 				ctl |= V_CTLTCAMINDEX(i - 512) | V_T7_CTLTCAMSEL(1);
11284 			else
11285 				ctl |= V_CTLTCAMINDEX(i - 1024) | V_T7_CTLTCAMSEL(2);
11286 		}
11287 
11288 		mtx_lock(&sc->reg_lock);
11289 		if (hw_off_limits(sc))
11290 			rc = ENXIO;
11291 		else {
11292 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11293 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11294 			tcamy = G_DMACH(val) << 32;
11295 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11296 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11297 		}
11298 		mtx_unlock(&sc->reg_lock);
11299 		if (rc != 0)
11300 			break;
11301 
11302 		lookup_type = G_DATALKPTYPE(data2);
11303 		port_num = G_DATAPORTNUM(data2);
11304 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11305 			/* Inner header VNI */
11306 			vniy = (((data2 & F_DATAVIDH2) |
11307 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11308 			dip_hit = data2 & F_DATADIPHIT;
11309 			vlan_vld = 0;
11310 		} else {
11311 			vniy = 0;
11312 			dip_hit = 0;
11313 			vlan_vld = data2 & F_DATAVIDH2;
11314 			ivlan = G_VIDL(val);
11315 		}
11316 
11317 		ctl |= V_CTLXYBITSEL(1);
11318 		mtx_lock(&sc->reg_lock);
11319 		if (hw_off_limits(sc))
11320 			rc = ENXIO;
11321 		else {
11322 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11323 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11324 			tcamx = G_DMACH(val) << 32;
11325 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11326 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11327 		}
11328 		mtx_unlock(&sc->reg_lock);
11329 		if (rc != 0)
11330 			break;
11331 
11332 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11333 			/* Inner header VNI mask */
11334 			vnix = (((data2 & F_DATAVIDH2) |
11335 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11336 		} else
11337 			vnix = 0;
11338 
11339 		if (tcamx & tcamy)
11340 			continue;
11341 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11342 
11343 		mtx_lock(&sc->reg_lock);
11344 		if (hw_off_limits(sc))
11345 			rc = ENXIO;
11346 		else {
11347 			if (chip_rev(sc) == 0) {
11348 				cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11349 				cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11350 			} else {
11351 				t4_write_reg(sc, A_MPS_CLS_SRAM_H,
11352 				    V_SRAMWRN(0) | V_SRAMINDEX(i));
11353 				cls_lo = t4_read_reg(sc, A_MPS_CLS_SRAM_L);
11354 				cls_hi = t4_read_reg(sc, A_MPS_CLS_SRAM_H);
11355 			}
11356 		}
11357 		mtx_unlock(&sc->reg_lock);
11358 		if (rc != 0)
11359 			break;
11360 
11361 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11362 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11363 			    "%012jx %06x %06x    -    -   %3c"
11364 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11365 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11366 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11367 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11368 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11369 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11370 		} else {
11371 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11372 			    "%012jx    -       -   ", i, addr[0], addr[1],
11373 			    addr[2], addr[3], addr[4], addr[5],
11374 			    (uintmax_t)mask);
11375 
11376 			if (vlan_vld)
11377 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11378 			else
11379 				sbuf_printf(sb, "  -    N     ");
11380 
11381 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11382 			    lookup_type ? 'I' : 'O', port_num,
11383 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11384 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11385 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11386 		}
11387 
11388 		if (cls_lo & F_T6_REPLICATE) {
11389 			struct fw_ldst_cmd ldst_cmd;
11390 
11391 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11392 			ldst_cmd.op_to_addrspace =
11393 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11394 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11395 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11396 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11397 			ldst_cmd.u.mps.rplc.fid_idx =
11398 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11399 				V_FW_LDST_CMD_IDX(i));
11400 
11401 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11402 			    "t6mps");
11403 			if (rc)
11404 				break;
11405 			if (hw_off_limits(sc))
11406 				rc = ENXIO;
11407 			else
11408 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11409 				    sizeof(ldst_cmd), &ldst_cmd);
11410 			end_synchronized_op(sc, 0);
11411 			if (rc != 0)
11412 				break;
11413 			else {
11414 				sbuf_printf(sb, " %08x %08x %08x %08x"
11415 				    " %08x %08x %08x %08x",
11416 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11417 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11418 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11419 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11420 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11421 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11422 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11423 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11424 			}
11425 		} else
11426 			sbuf_printf(sb, "%72s", "");
11427 
11428 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11429 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11430 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11431 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11432 	}
11433 
11434 	if (rc)
11435 		(void) sbuf_finish(sb);
11436 	else
11437 		rc = sbuf_finish(sb);
11438 	sbuf_delete(sb);
11439 
11440 	return (rc);
11441 }
11442 
11443 static int
11444 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
11445 {
11446 	struct adapter *sc = arg1;
11447 	struct sbuf *sb;
11448 	int rc;
11449 	uint16_t mtus[NMTUS];
11450 
11451 	rc = 0;
11452 	mtx_lock(&sc->reg_lock);
11453 	if (hw_off_limits(sc))
11454 		rc = ENXIO;
11455 	else
11456 		t4_read_mtu_tbl(sc, mtus, NULL);
11457 	mtx_unlock(&sc->reg_lock);
11458 	if (rc != 0)
11459 		return (rc);
11460 
11461 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11462 	if (sb == NULL)
11463 		return (ENOMEM);
11464 
11465 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
11466 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
11467 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
11468 	    mtus[14], mtus[15]);
11469 
11470 	rc = sbuf_finish(sb);
11471 	sbuf_delete(sb);
11472 
11473 	return (rc);
11474 }
11475 
11476 static int
11477 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
11478 {
11479 	struct adapter *sc = arg1;
11480 	struct sbuf *sb;
11481 	int rc, i;
11482 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
11483 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
11484 	uint32_t stats[T7_PM_RX_CACHE_NSTATS];
11485 	static const char *tx_stats[MAX_PM_NSTATS] = {
11486 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
11487 		"Tx FIFO wait", NULL, "Tx latency"
11488 	};
11489 	static const char *rx_stats[MAX_PM_NSTATS] = {
11490 		"Read:", "Write bypass:", "Write mem:", "Flush:",
11491 		"Rx FIFO wait", NULL, "Rx latency"
11492 	};
11493 
11494 	rc = 0;
11495 	mtx_lock(&sc->reg_lock);
11496 	if (hw_off_limits(sc))
11497 		rc = ENXIO;
11498 	else {
11499 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
11500 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
11501 		if (chip_id(sc) >= CHELSIO_T7)
11502 			t4_pmrx_cache_get_stats(sc, stats);
11503 	}
11504 	mtx_unlock(&sc->reg_lock);
11505 	if (rc != 0)
11506 		return (rc);
11507 
11508 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11509 	if (sb == NULL)
11510 		return (ENOMEM);
11511 
11512 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
11513 	for (i = 0; i < 4; i++) {
11514 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11515 		    tx_cyc[i]);
11516 	}
11517 
11518 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
11519 	for (i = 0; i < 4; i++) {
11520 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11521 		    rx_cyc[i]);
11522 	}
11523 
11524 	if (chip_id(sc) > CHELSIO_T5) {
11525 		sbuf_printf(sb,
11526 		    "\n              Total wait      Total occupancy");
11527 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11528 		    tx_cyc[i]);
11529 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11530 		    rx_cyc[i]);
11531 
11532 		i += 2;
11533 		MPASS(i < nitems(tx_stats));
11534 
11535 		sbuf_printf(sb,
11536 		    "\n                   Reads           Total wait");
11537 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11538 		    tx_cyc[i]);
11539 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11540 		    rx_cyc[i]);
11541 	}
11542 
11543 	if (chip_id(sc) >= CHELSIO_T7) {
11544 		i = 0;
11545 		sbuf_printf(sb, "\n\nPM RX Cache Stats\n");
11546 		sbuf_printf(sb, "%-40s    %u\n", "ReqWrite", stats[i++]);
11547 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadInv", stats[i++]);
11548 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadNoInv", stats[i++]);
11549 		sbuf_printf(sb, "%-40s    %u\n", "Write Split Request",
11550 			   stats[i++]);
11551 		sbuf_printf(sb, "%-40s    %u\n",
11552 			   "Normal Read Split (Read Invalidate)", stats[i++]);
11553 		sbuf_printf(sb, "%-40s    %u\n",
11554 			   "Feedback Read Split (Read NoInvalidate)",
11555 			   stats[i++]);
11556 		sbuf_printf(sb, "%-40s    %u\n", "Write Hit", stats[i++]);
11557 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit",
11558 			   stats[i++]);
11559 		sbuf_printf(sb, "%-40s    %u\n", "Feedback Read Hit",
11560 			   stats[i++]);
11561 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full Avail",
11562 			   stats[i++]);
11563 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full UnAvail",
11564 			   stats[i++]);
11565 		sbuf_printf(sb, "%-40s    %u\n",
11566 			   "Normal Read Hit Partial Avail",
11567 			   stats[i++]);
11568 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full Avail",
11569 			   stats[i++]);
11570 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full UnAvail",
11571 			   stats[i++]);
11572 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Partial Avail",
11573 			   stats[i++]);
11574 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Full Free",
11575 			   stats[i++]);
11576 		sbuf_printf(sb, "%-40s    %u\n",
11577 			   "Normal Read Part-avail Mul-Regions",
11578 			   stats[i++]);
11579 		sbuf_printf(sb, "%-40s    %u\n",
11580 			   "FB Read Part-avail Mul-Regions",
11581 			   stats[i++]);
11582 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss FL Used",
11583 			   stats[i++]);
11584 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss LRU Used",
11585 			   stats[i++]);
11586 		sbuf_printf(sb, "%-40s    %u\n",
11587 			   "Write Miss LRU-Multiple Evict", stats[i++]);
11588 		sbuf_printf(sb, "%-40s    %u\n",
11589 			   "Write Hit Increasing Islands", stats[i++]);
11590 		sbuf_printf(sb, "%-40s    %u\n",
11591 			   "Normal Read Island Read split", stats[i++]);
11592 		sbuf_printf(sb, "%-40s    %u\n", "Write Overflow Eviction",
11593 			   stats[i++]);
11594 		sbuf_printf(sb, "%-40s    %u", "Read Overflow Eviction",
11595 			   stats[i++]);
11596 	}
11597 
11598 	rc = sbuf_finish(sb);
11599 	sbuf_delete(sb);
11600 
11601 	return (rc);
11602 }
11603 
11604 static int
11605 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
11606 {
11607 	struct adapter *sc = arg1;
11608 	struct sbuf *sb;
11609 	int rc;
11610 	struct tp_rdma_stats stats;
11611 
11612 	rc = 0;
11613 	mtx_lock(&sc->reg_lock);
11614 	if (hw_off_limits(sc))
11615 		rc = ENXIO;
11616 	else
11617 		t4_tp_get_rdma_stats(sc, &stats, 0);
11618 	mtx_unlock(&sc->reg_lock);
11619 	if (rc != 0)
11620 		return (rc);
11621 
11622 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11623 	if (sb == NULL)
11624 		return (ENOMEM);
11625 
11626 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
11627 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
11628 
11629 	rc = sbuf_finish(sb);
11630 	sbuf_delete(sb);
11631 
11632 	return (rc);
11633 }
11634 
11635 static int
11636 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
11637 {
11638 	struct adapter *sc = arg1;
11639 	struct sbuf *sb;
11640 	int rc;
11641 	struct tp_tcp_stats v4, v6;
11642 
11643 	rc = 0;
11644 	mtx_lock(&sc->reg_lock);
11645 	if (hw_off_limits(sc))
11646 		rc = ENXIO;
11647 	else
11648 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
11649 	mtx_unlock(&sc->reg_lock);
11650 	if (rc != 0)
11651 		return (rc);
11652 
11653 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11654 	if (sb == NULL)
11655 		return (ENOMEM);
11656 
11657 	sbuf_printf(sb,
11658 	    "                                IP                 IPv6\n");
11659 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
11660 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
11661 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
11662 	    v4.tcp_in_segs, v6.tcp_in_segs);
11663 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
11664 	    v4.tcp_out_segs, v6.tcp_out_segs);
11665 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
11666 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
11667 
11668 	rc = sbuf_finish(sb);
11669 	sbuf_delete(sb);
11670 
11671 	return (rc);
11672 }
11673 
11674 static int
11675 sysctl_tids(SYSCTL_HANDLER_ARGS)
11676 {
11677 	struct adapter *sc = arg1;
11678 	struct sbuf *sb;
11679 	int rc;
11680 	uint32_t x, y;
11681 	struct tid_info *t = &sc->tids;
11682 
11683 	rc = 0;
11684 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11685 	if (sb == NULL)
11686 		return (ENOMEM);
11687 
11688 	if (t->natids) {
11689 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
11690 		    t->atids_in_use);
11691 	}
11692 
11693 	if (t->nhpftids) {
11694 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
11695 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
11696 	}
11697 
11698 	if (t->ntids) {
11699 		bool hashen = false;
11700 
11701 		mtx_lock(&sc->reg_lock);
11702 		if (hw_off_limits(sc))
11703 			rc = ENXIO;
11704 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
11705 			hashen = true;
11706 			if (chip_id(sc) <= CHELSIO_T5) {
11707 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
11708 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
11709 			} else {
11710 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
11711 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
11712 			}
11713 		}
11714 		mtx_unlock(&sc->reg_lock);
11715 		if (rc != 0)
11716 			goto done;
11717 
11718 		sbuf_printf(sb, "TID range: ");
11719 		if (hashen) {
11720 			if (x)
11721 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
11722 			sbuf_printf(sb, "%u-%u", y, t->tid_base + t->ntids - 1);
11723 		} else {
11724 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
11725 			    t->ntids - 1);
11726 		}
11727 		sbuf_printf(sb, ", in use: %u\n",
11728 		    atomic_load_acq_int(&t->tids_in_use));
11729 	}
11730 
11731 	if (t->nstids) {
11732 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
11733 		    t->stid_base + t->nstids - 1, t->stids_in_use);
11734 	}
11735 
11736 	if (t->nftids) {
11737 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
11738 		    t->ftid_end, t->ftids_in_use);
11739 	}
11740 
11741 	if (t->netids) {
11742 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
11743 		    t->etid_base + t->netids - 1, t->etids_in_use);
11744 	}
11745 
11746 	mtx_lock(&sc->reg_lock);
11747 	if (hw_off_limits(sc))
11748 		rc = ENXIO;
11749 	else {
11750 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
11751 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
11752 	}
11753 	mtx_unlock(&sc->reg_lock);
11754 	if (rc != 0)
11755 		goto done;
11756 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
11757 done:
11758 	if (rc == 0)
11759 		rc = sbuf_finish(sb);
11760 	else
11761 		(void)sbuf_finish(sb);
11762 	sbuf_delete(sb);
11763 
11764 	return (rc);
11765 }
11766 
11767 static int
11768 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
11769 {
11770 	struct adapter *sc = arg1;
11771 	struct sbuf *sb;
11772 	int rc;
11773 	struct tp_err_stats stats;
11774 
11775 	rc = 0;
11776 	mtx_lock(&sc->reg_lock);
11777 	if (hw_off_limits(sc))
11778 		rc = ENXIO;
11779 	else
11780 		t4_tp_get_err_stats(sc, &stats, 0);
11781 	mtx_unlock(&sc->reg_lock);
11782 	if (rc != 0)
11783 		return (rc);
11784 
11785 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11786 	if (sb == NULL)
11787 		return (ENOMEM);
11788 
11789 	if (sc->chip_params->nchan > 2) {
11790 		sbuf_printf(sb, "                 channel 0  channel 1"
11791 		    "  channel 2  channel 3\n");
11792 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
11793 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
11794 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
11795 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
11796 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
11797 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
11798 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
11799 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
11800 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
11801 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
11802 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
11803 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
11804 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
11805 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
11806 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
11807 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
11808 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
11809 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
11810 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
11811 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
11812 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
11813 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
11814 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
11815 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
11816 	} else {
11817 		sbuf_printf(sb, "                 channel 0  channel 1\n");
11818 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
11819 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
11820 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
11821 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
11822 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
11823 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
11824 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
11825 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
11826 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
11827 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
11828 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
11829 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
11830 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
11831 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
11832 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
11833 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
11834 	}
11835 
11836 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
11837 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
11838 
11839 	rc = sbuf_finish(sb);
11840 	sbuf_delete(sb);
11841 
11842 	return (rc);
11843 }
11844 
11845 static int
11846 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
11847 {
11848 	struct adapter *sc = arg1;
11849 	struct sbuf *sb;
11850 	int rc;
11851 	struct tp_tnl_stats stats;
11852 
11853 	rc = 0;
11854 	mtx_lock(&sc->reg_lock);
11855 	if (hw_off_limits(sc))
11856 		rc = ENXIO;
11857 	else
11858 		t4_tp_get_tnl_stats(sc, &stats, 1);
11859 	mtx_unlock(&sc->reg_lock);
11860 	if (rc != 0)
11861 		return (rc);
11862 
11863 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11864 	if (sb == NULL)
11865 		return (ENOMEM);
11866 
11867 	if (sc->chip_params->nchan > 2) {
11868 		sbuf_printf(sb, "           channel 0  channel 1"
11869 		    "  channel 2  channel 3\n");
11870 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
11871 		    stats.out_pkt[0], stats.out_pkt[1],
11872 		    stats.out_pkt[2], stats.out_pkt[3]);
11873 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
11874 		    stats.in_pkt[0], stats.in_pkt[1],
11875 		    stats.in_pkt[2], stats.in_pkt[3]);
11876 	} else {
11877 		sbuf_printf(sb, "           channel 0  channel 1\n");
11878 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
11879 		    stats.out_pkt[0], stats.out_pkt[1]);
11880 		sbuf_printf(sb, "InPkts:   %10u %10u",
11881 		    stats.in_pkt[0], stats.in_pkt[1]);
11882 	}
11883 
11884 	rc = sbuf_finish(sb);
11885 	sbuf_delete(sb);
11886 
11887 	return (rc);
11888 }
11889 
11890 static int
11891 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
11892 {
11893 	struct adapter *sc = arg1;
11894 	struct tp_params *tpp = &sc->params.tp;
11895 	u_int mask;
11896 	int rc;
11897 
11898 	mask = tpp->la_mask >> 16;
11899 	rc = sysctl_handle_int(oidp, &mask, 0, req);
11900 	if (rc != 0 || req->newptr == NULL)
11901 		return (rc);
11902 	if (mask > 0xffff)
11903 		return (EINVAL);
11904 	mtx_lock(&sc->reg_lock);
11905 	if (hw_off_limits(sc))
11906 		rc = ENXIO;
11907 	else {
11908 		tpp->la_mask = mask << 16;
11909 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
11910 		    tpp->la_mask);
11911 	}
11912 	mtx_unlock(&sc->reg_lock);
11913 
11914 	return (rc);
11915 }
11916 
11917 struct field_desc {
11918 	const char *name;
11919 	u_int start;
11920 	u_int width;
11921 };
11922 
11923 static void
11924 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
11925 {
11926 	char buf[32];
11927 	int line_size = 0;
11928 
11929 	while (f->name) {
11930 		uint64_t mask = (1ULL << f->width) - 1;
11931 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
11932 		    ((uintmax_t)v >> f->start) & mask);
11933 
11934 		if (line_size + len >= 79) {
11935 			line_size = 8;
11936 			sbuf_printf(sb, "\n        ");
11937 		}
11938 		sbuf_printf(sb, "%s ", buf);
11939 		line_size += len + 1;
11940 		f++;
11941 	}
11942 	sbuf_printf(sb, "\n");
11943 }
11944 
11945 static const struct field_desc tp_la0[] = {
11946 	{ "RcfOpCodeOut", 60, 4 },
11947 	{ "State", 56, 4 },
11948 	{ "WcfState", 52, 4 },
11949 	{ "RcfOpcSrcOut", 50, 2 },
11950 	{ "CRxError", 49, 1 },
11951 	{ "ERxError", 48, 1 },
11952 	{ "SanityFailed", 47, 1 },
11953 	{ "SpuriousMsg", 46, 1 },
11954 	{ "FlushInputMsg", 45, 1 },
11955 	{ "FlushInputCpl", 44, 1 },
11956 	{ "RssUpBit", 43, 1 },
11957 	{ "RssFilterHit", 42, 1 },
11958 	{ "Tid", 32, 10 },
11959 	{ "InitTcb", 31, 1 },
11960 	{ "LineNumber", 24, 7 },
11961 	{ "Emsg", 23, 1 },
11962 	{ "EdataOut", 22, 1 },
11963 	{ "Cmsg", 21, 1 },
11964 	{ "CdataOut", 20, 1 },
11965 	{ "EreadPdu", 19, 1 },
11966 	{ "CreadPdu", 18, 1 },
11967 	{ "TunnelPkt", 17, 1 },
11968 	{ "RcfPeerFin", 16, 1 },
11969 	{ "RcfReasonOut", 12, 4 },
11970 	{ "TxCchannel", 10, 2 },
11971 	{ "RcfTxChannel", 8, 2 },
11972 	{ "RxEchannel", 6, 2 },
11973 	{ "RcfRxChannel", 5, 1 },
11974 	{ "RcfDataOutSrdy", 4, 1 },
11975 	{ "RxDvld", 3, 1 },
11976 	{ "RxOoDvld", 2, 1 },
11977 	{ "RxCongestion", 1, 1 },
11978 	{ "TxCongestion", 0, 1 },
11979 	{ NULL }
11980 };
11981 
11982 static const struct field_desc tp_la1[] = {
11983 	{ "CplCmdIn", 56, 8 },
11984 	{ "CplCmdOut", 48, 8 },
11985 	{ "ESynOut", 47, 1 },
11986 	{ "EAckOut", 46, 1 },
11987 	{ "EFinOut", 45, 1 },
11988 	{ "ERstOut", 44, 1 },
11989 	{ "SynIn", 43, 1 },
11990 	{ "AckIn", 42, 1 },
11991 	{ "FinIn", 41, 1 },
11992 	{ "RstIn", 40, 1 },
11993 	{ "DataIn", 39, 1 },
11994 	{ "DataInVld", 38, 1 },
11995 	{ "PadIn", 37, 1 },
11996 	{ "RxBufEmpty", 36, 1 },
11997 	{ "RxDdp", 35, 1 },
11998 	{ "RxFbCongestion", 34, 1 },
11999 	{ "TxFbCongestion", 33, 1 },
12000 	{ "TxPktSumSrdy", 32, 1 },
12001 	{ "RcfUlpType", 28, 4 },
12002 	{ "Eread", 27, 1 },
12003 	{ "Ebypass", 26, 1 },
12004 	{ "Esave", 25, 1 },
12005 	{ "Static0", 24, 1 },
12006 	{ "Cread", 23, 1 },
12007 	{ "Cbypass", 22, 1 },
12008 	{ "Csave", 21, 1 },
12009 	{ "CPktOut", 20, 1 },
12010 	{ "RxPagePoolFull", 18, 2 },
12011 	{ "RxLpbkPkt", 17, 1 },
12012 	{ "TxLpbkPkt", 16, 1 },
12013 	{ "RxVfValid", 15, 1 },
12014 	{ "SynLearned", 14, 1 },
12015 	{ "SetDelEntry", 13, 1 },
12016 	{ "SetInvEntry", 12, 1 },
12017 	{ "CpcmdDvld", 11, 1 },
12018 	{ "CpcmdSave", 10, 1 },
12019 	{ "RxPstructsFull", 8, 2 },
12020 	{ "EpcmdDvld", 7, 1 },
12021 	{ "EpcmdFlush", 6, 1 },
12022 	{ "EpcmdTrimPrefix", 5, 1 },
12023 	{ "EpcmdTrimPostfix", 4, 1 },
12024 	{ "ERssIp4Pkt", 3, 1 },
12025 	{ "ERssIp6Pkt", 2, 1 },
12026 	{ "ERssTcpUdpPkt", 1, 1 },
12027 	{ "ERssFceFipPkt", 0, 1 },
12028 	{ NULL }
12029 };
12030 
12031 static const struct field_desc tp_la2[] = {
12032 	{ "CplCmdIn", 56, 8 },
12033 	{ "MpsVfVld", 55, 1 },
12034 	{ "MpsPf", 52, 3 },
12035 	{ "MpsVf", 44, 8 },
12036 	{ "SynIn", 43, 1 },
12037 	{ "AckIn", 42, 1 },
12038 	{ "FinIn", 41, 1 },
12039 	{ "RstIn", 40, 1 },
12040 	{ "DataIn", 39, 1 },
12041 	{ "DataInVld", 38, 1 },
12042 	{ "PadIn", 37, 1 },
12043 	{ "RxBufEmpty", 36, 1 },
12044 	{ "RxDdp", 35, 1 },
12045 	{ "RxFbCongestion", 34, 1 },
12046 	{ "TxFbCongestion", 33, 1 },
12047 	{ "TxPktSumSrdy", 32, 1 },
12048 	{ "RcfUlpType", 28, 4 },
12049 	{ "Eread", 27, 1 },
12050 	{ "Ebypass", 26, 1 },
12051 	{ "Esave", 25, 1 },
12052 	{ "Static0", 24, 1 },
12053 	{ "Cread", 23, 1 },
12054 	{ "Cbypass", 22, 1 },
12055 	{ "Csave", 21, 1 },
12056 	{ "CPktOut", 20, 1 },
12057 	{ "RxPagePoolFull", 18, 2 },
12058 	{ "RxLpbkPkt", 17, 1 },
12059 	{ "TxLpbkPkt", 16, 1 },
12060 	{ "RxVfValid", 15, 1 },
12061 	{ "SynLearned", 14, 1 },
12062 	{ "SetDelEntry", 13, 1 },
12063 	{ "SetInvEntry", 12, 1 },
12064 	{ "CpcmdDvld", 11, 1 },
12065 	{ "CpcmdSave", 10, 1 },
12066 	{ "RxPstructsFull", 8, 2 },
12067 	{ "EpcmdDvld", 7, 1 },
12068 	{ "EpcmdFlush", 6, 1 },
12069 	{ "EpcmdTrimPrefix", 5, 1 },
12070 	{ "EpcmdTrimPostfix", 4, 1 },
12071 	{ "ERssIp4Pkt", 3, 1 },
12072 	{ "ERssIp6Pkt", 2, 1 },
12073 	{ "ERssTcpUdpPkt", 1, 1 },
12074 	{ "ERssFceFipPkt", 0, 1 },
12075 	{ NULL }
12076 };
12077 
12078 static void
12079 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
12080 {
12081 
12082 	field_desc_show(sb, *p, tp_la0);
12083 }
12084 
12085 static void
12086 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
12087 {
12088 
12089 	if (idx)
12090 		sbuf_printf(sb, "\n");
12091 	field_desc_show(sb, p[0], tp_la0);
12092 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12093 		field_desc_show(sb, p[1], tp_la0);
12094 }
12095 
12096 static void
12097 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
12098 {
12099 
12100 	if (idx)
12101 		sbuf_printf(sb, "\n");
12102 	field_desc_show(sb, p[0], tp_la0);
12103 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12104 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
12105 }
12106 
12107 static int
12108 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
12109 {
12110 	struct adapter *sc = arg1;
12111 	struct sbuf *sb;
12112 	uint64_t *buf, *p;
12113 	int rc;
12114 	u_int i, inc;
12115 	void (*show_func)(struct sbuf *, uint64_t *, int);
12116 
12117 	rc = 0;
12118 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12119 	if (sb == NULL)
12120 		return (ENOMEM);
12121 
12122 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
12123 
12124 	mtx_lock(&sc->reg_lock);
12125 	if (hw_off_limits(sc))
12126 		rc = ENXIO;
12127 	else {
12128 		t4_tp_read_la(sc, buf, NULL);
12129 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
12130 		case 2:
12131 			inc = 2;
12132 			show_func = tp_la_show2;
12133 			break;
12134 		case 3:
12135 			inc = 2;
12136 			show_func = tp_la_show3;
12137 			break;
12138 		default:
12139 			inc = 1;
12140 			show_func = tp_la_show;
12141 		}
12142 	}
12143 	mtx_unlock(&sc->reg_lock);
12144 	if (rc != 0)
12145 		goto done;
12146 
12147 	p = buf;
12148 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
12149 		(*show_func)(sb, p, i);
12150 	rc = sbuf_finish(sb);
12151 done:
12152 	sbuf_delete(sb);
12153 	free(buf, M_CXGBE);
12154 	return (rc);
12155 }
12156 
12157 static int
12158 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
12159 {
12160 	struct adapter *sc = arg1;
12161 	struct sbuf *sb;
12162 	int rc;
12163 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
12164 
12165 	rc = 0;
12166 	mtx_lock(&sc->reg_lock);
12167 	if (hw_off_limits(sc))
12168 		rc = ENXIO;
12169 	else
12170 		t4_get_chan_txrate(sc, nrate, orate);
12171 	mtx_unlock(&sc->reg_lock);
12172 	if (rc != 0)
12173 		return (rc);
12174 
12175 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
12176 	if (sb == NULL)
12177 		return (ENOMEM);
12178 
12179 	if (sc->chip_params->nchan > 2) {
12180 		sbuf_printf(sb, "              channel 0   channel 1"
12181 		    "   channel 2   channel 3\n");
12182 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
12183 		    nrate[0], nrate[1], nrate[2], nrate[3]);
12184 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
12185 		    orate[0], orate[1], orate[2], orate[3]);
12186 	} else {
12187 		sbuf_printf(sb, "              channel 0   channel 1\n");
12188 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
12189 		    nrate[0], nrate[1]);
12190 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
12191 		    orate[0], orate[1]);
12192 	}
12193 
12194 	rc = sbuf_finish(sb);
12195 	sbuf_delete(sb);
12196 
12197 	return (rc);
12198 }
12199 
12200 static int
12201 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
12202 {
12203 	struct adapter *sc = arg1;
12204 	struct sbuf *sb;
12205 	uint32_t *buf, *p;
12206 	int rc, i;
12207 
12208 	rc = 0;
12209 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12210 	if (sb == NULL)
12211 		return (ENOMEM);
12212 
12213 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
12214 	    M_ZERO | M_WAITOK);
12215 
12216 	mtx_lock(&sc->reg_lock);
12217 	if (hw_off_limits(sc))
12218 		rc = ENXIO;
12219 	else
12220 		t4_ulprx_read_la(sc, buf);
12221 	mtx_unlock(&sc->reg_lock);
12222 	if (rc != 0)
12223 		goto done;
12224 
12225 	p = buf;
12226 	sbuf_printf(sb, "      Pcmd        Type   Message"
12227 	    "                Data");
12228 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
12229 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
12230 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
12231 	}
12232 	rc = sbuf_finish(sb);
12233 done:
12234 	sbuf_delete(sb);
12235 	free(buf, M_CXGBE);
12236 	return (rc);
12237 }
12238 
12239 static int
12240 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
12241 {
12242 	struct adapter *sc = arg1;
12243 	struct sbuf *sb;
12244 	int rc;
12245 	uint32_t cfg, s1, s2;
12246 
12247 	MPASS(chip_id(sc) >= CHELSIO_T5);
12248 
12249 	rc = 0;
12250 	mtx_lock(&sc->reg_lock);
12251 	if (hw_off_limits(sc))
12252 		rc = ENXIO;
12253 	else {
12254 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
12255 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
12256 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
12257 	}
12258 	mtx_unlock(&sc->reg_lock);
12259 	if (rc != 0)
12260 		return (rc);
12261 
12262 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12263 	if (sb == NULL)
12264 		return (ENOMEM);
12265 
12266 	if (G_STATSOURCE_T5(cfg) == 7) {
12267 		int mode;
12268 
12269 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
12270 		if (mode == 0)
12271 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
12272 		else if (mode == 1)
12273 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
12274 		else
12275 			sbuf_printf(sb, "unknown mode %d", mode);
12276 	}
12277 	rc = sbuf_finish(sb);
12278 	sbuf_delete(sb);
12279 
12280 	return (rc);
12281 }
12282 
12283 static int
12284 sysctl_cpus(SYSCTL_HANDLER_ARGS)
12285 {
12286 	struct adapter *sc = arg1;
12287 	enum cpu_sets op = arg2;
12288 	cpuset_t cpuset;
12289 	struct sbuf *sb;
12290 	int i, rc;
12291 
12292 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
12293 
12294 	CPU_ZERO(&cpuset);
12295 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
12296 	if (rc != 0)
12297 		return (rc);
12298 
12299 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12300 	if (sb == NULL)
12301 		return (ENOMEM);
12302 
12303 	CPU_FOREACH(i)
12304 		sbuf_printf(sb, "%d ", i);
12305 	rc = sbuf_finish(sb);
12306 	sbuf_delete(sb);
12307 
12308 	return (rc);
12309 }
12310 
12311 static int
12312 sysctl_reset(SYSCTL_HANDLER_ARGS)
12313 {
12314 	struct adapter *sc = arg1;
12315 	u_int val;
12316 	int rc;
12317 
12318 	val = atomic_load_int(&sc->num_resets);
12319 	rc = sysctl_handle_int(oidp, &val, 0, req);
12320 	if (rc != 0 || req->newptr == NULL)
12321 		return (rc);
12322 
12323 	if (val == 0) {
12324 		/* Zero out the counter that tracks reset. */
12325 		atomic_store_int(&sc->num_resets, 0);
12326 		return (0);
12327 	}
12328 
12329 	if (val != 1)
12330 		return (EINVAL);	/* 0 or 1 are the only legal values */
12331 
12332 	if (hw_off_limits(sc))		/* harmless race */
12333 		return (EALREADY);
12334 
12335 	taskqueue_enqueue(reset_tq, &sc->reset_task);
12336 	return (0);
12337 }
12338 
12339 static int
12340 sysctl_tcb_cache(SYSCTL_HANDLER_ARGS)
12341 {
12342 	struct adapter *sc = arg1;
12343 	u_int val, v;
12344 	int rc;
12345 
12346 	mtx_lock(&sc->reg_lock);
12347 	if (hw_off_limits(sc)) {
12348 		rc = ENXIO;
12349 		goto done;
12350 	}
12351 	t4_tp_pio_read(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12352 	mtx_unlock(&sc->reg_lock);
12353 
12354 	val = v & F_GLFL ? 0 : 1;
12355 	rc = sysctl_handle_int(oidp, &val, 0, req);
12356 	if (rc != 0 || req->newptr == NULL)
12357 		return (rc);
12358 	if (val == 0)
12359 		v |= F_GLFL;
12360 	else
12361 		v &= ~F_GLFL;
12362 
12363 	mtx_lock(&sc->reg_lock);
12364 	if (hw_off_limits(sc))
12365 		rc = ENXIO;
12366 	else
12367 		t4_tp_pio_write(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12368 done:
12369 	mtx_unlock(&sc->reg_lock);
12370 	return (rc);
12371 }
12372 
12373 #ifdef TCP_OFFLOAD
12374 static int
12375 sysctl_tls(SYSCTL_HANDLER_ARGS)
12376 {
12377 	struct adapter *sc = arg1;
12378 	int i, j, v, rc;
12379 	struct vi_info *vi;
12380 
12381 	v = sc->tt.tls;
12382 	rc = sysctl_handle_int(oidp, &v, 0, req);
12383 	if (rc != 0 || req->newptr == NULL)
12384 		return (rc);
12385 
12386 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
12387 		return (ENOTSUP);
12388 
12389 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
12390 	if (rc)
12391 		return (rc);
12392 	if (hw_off_limits(sc))
12393 		rc = ENXIO;
12394 	else {
12395 		sc->tt.tls = !!v;
12396 		for_each_port(sc, i) {
12397 			for_each_vi(sc->port[i], j, vi) {
12398 				if (vi->flags & VI_INIT_DONE)
12399 					t4_update_fl_bufsize(vi->ifp);
12400 			}
12401 		}
12402 	}
12403 	end_synchronized_op(sc, 0);
12404 
12405 	return (rc);
12406 
12407 }
12408 
12409 static void
12410 unit_conv(char *buf, size_t len, u_int val, u_int factor)
12411 {
12412 	u_int rem = val % factor;
12413 
12414 	if (rem == 0)
12415 		snprintf(buf, len, "%u", val / factor);
12416 	else {
12417 		while (rem % 10 == 0)
12418 			rem /= 10;
12419 		snprintf(buf, len, "%u.%u", val / factor, rem);
12420 	}
12421 }
12422 
12423 static int
12424 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
12425 {
12426 	struct adapter *sc = arg1;
12427 	char buf[16];
12428 	u_int res, re;
12429 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12430 
12431 	mtx_lock(&sc->reg_lock);
12432 	if (hw_off_limits(sc))
12433 		res = (u_int)-1;
12434 	else
12435 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
12436 	mtx_unlock(&sc->reg_lock);
12437 	if (res == (u_int)-1)
12438 		return (ENXIO);
12439 
12440 	switch (arg2) {
12441 	case 0:
12442 		/* timer_tick */
12443 		re = G_TIMERRESOLUTION(res);
12444 		break;
12445 	case 1:
12446 		/* TCP timestamp tick */
12447 		re = G_TIMESTAMPRESOLUTION(res);
12448 		break;
12449 	case 2:
12450 		/* DACK tick */
12451 		re = G_DELAYEDACKRESOLUTION(res);
12452 		break;
12453 	default:
12454 		return (EDOOFUS);
12455 	}
12456 
12457 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
12458 
12459 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
12460 }
12461 
12462 static int
12463 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
12464 {
12465 	struct adapter *sc = arg1;
12466 	int rc;
12467 	u_int dack_tmr, dack_re, v;
12468 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12469 
12470 	mtx_lock(&sc->reg_lock);
12471 	if (hw_off_limits(sc))
12472 		rc = ENXIO;
12473 	else {
12474 		rc = 0;
12475 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
12476 		    A_TP_TIMER_RESOLUTION));
12477 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
12478 	}
12479 	mtx_unlock(&sc->reg_lock);
12480 	if (rc != 0)
12481 		return (rc);
12482 
12483 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
12484 
12485 	return (sysctl_handle_int(oidp, &v, 0, req));
12486 }
12487 
12488 static int
12489 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
12490 {
12491 	struct adapter *sc = arg1;
12492 	int rc, reg = arg2;
12493 	u_int tre;
12494 	u_long tp_tick_us, v;
12495 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12496 
12497 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
12498 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
12499 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
12500 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
12501 
12502 	mtx_lock(&sc->reg_lock);
12503 	if (hw_off_limits(sc))
12504 		rc = ENXIO;
12505 	else {
12506 		rc = 0;
12507 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
12508 		tp_tick_us = (cclk_ps << tre) / 1000000;
12509 		if (reg == A_TP_INIT_SRTT)
12510 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
12511 		else
12512 			v = tp_tick_us * t4_read_reg(sc, reg);
12513 	}
12514 	mtx_unlock(&sc->reg_lock);
12515 	if (rc != 0)
12516 		return (rc);
12517 	else
12518 		return (sysctl_handle_long(oidp, &v, 0, req));
12519 }
12520 
12521 /*
12522  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
12523  * passed to this function.
12524  */
12525 static int
12526 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
12527 {
12528 	struct adapter *sc = arg1;
12529 	int rc, idx = arg2;
12530 	u_int v;
12531 
12532 	MPASS(idx >= 0 && idx <= 24);
12533 
12534 	mtx_lock(&sc->reg_lock);
12535 	if (hw_off_limits(sc))
12536 		rc = ENXIO;
12537 	else {
12538 		rc = 0;
12539 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
12540 	}
12541 	mtx_unlock(&sc->reg_lock);
12542 	if (rc != 0)
12543 		return (rc);
12544 	else
12545 		return (sysctl_handle_int(oidp, &v, 0, req));
12546 }
12547 
12548 static int
12549 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
12550 {
12551 	struct adapter *sc = arg1;
12552 	int rc, idx = arg2;
12553 	u_int shift, v, r;
12554 
12555 	MPASS(idx >= 0 && idx < 16);
12556 
12557 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
12558 	shift = (idx & 3) << 3;
12559 	mtx_lock(&sc->reg_lock);
12560 	if (hw_off_limits(sc))
12561 		rc = ENXIO;
12562 	else {
12563 		rc = 0;
12564 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
12565 	}
12566 	mtx_unlock(&sc->reg_lock);
12567 	if (rc != 0)
12568 		return (rc);
12569 	else
12570 		return (sysctl_handle_int(oidp, &v, 0, req));
12571 }
12572 
12573 static int
12574 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
12575 {
12576 	struct vi_info *vi = arg1;
12577 	struct adapter *sc = vi->adapter;
12578 	int idx, rc, i;
12579 	struct sge_ofld_rxq *ofld_rxq;
12580 	uint8_t v;
12581 
12582 	idx = vi->ofld_tmr_idx;
12583 
12584 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12585 	if (rc != 0 || req->newptr == NULL)
12586 		return (rc);
12587 
12588 	if (idx < 0 || idx >= SGE_NTIMERS)
12589 		return (EINVAL);
12590 
12591 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12592 	    "t4otmr");
12593 	if (rc)
12594 		return (rc);
12595 
12596 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
12597 	for_each_ofld_rxq(vi, i, ofld_rxq) {
12598 #ifdef atomic_store_rel_8
12599 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
12600 #else
12601 		ofld_rxq->iq.intr_params = v;
12602 #endif
12603 	}
12604 	vi->ofld_tmr_idx = idx;
12605 
12606 	end_synchronized_op(sc, LOCK_HELD);
12607 	return (0);
12608 }
12609 
12610 static int
12611 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
12612 {
12613 	struct vi_info *vi = arg1;
12614 	struct adapter *sc = vi->adapter;
12615 	int idx, rc;
12616 
12617 	idx = vi->ofld_pktc_idx;
12618 
12619 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12620 	if (rc != 0 || req->newptr == NULL)
12621 		return (rc);
12622 
12623 	if (idx < -1 || idx >= SGE_NCOUNTERS)
12624 		return (EINVAL);
12625 
12626 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12627 	    "t4opktc");
12628 	if (rc)
12629 		return (rc);
12630 
12631 	if (vi->flags & VI_INIT_DONE)
12632 		rc = EBUSY; /* cannot be changed once the queues are created */
12633 	else
12634 		vi->ofld_pktc_idx = idx;
12635 
12636 	end_synchronized_op(sc, LOCK_HELD);
12637 	return (rc);
12638 }
12639 #endif
12640 
12641 static int
12642 get_sge_context(struct adapter *sc, int mem_id, uint32_t cid, int len,
12643     uint32_t *data)
12644 {
12645 	int rc;
12646 
12647 	if (len < sc->chip_params->sge_ctxt_size)
12648 		return (ENOBUFS);
12649 	if (cid > M_CTXTQID)
12650 		return (EINVAL);
12651 	if (mem_id != CTXT_EGRESS && mem_id != CTXT_INGRESS &&
12652 	    mem_id != CTXT_FLM && mem_id != CTXT_CNM)
12653 		return (EINVAL);
12654 
12655 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
12656 	if (rc)
12657 		return (rc);
12658 
12659 	if (hw_off_limits(sc)) {
12660 		rc = ENXIO;
12661 		goto done;
12662 	}
12663 
12664 	if (sc->flags & FW_OK && !is_t7(sc)) {
12665 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cid, mem_id, data);
12666 		if (rc == 0)
12667 			goto done;
12668 	}
12669 
12670 	/*
12671 	 * Read via firmware failed or wasn't even attempted.  Read directly via
12672 	 * the backdoor.
12673 	 */
12674 	rc = -t4_sge_ctxt_rd_bd(sc, cid, mem_id, data);
12675 done:
12676 	end_synchronized_op(sc, 0);
12677 	return (rc);
12678 }
12679 
12680 static int
12681 load_fw(struct adapter *sc, struct t4_data *fw)
12682 {
12683 	int rc;
12684 	uint8_t *fw_data;
12685 
12686 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
12687 	if (rc)
12688 		return (rc);
12689 
12690 	if (hw_off_limits(sc)) {
12691 		rc = ENXIO;
12692 		goto done;
12693 	}
12694 
12695 	/*
12696 	 * The firmware, with the sole exception of the memory parity error
12697 	 * handler, runs from memory and not flash.  It is almost always safe to
12698 	 * install a new firmware on a running system.  Just set bit 1 in
12699 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
12700 	 */
12701 	if (sc->flags & FULL_INIT_DONE &&
12702 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
12703 		rc = EBUSY;
12704 		goto done;
12705 	}
12706 
12707 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
12708 
12709 	rc = copyin(fw->data, fw_data, fw->len);
12710 	if (rc == 0)
12711 		rc = -t4_load_fw(sc, fw_data, fw->len);
12712 
12713 	free(fw_data, M_CXGBE);
12714 done:
12715 	end_synchronized_op(sc, 0);
12716 	return (rc);
12717 }
12718 
12719 static int
12720 load_cfg(struct adapter *sc, struct t4_data *cfg)
12721 {
12722 	int rc;
12723 	uint8_t *cfg_data = NULL;
12724 
12725 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12726 	if (rc)
12727 		return (rc);
12728 
12729 	if (hw_off_limits(sc)) {
12730 		rc = ENXIO;
12731 		goto done;
12732 	}
12733 
12734 	if (cfg->len == 0) {
12735 		/* clear */
12736 		rc = -t4_load_cfg(sc, NULL, 0);
12737 		goto done;
12738 	}
12739 
12740 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
12741 
12742 	rc = copyin(cfg->data, cfg_data, cfg->len);
12743 	if (rc == 0)
12744 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
12745 
12746 	free(cfg_data, M_CXGBE);
12747 done:
12748 	end_synchronized_op(sc, 0);
12749 	return (rc);
12750 }
12751 
12752 static int
12753 load_boot(struct adapter *sc, struct t4_bootrom *br)
12754 {
12755 	int rc;
12756 	uint8_t *br_data = NULL;
12757 	u_int offset;
12758 
12759 	if (br->len > 1024 * 1024)
12760 		return (EFBIG);
12761 
12762 	if (br->pf_offset == 0) {
12763 		/* pfidx */
12764 		if (br->pfidx_addr > 7)
12765 			return (EINVAL);
12766 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
12767 		    A_PCIE_PF_EXPROM_OFST)));
12768 	} else if (br->pf_offset == 1) {
12769 		/* offset */
12770 		offset = G_OFFSET(br->pfidx_addr);
12771 	} else {
12772 		return (EINVAL);
12773 	}
12774 
12775 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
12776 	if (rc)
12777 		return (rc);
12778 
12779 	if (hw_off_limits(sc)) {
12780 		rc = ENXIO;
12781 		goto done;
12782 	}
12783 
12784 	if (br->len == 0) {
12785 		/* clear */
12786 		rc = -t4_load_boot(sc, NULL, offset, 0);
12787 		goto done;
12788 	}
12789 
12790 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
12791 
12792 	rc = copyin(br->data, br_data, br->len);
12793 	if (rc == 0)
12794 		rc = -t4_load_boot(sc, br_data, offset, br->len);
12795 
12796 	free(br_data, M_CXGBE);
12797 done:
12798 	end_synchronized_op(sc, 0);
12799 	return (rc);
12800 }
12801 
12802 static int
12803 load_bootcfg(struct adapter *sc, struct t4_data *bc)
12804 {
12805 	int rc;
12806 	uint8_t *bc_data = NULL;
12807 
12808 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12809 	if (rc)
12810 		return (rc);
12811 
12812 	if (hw_off_limits(sc)) {
12813 		rc = ENXIO;
12814 		goto done;
12815 	}
12816 
12817 	if (bc->len == 0) {
12818 		/* clear */
12819 		rc = -t4_load_bootcfg(sc, NULL, 0);
12820 		goto done;
12821 	}
12822 
12823 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
12824 
12825 	rc = copyin(bc->data, bc_data, bc->len);
12826 	if (rc == 0)
12827 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
12828 
12829 	free(bc_data, M_CXGBE);
12830 done:
12831 	end_synchronized_op(sc, 0);
12832 	return (rc);
12833 }
12834 
12835 static int
12836 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
12837 {
12838 	int rc;
12839 	struct cudbg_init *cudbg;
12840 	void *handle, *buf;
12841 
12842 	/* buf is large, don't block if no memory is available */
12843 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
12844 	if (buf == NULL)
12845 		return (ENOMEM);
12846 
12847 	handle = cudbg_alloc_handle();
12848 	if (handle == NULL) {
12849 		rc = ENOMEM;
12850 		goto done;
12851 	}
12852 
12853 	cudbg = cudbg_get_init(handle);
12854 	cudbg->adap = sc;
12855 	cudbg->print = (cudbg_print_cb)printf;
12856 
12857 #ifndef notyet
12858 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
12859 	    __func__, dump->wr_flash, dump->len, dump->data);
12860 #endif
12861 
12862 	if (dump->wr_flash)
12863 		cudbg->use_flash = 1;
12864 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
12865 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
12866 
12867 	rc = cudbg_collect(handle, buf, &dump->len);
12868 	if (rc != 0)
12869 		goto done;
12870 
12871 	rc = copyout(buf, dump->data, dump->len);
12872 done:
12873 	cudbg_free_handle(handle);
12874 	free(buf, M_CXGBE);
12875 	return (rc);
12876 }
12877 
12878 static void
12879 free_offload_policy(struct t4_offload_policy *op)
12880 {
12881 	struct offload_rule *r;
12882 	int i;
12883 
12884 	if (op == NULL)
12885 		return;
12886 
12887 	r = &op->rule[0];
12888 	for (i = 0; i < op->nrules; i++, r++) {
12889 		free(r->bpf_prog.bf_insns, M_CXGBE);
12890 	}
12891 	free(op->rule, M_CXGBE);
12892 	free(op, M_CXGBE);
12893 }
12894 
12895 static int
12896 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
12897 {
12898 	int i, rc, len;
12899 	struct t4_offload_policy *op, *old;
12900 	struct bpf_program *bf;
12901 	const struct offload_settings *s;
12902 	struct offload_rule *r;
12903 	void *u;
12904 
12905 	if (!is_offload(sc))
12906 		return (ENODEV);
12907 
12908 	if (uop->nrules == 0) {
12909 		/* Delete installed policies. */
12910 		op = NULL;
12911 		goto set_policy;
12912 	} else if (uop->nrules > 256) { /* arbitrary */
12913 		return (E2BIG);
12914 	}
12915 
12916 	/* Copy userspace offload policy to kernel */
12917 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
12918 	op->nrules = uop->nrules;
12919 	len = op->nrules * sizeof(struct offload_rule);
12920 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12921 	rc = copyin(uop->rule, op->rule, len);
12922 	if (rc) {
12923 		free(op->rule, M_CXGBE);
12924 		free(op, M_CXGBE);
12925 		return (rc);
12926 	}
12927 
12928 	r = &op->rule[0];
12929 	for (i = 0; i < op->nrules; i++, r++) {
12930 
12931 		/* Validate open_type */
12932 		if (r->open_type != OPEN_TYPE_LISTEN &&
12933 		    r->open_type != OPEN_TYPE_ACTIVE &&
12934 		    r->open_type != OPEN_TYPE_PASSIVE &&
12935 		    r->open_type != OPEN_TYPE_DONTCARE) {
12936 error:
12937 			/*
12938 			 * Rules 0 to i have malloc'd filters that need to be
12939 			 * freed.  Rules i+1 to nrules have userspace pointers
12940 			 * and should be left alone.
12941 			 */
12942 			op->nrules = i;
12943 			free_offload_policy(op);
12944 			return (rc);
12945 		}
12946 
12947 		/* Validate settings */
12948 		s = &r->settings;
12949 		if ((s->offload != 0 && s->offload != 1) ||
12950 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
12951 		    s->sched_class < -1 ||
12952 		    s->sched_class >= sc->params.nsched_cls) {
12953 			rc = EINVAL;
12954 			goto error;
12955 		}
12956 
12957 		bf = &r->bpf_prog;
12958 		u = bf->bf_insns;	/* userspace ptr */
12959 		bf->bf_insns = NULL;
12960 		if (bf->bf_len == 0) {
12961 			/* legal, matches everything */
12962 			continue;
12963 		}
12964 		len = bf->bf_len * sizeof(*bf->bf_insns);
12965 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12966 		rc = copyin(u, bf->bf_insns, len);
12967 		if (rc != 0)
12968 			goto error;
12969 
12970 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
12971 			rc = EINVAL;
12972 			goto error;
12973 		}
12974 	}
12975 set_policy:
12976 	rw_wlock(&sc->policy_lock);
12977 	old = sc->policy;
12978 	sc->policy = op;
12979 	rw_wunlock(&sc->policy_lock);
12980 	free_offload_policy(old);
12981 
12982 	return (0);
12983 }
12984 
12985 #define MAX_READ_BUF_SIZE (128 * 1024)
12986 static int
12987 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
12988 {
12989 	uint32_t addr, remaining, n;
12990 	uint32_t *buf;
12991 	int rc;
12992 	uint8_t *dst;
12993 
12994 	mtx_lock(&sc->reg_lock);
12995 	if (hw_off_limits(sc))
12996 		rc = ENXIO;
12997 	else
12998 		rc = validate_mem_range(sc, mr->addr, mr->len);
12999 	mtx_unlock(&sc->reg_lock);
13000 	if (rc != 0)
13001 		return (rc);
13002 
13003 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
13004 	addr = mr->addr;
13005 	remaining = mr->len;
13006 	dst = (void *)mr->data;
13007 
13008 	while (remaining) {
13009 		n = min(remaining, MAX_READ_BUF_SIZE);
13010 		mtx_lock(&sc->reg_lock);
13011 		if (hw_off_limits(sc))
13012 			rc = ENXIO;
13013 		else
13014 			read_via_memwin(sc, 2, addr, buf, n);
13015 		mtx_unlock(&sc->reg_lock);
13016 		if (rc != 0)
13017 			break;
13018 
13019 		rc = copyout(buf, dst, n);
13020 		if (rc != 0)
13021 			break;
13022 
13023 		dst += n;
13024 		remaining -= n;
13025 		addr += n;
13026 	}
13027 
13028 	free(buf, M_CXGBE);
13029 	return (rc);
13030 }
13031 #undef MAX_READ_BUF_SIZE
13032 
13033 static int
13034 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
13035 {
13036 	int rc;
13037 
13038 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
13039 		return (EINVAL);
13040 
13041 	if (i2cd->len > sizeof(i2cd->data))
13042 		return (EFBIG);
13043 
13044 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
13045 	if (rc)
13046 		return (rc);
13047 	if (hw_off_limits(sc))
13048 		rc = ENXIO;
13049 	else
13050 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
13051 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
13052 	end_synchronized_op(sc, 0);
13053 
13054 	return (rc);
13055 }
13056 
13057 static int
13058 clear_stats(struct adapter *sc, u_int port_id)
13059 {
13060 	int i, v, chan_map;
13061 	struct port_info *pi;
13062 	struct vi_info *vi;
13063 	struct sge_rxq *rxq;
13064 	struct sge_txq *txq;
13065 	struct sge_wrq *wrq;
13066 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13067 	struct sge_ofld_txq *ofld_txq;
13068 #endif
13069 #ifdef TCP_OFFLOAD
13070 	struct sge_ofld_rxq *ofld_rxq;
13071 #endif
13072 
13073 	if (port_id >= sc->params.nports)
13074 		return (EINVAL);
13075 	pi = sc->port[port_id];
13076 	if (pi == NULL)
13077 		return (EIO);
13078 
13079 	mtx_lock(&sc->reg_lock);
13080 	if (!hw_off_limits(sc)) {
13081 		/* MAC stats */
13082 		t4_clr_port_stats(sc, pi->hw_port);
13083 		if (is_t6(sc)) {
13084 			if (pi->fcs_reg != -1)
13085 				pi->fcs_base = t4_read_reg64(sc,
13086 				    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13087 			else
13088 				pi->stats.rx_fcs_err = 0;
13089 		}
13090 		for_each_vi(pi, v, vi) {
13091 			if (vi->flags & VI_INIT_DONE)
13092 				t4_clr_vi_stats(sc, vi->vin);
13093 		}
13094 		chan_map = pi->rx_e_chan_map;
13095 		v = 0;	/* reuse */
13096 		while (chan_map) {
13097 			i = ffs(chan_map) - 1;
13098 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
13099 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
13100 			chan_map &= ~(1 << i);
13101 		}
13102 	}
13103 	mtx_unlock(&sc->reg_lock);
13104 	pi->tx_parse_error = 0;
13105 	pi->tnl_cong_drops = 0;
13106 
13107 	/*
13108 	 * Since this command accepts a port, clear stats for
13109 	 * all VIs on this port.
13110 	 */
13111 	for_each_vi(pi, v, vi) {
13112 		if (vi->flags & VI_INIT_DONE) {
13113 
13114 			for_each_rxq(vi, i, rxq) {
13115 #if defined(INET) || defined(INET6)
13116 				rxq->lro.lro_queued = 0;
13117 				rxq->lro.lro_flushed = 0;
13118 #endif
13119 				rxq->rxcsum = 0;
13120 				rxq->vlan_extraction = 0;
13121 				rxq->vxlan_rxcsum = 0;
13122 
13123 				rxq->fl.cl_allocated = 0;
13124 				rxq->fl.cl_recycled = 0;
13125 				rxq->fl.cl_fast_recycled = 0;
13126 			}
13127 
13128 			for_each_txq(vi, i, txq) {
13129 				txq->txcsum = 0;
13130 				txq->tso_wrs = 0;
13131 				txq->vlan_insertion = 0;
13132 				txq->imm_wrs = 0;
13133 				txq->sgl_wrs = 0;
13134 				txq->txpkt_wrs = 0;
13135 				txq->txpkts0_wrs = 0;
13136 				txq->txpkts1_wrs = 0;
13137 				txq->txpkts0_pkts = 0;
13138 				txq->txpkts1_pkts = 0;
13139 				txq->txpkts_flush = 0;
13140 				txq->raw_wrs = 0;
13141 				txq->vxlan_tso_wrs = 0;
13142 				txq->vxlan_txcsum = 0;
13143 				txq->kern_tls_records = 0;
13144 				txq->kern_tls_short = 0;
13145 				txq->kern_tls_partial = 0;
13146 				txq->kern_tls_full = 0;
13147 				txq->kern_tls_octets = 0;
13148 				txq->kern_tls_waste = 0;
13149 				txq->kern_tls_header = 0;
13150 				txq->kern_tls_fin_short = 0;
13151 				txq->kern_tls_cbc = 0;
13152 				txq->kern_tls_gcm = 0;
13153 				if (is_t6(sc)) {
13154 					txq->kern_tls_options = 0;
13155 					txq->kern_tls_fin = 0;
13156 				} else {
13157 					txq->kern_tls_ghash_received = 0;
13158 					txq->kern_tls_ghash_requested = 0;
13159 					txq->kern_tls_lso = 0;
13160 					txq->kern_tls_partial_ghash = 0;
13161 					txq->kern_tls_splitmode = 0;
13162 					txq->kern_tls_trailer = 0;
13163 					txq->kern_tls_imm_only = 0;
13164 					txq->kern_tls_imm_last16 = 0;
13165 				}
13166 				mp_ring_reset_stats(txq->r);
13167 			}
13168 
13169 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13170 			for_each_ofld_txq(vi, i, ofld_txq) {
13171 				ofld_txq->wrq.tx_wrs_direct = 0;
13172 				ofld_txq->wrq.tx_wrs_copied = 0;
13173 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
13174 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
13175 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
13176 				counter_u64_zero(ofld_txq->tx_nvme_pdus);
13177 				counter_u64_zero(ofld_txq->tx_nvme_octets);
13178 				counter_u64_zero(ofld_txq->tx_nvme_iso_wrs);
13179 				counter_u64_zero(ofld_txq->tx_aio_jobs);
13180 				counter_u64_zero(ofld_txq->tx_aio_octets);
13181 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
13182 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
13183 			}
13184 #endif
13185 #ifdef TCP_OFFLOAD
13186 			for_each_ofld_rxq(vi, i, ofld_rxq) {
13187 				ofld_rxq->fl.cl_allocated = 0;
13188 				ofld_rxq->fl.cl_recycled = 0;
13189 				ofld_rxq->fl.cl_fast_recycled = 0;
13190 				counter_u64_zero(
13191 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
13192 				counter_u64_zero(
13193 				    ofld_rxq->rx_iscsi_ddp_setup_error);
13194 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
13195 				ofld_rxq->rx_iscsi_ddp_octets = 0;
13196 				ofld_rxq->rx_iscsi_fl_pdus = 0;
13197 				ofld_rxq->rx_iscsi_fl_octets = 0;
13198 				counter_u64_zero(
13199 				    ofld_rxq->rx_nvme_ddp_setup_ok);
13200 				counter_u64_zero(
13201 				    ofld_rxq->rx_nvme_ddp_setup_no_stag);
13202 				counter_u64_zero(
13203 				    ofld_rxq->rx_nvme_ddp_setup_error);
13204 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_pdus);
13205 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_octets);
13206 				counter_u64_zero(ofld_rxq->rx_nvme_fl_pdus);
13207 				counter_u64_zero(ofld_rxq->rx_nvme_fl_octets);
13208 				counter_u64_zero(
13209 				    ofld_rxq->rx_nvme_invalid_headers);
13210 				counter_u64_zero(
13211 				    ofld_rxq->rx_nvme_header_digest_errors);
13212 				counter_u64_zero(
13213 				    ofld_rxq->rx_nvme_data_digest_errors);
13214 				ofld_rxq->rx_aio_ddp_jobs = 0;
13215 				ofld_rxq->rx_aio_ddp_octets = 0;
13216 				ofld_rxq->rx_toe_tls_records = 0;
13217 				ofld_rxq->rx_toe_tls_octets = 0;
13218 				ofld_rxq->rx_toe_ddp_octets = 0;
13219 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
13220 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
13221 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
13222 			}
13223 #endif
13224 
13225 			if (IS_MAIN_VI(vi)) {
13226 				wrq = &sc->sge.ctrlq[pi->port_id];
13227 				wrq->tx_wrs_direct = 0;
13228 				wrq->tx_wrs_copied = 0;
13229 			}
13230 		}
13231 	}
13232 
13233 	return (0);
13234 }
13235 
13236 static int
13237 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13238 {
13239 #ifdef INET6
13240 	struct in6_addr in6;
13241 
13242 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13243 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
13244 		return (0);
13245 	else
13246 		return (EIO);
13247 #else
13248 	return (ENOTSUP);
13249 #endif
13250 }
13251 
13252 static int
13253 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13254 {
13255 #ifdef INET6
13256 	struct in6_addr in6;
13257 
13258 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13259 	return (t4_release_clip_addr(sc, &in6));
13260 #else
13261 	return (ENOTSUP);
13262 #endif
13263 }
13264 
13265 int
13266 t4_os_find_pci_capability(struct adapter *sc, int cap)
13267 {
13268 	int i;
13269 
13270 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
13271 }
13272 
13273 void
13274 t4_os_portmod_changed(struct port_info *pi)
13275 {
13276 	struct adapter *sc = pi->adapter;
13277 	struct vi_info *vi;
13278 	if_t ifp;
13279 	static const char *mod_str[] = {
13280 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM",
13281 		"LR_SIMPLEX", "DR"
13282 	};
13283 
13284 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
13285 	    ("%s: port_type %u", __func__, pi->port_type));
13286 
13287 	vi = &pi->vi[0];
13288 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
13289 		PORT_LOCK(pi);
13290 		build_medialist(pi);
13291 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
13292 			fixup_link_config(pi);
13293 			apply_link_config(pi);
13294 		}
13295 		PORT_UNLOCK(pi);
13296 		end_synchronized_op(sc, LOCK_HELD);
13297 	}
13298 
13299 	ifp = vi->ifp;
13300 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
13301 		if_printf(ifp, "transceiver unplugged.\n");
13302 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
13303 		if_printf(ifp, "unknown transceiver inserted.\n");
13304 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
13305 		if_printf(ifp, "unsupported transceiver inserted.\n");
13306 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
13307 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
13308 		    port_top_speed(pi), mod_str[pi->mod_type]);
13309 	} else {
13310 		if_printf(ifp, "transceiver (type %d) inserted.\n",
13311 		    pi->mod_type);
13312 	}
13313 }
13314 
13315 void
13316 t4_os_link_changed(struct port_info *pi)
13317 {
13318 	struct vi_info *vi;
13319 	if_t ifp;
13320 	struct link_config *lc = &pi->link_cfg;
13321 	struct adapter *sc = pi->adapter;
13322 	int v;
13323 
13324 	PORT_LOCK_ASSERT_OWNED(pi);
13325 
13326 	if (is_t6(sc)) {
13327 		if (lc->link_ok) {
13328 			if (lc->speed > 25000 ||
13329 			    (lc->speed == 25000 && lc->fec == FEC_RS))
13330 				pi->fcs_reg = A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS;
13331 			else
13332 				pi->fcs_reg = A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS;
13333 			pi->fcs_base = t4_read_reg64(sc,
13334 			    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13335 			pi->stats.rx_fcs_err = 0;
13336 		} else {
13337 			pi->fcs_reg = -1;
13338 		}
13339 	} else {
13340 		MPASS(pi->fcs_reg != -1);
13341 		MPASS(pi->fcs_base == 0);
13342 	}
13343 
13344 	for_each_vi(pi, v, vi) {
13345 		ifp = vi->ifp;
13346 		if (ifp == NULL || IS_DETACHING(vi))
13347 			continue;
13348 
13349 		if (lc->link_ok) {
13350 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
13351 			if_link_state_change(ifp, LINK_STATE_UP);
13352 		} else {
13353 			if_link_state_change(ifp, LINK_STATE_DOWN);
13354 		}
13355 	}
13356 }
13357 
13358 void
13359 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
13360 {
13361 	struct adapter *sc;
13362 
13363 	sx_slock(&t4_list_lock);
13364 	SLIST_FOREACH(sc, &t4_list, link) {
13365 		/*
13366 		 * func should not make any assumptions about what state sc is
13367 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
13368 		 */
13369 		func(sc, arg);
13370 	}
13371 	sx_sunlock(&t4_list_lock);
13372 }
13373 
13374 static int
13375 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
13376     struct thread *td)
13377 {
13378 	int rc;
13379 	struct adapter *sc = dev->si_drv1;
13380 
13381 	rc = priv_check(td, PRIV_DRIVER);
13382 	if (rc != 0)
13383 		return (rc);
13384 
13385 	switch (cmd) {
13386 	case CHELSIO_T4_GETREG: {
13387 		struct t4_reg *edata = (struct t4_reg *)data;
13388 
13389 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13390 			return (EFAULT);
13391 
13392 		mtx_lock(&sc->reg_lock);
13393 		if (hw_off_limits(sc))
13394 			rc = ENXIO;
13395 		else if (edata->size == 4)
13396 			edata->val = t4_read_reg(sc, edata->addr);
13397 		else if (edata->size == 8)
13398 			edata->val = t4_read_reg64(sc, edata->addr);
13399 		else
13400 			rc = EINVAL;
13401 		mtx_unlock(&sc->reg_lock);
13402 
13403 		break;
13404 	}
13405 	case CHELSIO_T4_SETREG: {
13406 		struct t4_reg *edata = (struct t4_reg *)data;
13407 
13408 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13409 			return (EFAULT);
13410 
13411 		mtx_lock(&sc->reg_lock);
13412 		if (hw_off_limits(sc))
13413 			rc = ENXIO;
13414 		else if (edata->size == 4) {
13415 			if (edata->val & 0xffffffff00000000)
13416 				rc = EINVAL;
13417 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
13418 		} else if (edata->size == 8)
13419 			t4_write_reg64(sc, edata->addr, edata->val);
13420 		else
13421 			rc = EINVAL;
13422 		mtx_unlock(&sc->reg_lock);
13423 
13424 		break;
13425 	}
13426 	case CHELSIO_T4_REGDUMP: {
13427 		struct t4_regdump *regs = (struct t4_regdump *)data;
13428 		int reglen = t4_get_regs_len(sc);
13429 		uint8_t *buf;
13430 
13431 		if (regs->len < reglen) {
13432 			regs->len = reglen; /* hint to the caller */
13433 			return (ENOBUFS);
13434 		}
13435 
13436 		regs->len = reglen;
13437 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
13438 		mtx_lock(&sc->reg_lock);
13439 		if (hw_off_limits(sc))
13440 			rc = ENXIO;
13441 		else
13442 			get_regs(sc, regs, buf);
13443 		mtx_unlock(&sc->reg_lock);
13444 		if (rc == 0)
13445 			rc = copyout(buf, regs->data, reglen);
13446 		free(buf, M_CXGBE);
13447 		break;
13448 	}
13449 	case CHELSIO_T4_GET_FILTER_MODE:
13450 		rc = get_filter_mode(sc, (uint32_t *)data);
13451 		break;
13452 	case CHELSIO_T4_SET_FILTER_MODE:
13453 		rc = set_filter_mode(sc, *(uint32_t *)data);
13454 		break;
13455 	case CHELSIO_T4_SET_FILTER_MASK:
13456 		rc = set_filter_mask(sc, *(uint32_t *)data);
13457 		break;
13458 	case CHELSIO_T4_GET_FILTER:
13459 		rc = get_filter(sc, (struct t4_filter *)data);
13460 		break;
13461 	case CHELSIO_T4_SET_FILTER:
13462 		rc = set_filter(sc, (struct t4_filter *)data);
13463 		break;
13464 	case CHELSIO_T4_DEL_FILTER:
13465 		rc = del_filter(sc, (struct t4_filter *)data);
13466 		break;
13467 	case CHELSIO_T4_GET_SGE_CONTEXT: {
13468 		struct t4_sge_context *ctxt = (struct t4_sge_context *)data;
13469 
13470 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13471 		    sizeof(ctxt->data), &ctxt->data[0]);
13472 		break;
13473 	}
13474 	case CHELSIO_T4_LOAD_FW:
13475 		rc = load_fw(sc, (struct t4_data *)data);
13476 		break;
13477 	case CHELSIO_T4_GET_MEM:
13478 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
13479 		break;
13480 	case CHELSIO_T4_GET_I2C:
13481 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
13482 		break;
13483 	case CHELSIO_T4_CLEAR_STATS:
13484 		rc = clear_stats(sc, *(uint32_t *)data);
13485 		break;
13486 	case CHELSIO_T4_SCHED_CLASS:
13487 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
13488 		break;
13489 	case CHELSIO_T4_SCHED_QUEUE:
13490 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
13491 		break;
13492 	case CHELSIO_T4_GET_TRACER:
13493 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
13494 		break;
13495 	case CHELSIO_T4_SET_TRACER:
13496 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
13497 		break;
13498 	case CHELSIO_T4_LOAD_CFG:
13499 		rc = load_cfg(sc, (struct t4_data *)data);
13500 		break;
13501 	case CHELSIO_T4_LOAD_BOOT:
13502 		rc = load_boot(sc, (struct t4_bootrom *)data);
13503 		break;
13504 	case CHELSIO_T4_LOAD_BOOTCFG:
13505 		rc = load_bootcfg(sc, (struct t4_data *)data);
13506 		break;
13507 	case CHELSIO_T4_CUDBG_DUMP:
13508 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
13509 		break;
13510 	case CHELSIO_T4_SET_OFLD_POLICY:
13511 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
13512 		break;
13513 	case CHELSIO_T4_HOLD_CLIP_ADDR:
13514 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
13515 		break;
13516 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
13517 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
13518 		break;
13519 	case CHELSIO_T4_GET_SGE_CTXT: {
13520 		struct t4_sge_ctxt *ctxt = (struct t4_sge_ctxt *)data;
13521 
13522 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13523 		    sizeof(ctxt->data), &ctxt->data[0]);
13524 		break;
13525 	}
13526 	default:
13527 		rc = ENOTTY;
13528 	}
13529 
13530 	return (rc);
13531 }
13532 
13533 #ifdef TCP_OFFLOAD
13534 int
13535 toe_capability(struct vi_info *vi, bool enable)
13536 {
13537 	int rc;
13538 	struct port_info *pi = vi->pi;
13539 	struct adapter *sc = pi->adapter;
13540 
13541 	ASSERT_SYNCHRONIZED_OP(sc);
13542 
13543 	if (!is_offload(sc))
13544 		return (ENODEV);
13545 	if (!hw_all_ok(sc))
13546 		return (ENXIO);
13547 
13548 	if (enable) {
13549 #ifdef KERN_TLS
13550 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
13551 			int i, j, n;
13552 			struct port_info *p;
13553 			struct vi_info *v;
13554 
13555 			/*
13556 			 * Reconfigure hardware for TOE if TXTLS is not enabled
13557 			 * on any ifnet.
13558 			 */
13559 			n = 0;
13560 			for_each_port(sc, i) {
13561 				p = sc->port[i];
13562 				for_each_vi(p, j, v) {
13563 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
13564 						CH_WARN(sc,
13565 						    "%s has NIC TLS enabled.\n",
13566 						    device_get_nameunit(v->dev));
13567 						n++;
13568 					}
13569 				}
13570 			}
13571 			if (n > 0) {
13572 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
13573 				    "associated with this adapter before "
13574 				    "trying to enable TOE.\n");
13575 				return (EAGAIN);
13576 			}
13577 			rc = t6_config_kern_tls(sc, false);
13578 			if (rc)
13579 				return (rc);
13580 		}
13581 #endif
13582 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
13583 			/* TOE is already enabled. */
13584 			return (0);
13585 		}
13586 
13587 		/*
13588 		 * We need the port's queues around so that we're able to send
13589 		 * and receive CPLs to/from the TOE even if the ifnet for this
13590 		 * port has never been UP'd administratively.
13591 		 */
13592 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
13593 			return (rc);
13594 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
13595 		    ((rc = vi_init(&pi->vi[0])) != 0))
13596 			return (rc);
13597 
13598 		if (isset(&sc->offload_map, pi->port_id)) {
13599 			/* TOE is enabled on another VI of this port. */
13600 			MPASS(pi->uld_vis > 0);
13601 			pi->uld_vis++;
13602 			return (0);
13603 		}
13604 
13605 		if (!uld_active(sc, ULD_TOM)) {
13606 			rc = t4_activate_uld(sc, ULD_TOM);
13607 			if (rc == EAGAIN) {
13608 				log(LOG_WARNING,
13609 				    "You must kldload t4_tom.ko before trying "
13610 				    "to enable TOE on a cxgbe interface.\n");
13611 			}
13612 			if (rc != 0)
13613 				return (rc);
13614 			KASSERT(sc->tom_softc != NULL,
13615 			    ("%s: TOM activated but softc NULL", __func__));
13616 			KASSERT(uld_active(sc, ULD_TOM),
13617 			    ("%s: TOM activated but flag not set", __func__));
13618 		}
13619 
13620 		/*
13621 		 * Activate iWARP, iSCSI, and NVMe too, if the modules
13622 		 * are loaded.
13623 		 */
13624 		if (!uld_active(sc, ULD_IWARP))
13625 			(void) t4_activate_uld(sc, ULD_IWARP);
13626 		if (!uld_active(sc, ULD_ISCSI))
13627 			(void) t4_activate_uld(sc, ULD_ISCSI);
13628 		if (!uld_active(sc, ULD_NVME))
13629 			(void) t4_activate_uld(sc, ULD_NVME);
13630 
13631 		if (pi->uld_vis++ == 0)
13632 			setbit(&sc->offload_map, pi->port_id);
13633 	} else {
13634 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
13635 			/* TOE is already disabled. */
13636 			return (0);
13637 		}
13638 		MPASS(isset(&sc->offload_map, pi->port_id));
13639 		MPASS(pi->uld_vis > 0);
13640 		if (--pi->uld_vis == 0)
13641 			clrbit(&sc->offload_map, pi->port_id);
13642 	}
13643 
13644 	return (0);
13645 }
13646 
13647 /*
13648  * Add an upper layer driver to the global list.
13649  */
13650 int
13651 t4_register_uld(struct uld_info *ui, int id)
13652 {
13653 	int rc;
13654 
13655 	if (id < 0 || id > ULD_MAX)
13656 		return (EINVAL);
13657 	sx_xlock(&t4_uld_list_lock);
13658 	if (t4_uld_list[id] != NULL)
13659 		rc = EEXIST;
13660 	else {
13661 		t4_uld_list[id] = ui;
13662 		rc = 0;
13663 	}
13664 	sx_xunlock(&t4_uld_list_lock);
13665 	return (rc);
13666 }
13667 
13668 int
13669 t4_unregister_uld(struct uld_info *ui, int id)
13670 {
13671 
13672 	if (id < 0 || id > ULD_MAX)
13673 		return (EINVAL);
13674 	sx_xlock(&t4_uld_list_lock);
13675 	MPASS(t4_uld_list[id] == ui);
13676 	t4_uld_list[id] = NULL;
13677 	sx_xunlock(&t4_uld_list_lock);
13678 	return (0);
13679 }
13680 
13681 int
13682 t4_activate_uld(struct adapter *sc, int id)
13683 {
13684 	int rc;
13685 
13686 	ASSERT_SYNCHRONIZED_OP(sc);
13687 
13688 	if (id < 0 || id > ULD_MAX)
13689 		return (EINVAL);
13690 
13691 	/* Adapter needs to be initialized before any ULD can be activated. */
13692 	if (!(sc->flags & FULL_INIT_DONE)) {
13693 		rc = adapter_init(sc);
13694 		if (rc != 0)
13695 			return (rc);
13696 	}
13697 
13698 	sx_slock(&t4_uld_list_lock);
13699 	if (t4_uld_list[id] == NULL)
13700 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
13701 	else {
13702 		rc = t4_uld_list[id]->uld_activate(sc);
13703 		if (rc == 0)
13704 			setbit(&sc->active_ulds, id);
13705 	}
13706 	sx_sunlock(&t4_uld_list_lock);
13707 
13708 	return (rc);
13709 }
13710 
13711 int
13712 t4_deactivate_uld(struct adapter *sc, int id)
13713 {
13714 	int rc;
13715 
13716 	ASSERT_SYNCHRONIZED_OP(sc);
13717 
13718 	if (id < 0 || id > ULD_MAX)
13719 		return (EINVAL);
13720 
13721 	sx_slock(&t4_uld_list_lock);
13722 	if (t4_uld_list[id] == NULL)
13723 		rc = ENXIO;
13724 	else {
13725 		rc = t4_uld_list[id]->uld_deactivate(sc);
13726 		if (rc == 0)
13727 			clrbit(&sc->active_ulds, id);
13728 	}
13729 	sx_sunlock(&t4_uld_list_lock);
13730 
13731 	return (rc);
13732 }
13733 
13734 static int
13735 deactivate_all_uld(struct adapter *sc)
13736 {
13737 	int i, rc;
13738 
13739 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
13740 	if (rc != 0)
13741 		return (ENXIO);
13742 	sx_slock(&t4_uld_list_lock);
13743 	for (i = 0; i <= ULD_MAX; i++) {
13744 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
13745 			continue;
13746 		rc = t4_uld_list[i]->uld_deactivate(sc);
13747 		if (rc != 0)
13748 			break;
13749 		clrbit(&sc->active_ulds, i);
13750 	}
13751 	sx_sunlock(&t4_uld_list_lock);
13752 	end_synchronized_op(sc, 0);
13753 
13754 	return (rc);
13755 }
13756 
13757 static void
13758 stop_all_uld(struct adapter *sc)
13759 {
13760 	int i;
13761 
13762 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
13763 		return;
13764 	sx_slock(&t4_uld_list_lock);
13765 	for (i = 0; i <= ULD_MAX; i++) {
13766 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13767 		    t4_uld_list[i]->uld_stop == NULL)
13768 			continue;
13769 		(void) t4_uld_list[i]->uld_stop(sc);
13770 	}
13771 	sx_sunlock(&t4_uld_list_lock);
13772 	end_synchronized_op(sc, 0);
13773 }
13774 
13775 static void
13776 restart_all_uld(struct adapter *sc)
13777 {
13778 	int i;
13779 
13780 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
13781 		return;
13782 	sx_slock(&t4_uld_list_lock);
13783 	for (i = 0; i <= ULD_MAX; i++) {
13784 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13785 		    t4_uld_list[i]->uld_restart == NULL)
13786 			continue;
13787 		(void) t4_uld_list[i]->uld_restart(sc);
13788 	}
13789 	sx_sunlock(&t4_uld_list_lock);
13790 	end_synchronized_op(sc, 0);
13791 }
13792 
13793 int
13794 uld_active(struct adapter *sc, int id)
13795 {
13796 
13797 	MPASS(id >= 0 && id <= ULD_MAX);
13798 
13799 	return (isset(&sc->active_ulds, id));
13800 }
13801 #endif
13802 
13803 #ifdef KERN_TLS
13804 static int
13805 ktls_capability(struct adapter *sc, bool enable)
13806 {
13807 	ASSERT_SYNCHRONIZED_OP(sc);
13808 
13809 	if (!is_ktls(sc))
13810 		return (ENODEV);
13811 	if (!is_t6(sc))
13812 		return (0);
13813 	if (!hw_all_ok(sc))
13814 		return (ENXIO);
13815 
13816 	if (enable) {
13817 		if (sc->flags & KERN_TLS_ON)
13818 			return (0);	/* already on */
13819 		if (sc->offload_map != 0) {
13820 			CH_WARN(sc,
13821 			    "Disable TOE on all interfaces associated with "
13822 			    "this adapter before trying to enable NIC TLS.\n");
13823 			return (EAGAIN);
13824 		}
13825 		return (t6_config_kern_tls(sc, true));
13826 	} else {
13827 		/*
13828 		 * Nothing to do for disable.  If TOE is enabled sometime later
13829 		 * then toe_capability will reconfigure the hardware.
13830 		 */
13831 		return (0);
13832 	}
13833 }
13834 #endif
13835 
13836 /*
13837  * t  = ptr to tunable.
13838  * nc = number of CPUs.
13839  * c  = compiled in default for that tunable.
13840  */
13841 static void
13842 calculate_nqueues(int *t, int nc, const int c)
13843 {
13844 	int nq;
13845 
13846 	if (*t > 0)
13847 		return;
13848 	nq = *t < 0 ? -*t : c;
13849 	*t = min(nc, nq);
13850 }
13851 
13852 /*
13853  * Come up with reasonable defaults for some of the tunables, provided they're
13854  * not set by the user (in which case we'll use the values as is).
13855  */
13856 static void
13857 tweak_tunables(void)
13858 {
13859 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
13860 
13861 	if (t4_ntxq < 1) {
13862 #ifdef RSS
13863 		t4_ntxq = rss_getnumbuckets();
13864 #else
13865 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
13866 #endif
13867 	}
13868 
13869 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
13870 
13871 	if (t4_nrxq < 1) {
13872 #ifdef RSS
13873 		t4_nrxq = rss_getnumbuckets();
13874 #else
13875 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
13876 #endif
13877 	}
13878 
13879 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
13880 
13881 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13882 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
13883 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
13884 #endif
13885 #ifdef TCP_OFFLOAD
13886 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
13887 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
13888 #endif
13889 
13890 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
13891 	if (t4_toecaps_allowed == -1)
13892 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
13893 #else
13894 	if (t4_toecaps_allowed == -1)
13895 		t4_toecaps_allowed = 0;
13896 #endif
13897 
13898 #ifdef TCP_OFFLOAD
13899 	if (t4_rdmacaps_allowed == -1) {
13900 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
13901 		    FW_CAPS_CONFIG_RDMA_RDMAC;
13902 	}
13903 
13904 	if (t4_iscsicaps_allowed == -1) {
13905 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
13906 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
13907 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
13908 	}
13909 
13910 	if (t4_nvmecaps_allowed == -1)
13911 		t4_nvmecaps_allowed = FW_CAPS_CONFIG_NVME_TCP;
13912 
13913 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
13914 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
13915 
13916 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
13917 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
13918 #else
13919 	if (t4_rdmacaps_allowed == -1)
13920 		t4_rdmacaps_allowed = 0;
13921 
13922 	if (t4_iscsicaps_allowed == -1)
13923 		t4_iscsicaps_allowed = 0;
13924 
13925 	if (t4_nvmecaps_allowed == -1)
13926 		t4_nvmecaps_allowed = 0;
13927 #endif
13928 
13929 #ifdef DEV_NETMAP
13930 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
13931 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
13932 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
13933 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
13934 #endif
13935 
13936 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
13937 		t4_tmr_idx = TMR_IDX;
13938 
13939 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
13940 		t4_pktc_idx = PKTC_IDX;
13941 
13942 	if (t4_qsize_txq < 128)
13943 		t4_qsize_txq = 128;
13944 
13945 	if (t4_qsize_rxq < 128)
13946 		t4_qsize_rxq = 128;
13947 	while (t4_qsize_rxq & 7)
13948 		t4_qsize_rxq++;
13949 
13950 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
13951 
13952 	/*
13953 	 * Number of VIs to create per-port.  The first VI is the "main" regular
13954 	 * VI for the port.  The rest are additional virtual interfaces on the
13955 	 * same physical port.  Note that the main VI does not have native
13956 	 * netmap support but the extra VIs do.
13957 	 *
13958 	 * Limit the number of VIs per port to the number of available
13959 	 * MAC addresses per port.
13960 	 */
13961 	if (t4_num_vis < 1)
13962 		t4_num_vis = 1;
13963 	if (t4_num_vis > nitems(vi_mac_funcs)) {
13964 		t4_num_vis = nitems(vi_mac_funcs);
13965 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
13966 	}
13967 
13968 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
13969 		pcie_relaxed_ordering = 1;
13970 #if defined(__i386__) || defined(__amd64__)
13971 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
13972 			pcie_relaxed_ordering = 0;
13973 #endif
13974 	}
13975 }
13976 
13977 #ifdef DDB
13978 static void
13979 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
13980 {
13981 	uint32_t base, j, off, pf, reg, save, win_pos;
13982 
13983 	reg = chip_id(sc) > CHELSIO_T6 ?
13984 	    PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, 2) :
13985 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
13986 	save = t4_read_reg(sc, reg);
13987 	base = sc->memwin[2].mw_base;
13988 
13989 	if (is_t4(sc)) {
13990 		pf = 0;
13991 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
13992 	} else {
13993 		pf = V_PFNUM(sc->pf);
13994 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
13995 	}
13996 	off = addr - win_pos;
13997 	if (chip_id(sc) > CHELSIO_T6)
13998 		win_pos >>= X_T7_MEMOFST_SHIFT;
13999 	t4_write_reg(sc, reg, win_pos | pf);
14000 	t4_read_reg(sc, reg);
14001 
14002 	while (len > 0 && !db_pager_quit) {
14003 		uint32_t buf[8];
14004 		for (j = 0; j < 8; j++, off += 4)
14005 			buf[j] = htonl(t4_read_reg(sc, base + off));
14006 
14007 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
14008 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
14009 		    buf[7]);
14010 		if (len <= sizeof(buf))
14011 			len = 0;
14012 		else
14013 			len -= sizeof(buf);
14014 	}
14015 
14016 	t4_write_reg(sc, reg, save);
14017 	t4_read_reg(sc, reg);
14018 }
14019 
14020 static void
14021 t4_dump_tcb(struct adapter *sc, int tid)
14022 {
14023 	uint32_t tcb_addr;
14024 
14025 	/* Dump TCB for the tid */
14026 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
14027 	tcb_addr += tid * TCB_SIZE;
14028 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
14029 }
14030 
14031 static void
14032 t4_dump_devlog(struct adapter *sc)
14033 {
14034 	struct devlog_params *dparams = &sc->params.devlog;
14035 	struct fw_devlog_e e;
14036 	int i, first, j, m, nentries, rc;
14037 	uint64_t ftstamp = UINT64_MAX;
14038 
14039 	if (dparams->start == 0) {
14040 		db_printf("devlog params not valid\n");
14041 		return;
14042 	}
14043 
14044 	nentries = dparams->size / sizeof(struct fw_devlog_e);
14045 	m = fwmtype_to_hwmtype(dparams->memtype);
14046 
14047 	/* Find the first entry. */
14048 	first = -1;
14049 	for (i = 0; i < nentries && !db_pager_quit; i++) {
14050 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
14051 		    sizeof(e), (void *)&e);
14052 		if (rc != 0)
14053 			break;
14054 
14055 		if (e.timestamp == 0)
14056 			break;
14057 
14058 		e.timestamp = be64toh(e.timestamp);
14059 		if (e.timestamp < ftstamp) {
14060 			ftstamp = e.timestamp;
14061 			first = i;
14062 		}
14063 	}
14064 
14065 	if (first == -1)
14066 		return;
14067 
14068 	i = first;
14069 	do {
14070 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
14071 		    sizeof(e), (void *)&e);
14072 		if (rc != 0)
14073 			return;
14074 
14075 		if (e.timestamp == 0)
14076 			return;
14077 
14078 		e.timestamp = be64toh(e.timestamp);
14079 		e.seqno = be32toh(e.seqno);
14080 		for (j = 0; j < 8; j++)
14081 			e.params[j] = be32toh(e.params[j]);
14082 
14083 		db_printf("%10d  %15ju  %8s  %8s  ",
14084 		    e.seqno, e.timestamp,
14085 		    (e.level < nitems(devlog_level_strings) ?
14086 			devlog_level_strings[e.level] : "UNKNOWN"),
14087 		    (e.facility < nitems(devlog_facility_strings) ?
14088 			devlog_facility_strings[e.facility] : "UNKNOWN"));
14089 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
14090 		    e.params[3], e.params[4], e.params[5], e.params[6],
14091 		    e.params[7]);
14092 
14093 		if (++i == nentries)
14094 			i = 0;
14095 	} while (i != first && !db_pager_quit);
14096 }
14097 
14098 static DB_DEFINE_TABLE(show, t4, show_t4);
14099 
14100 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
14101 {
14102 	device_t dev;
14103 	int t;
14104 	bool valid;
14105 
14106 	valid = false;
14107 	t = db_read_token();
14108 	if (t == tIDENT) {
14109 		dev = device_lookup_by_name(db_tok_string);
14110 		valid = true;
14111 	}
14112 	db_skip_to_eol();
14113 	if (!valid) {
14114 		db_printf("usage: show t4 devlog <nexus>\n");
14115 		return;
14116 	}
14117 
14118 	if (dev == NULL) {
14119 		db_printf("device not found\n");
14120 		return;
14121 	}
14122 
14123 	t4_dump_devlog(device_get_softc(dev));
14124 }
14125 
14126 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
14127 {
14128 	device_t dev;
14129 	int radix, tid, t;
14130 	bool valid;
14131 
14132 	valid = false;
14133 	radix = db_radix;
14134 	db_radix = 10;
14135 	t = db_read_token();
14136 	if (t == tIDENT) {
14137 		dev = device_lookup_by_name(db_tok_string);
14138 		t = db_read_token();
14139 		if (t == tNUMBER) {
14140 			tid = db_tok_number;
14141 			valid = true;
14142 		}
14143 	}
14144 	db_radix = radix;
14145 	db_skip_to_eol();
14146 	if (!valid) {
14147 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
14148 		return;
14149 	}
14150 
14151 	if (dev == NULL) {
14152 		db_printf("device not found\n");
14153 		return;
14154 	}
14155 	if (tid < 0) {
14156 		db_printf("invalid tid\n");
14157 		return;
14158 	}
14159 
14160 	t4_dump_tcb(device_get_softc(dev), tid);
14161 }
14162 
14163 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
14164 {
14165 	device_t dev;
14166 	int radix, t;
14167 	bool valid;
14168 
14169 	valid = false;
14170 	radix = db_radix;
14171 	db_radix = 10;
14172 	t = db_read_token();
14173 	if (t == tIDENT) {
14174 		dev = device_lookup_by_name(db_tok_string);
14175 		t = db_read_token();
14176 		if (t == tNUMBER) {
14177 			addr = db_tok_number;
14178 			t = db_read_token();
14179 			if (t == tNUMBER) {
14180 				count = db_tok_number;
14181 				valid = true;
14182 			}
14183 		}
14184 	}
14185 	db_radix = radix;
14186 	db_skip_to_eol();
14187 	if (!valid) {
14188 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
14189 		return;
14190 	}
14191 
14192 	if (dev == NULL) {
14193 		db_printf("device not found\n");
14194 		return;
14195 	}
14196 	if (addr < 0) {
14197 		db_printf("invalid address\n");
14198 		return;
14199 	}
14200 	if (count <= 0) {
14201 		db_printf("invalid length\n");
14202 		return;
14203 	}
14204 
14205 	t4_dump_mem(device_get_softc(dev), addr, count);
14206 }
14207 #endif
14208 
14209 static eventhandler_tag vxlan_start_evtag;
14210 static eventhandler_tag vxlan_stop_evtag;
14211 
14212 struct vxlan_evargs {
14213 	if_t ifp;
14214 	uint16_t port;
14215 };
14216 
14217 static void
14218 enable_vxlan_rx(struct adapter *sc)
14219 {
14220 	int i, rc;
14221 	struct port_info *pi;
14222 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
14223 
14224 	ASSERT_SYNCHRONIZED_OP(sc);
14225 
14226 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
14227 	    F_VXLAN_EN);
14228 	for_each_port(sc, i) {
14229 		pi = sc->port[i];
14230 		if (pi->vxlan_tcam_entry == true)
14231 			continue;
14232 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
14233 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
14234 		    true);
14235 		if (rc < 0) {
14236 			rc = -rc;
14237 			CH_ERR(&pi->vi[0],
14238 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
14239 		} else {
14240 			MPASS(rc == sc->rawf_base + pi->port_id);
14241 			pi->vxlan_tcam_entry = true;
14242 		}
14243 	}
14244 }
14245 
14246 static void
14247 t4_vxlan_start(struct adapter *sc, void *arg)
14248 {
14249 	struct vxlan_evargs *v = arg;
14250 
14251 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14252 		return;
14253 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
14254 		return;
14255 
14256 	if (sc->vxlan_refcount == 0) {
14257 		sc->vxlan_port = v->port;
14258 		sc->vxlan_refcount = 1;
14259 		if (!hw_off_limits(sc))
14260 			enable_vxlan_rx(sc);
14261 	} else if (sc->vxlan_port == v->port) {
14262 		sc->vxlan_refcount++;
14263 	} else {
14264 		CH_ERR(sc, "VXLAN already configured on port  %d; "
14265 		    "ignoring attempt to configure it on port %d\n",
14266 		    sc->vxlan_port, v->port);
14267 	}
14268 	end_synchronized_op(sc, 0);
14269 }
14270 
14271 static void
14272 t4_vxlan_stop(struct adapter *sc, void *arg)
14273 {
14274 	struct vxlan_evargs *v = arg;
14275 
14276 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14277 		return;
14278 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
14279 		return;
14280 
14281 	/*
14282 	 * VXLANs may have been configured before the driver was loaded so we
14283 	 * may see more stops than starts.  This is not handled cleanly but at
14284 	 * least we keep the refcount sane.
14285 	 */
14286 	if (sc->vxlan_port != v->port)
14287 		goto done;
14288 	if (sc->vxlan_refcount == 0) {
14289 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
14290 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
14291 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
14292 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
14293 done:
14294 	end_synchronized_op(sc, 0);
14295 }
14296 
14297 static void
14298 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
14299     sa_family_t family, u_int port)
14300 {
14301 	struct vxlan_evargs v;
14302 
14303 	MPASS(family == AF_INET || family == AF_INET6);
14304 	v.ifp = ifp;
14305 	v.port = port;
14306 
14307 	t4_iterate(t4_vxlan_start, &v);
14308 }
14309 
14310 static void
14311 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
14312     u_int port)
14313 {
14314 	struct vxlan_evargs v;
14315 
14316 	MPASS(family == AF_INET || family == AF_INET6);
14317 	v.ifp = ifp;
14318 	v.port = port;
14319 
14320 	t4_iterate(t4_vxlan_stop, &v);
14321 }
14322 
14323 
14324 static struct sx mlu;	/* mod load unload */
14325 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
14326 
14327 static int
14328 mod_event(module_t mod, int cmd, void *arg)
14329 {
14330 	int rc = 0;
14331 	static int loaded = 0;
14332 
14333 	switch (cmd) {
14334 	case MOD_LOAD:
14335 		sx_xlock(&mlu);
14336 		if (loaded++ == 0) {
14337 			t4_sge_modload();
14338 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14339 			    t4_filter_rpl, CPL_COOKIE_FILTER);
14340 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
14341 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
14342 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
14343 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
14344 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14345 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
14346 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
14347 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
14348 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
14349 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
14350 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
14351 			    do_smt_write_rpl);
14352 			sx_init(&t4_list_lock, "T4/T5 adapters");
14353 			SLIST_INIT(&t4_list);
14354 			callout_init(&fatal_callout, 1);
14355 #ifdef TCP_OFFLOAD
14356 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
14357 #endif
14358 #ifdef INET6
14359 			t4_clip_modload();
14360 #endif
14361 #ifdef KERN_TLS
14362 			t6_ktls_modload();
14363 			t7_ktls_modload();
14364 #endif
14365 			t4_tracer_modload();
14366 			tweak_tunables();
14367 			vxlan_start_evtag =
14368 			    EVENTHANDLER_REGISTER(vxlan_start,
14369 				t4_vxlan_start_handler, NULL,
14370 				EVENTHANDLER_PRI_ANY);
14371 			vxlan_stop_evtag =
14372 			    EVENTHANDLER_REGISTER(vxlan_stop,
14373 				t4_vxlan_stop_handler, NULL,
14374 				EVENTHANDLER_PRI_ANY);
14375 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
14376 			    taskqueue_thread_enqueue, &reset_tq);
14377 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
14378 			    "t4_rst_thr");
14379 		}
14380 		sx_xunlock(&mlu);
14381 		break;
14382 
14383 	case MOD_UNLOAD:
14384 		sx_xlock(&mlu);
14385 		if (--loaded == 0) {
14386 #ifdef TCP_OFFLOAD
14387 			int i;
14388 #endif
14389 			int tries;
14390 
14391 			taskqueue_free(reset_tq);
14392 
14393 			tries = 0;
14394 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
14395 				uprintf("%ju clusters with custom free routine "
14396 				    "still is use.\n", t4_sge_extfree_refs());
14397 				pause("t4unload", 2 * hz);
14398 			}
14399 
14400 			sx_slock(&t4_list_lock);
14401 			if (!SLIST_EMPTY(&t4_list)) {
14402 				rc = EBUSY;
14403 				sx_sunlock(&t4_list_lock);
14404 				goto done_unload;
14405 			}
14406 #ifdef TCP_OFFLOAD
14407 			sx_slock(&t4_uld_list_lock);
14408 			for (i = 0; i <= ULD_MAX; i++) {
14409 				if (t4_uld_list[i] != NULL) {
14410 					rc = EBUSY;
14411 					sx_sunlock(&t4_uld_list_lock);
14412 					sx_sunlock(&t4_list_lock);
14413 					goto done_unload;
14414 				}
14415 			}
14416 			sx_sunlock(&t4_uld_list_lock);
14417 #endif
14418 			sx_sunlock(&t4_list_lock);
14419 
14420 			if (t4_sge_extfree_refs() == 0) {
14421 				EVENTHANDLER_DEREGISTER(vxlan_start,
14422 				    vxlan_start_evtag);
14423 				EVENTHANDLER_DEREGISTER(vxlan_stop,
14424 				    vxlan_stop_evtag);
14425 				t4_tracer_modunload();
14426 #ifdef KERN_TLS
14427 				t7_ktls_modunload();
14428 				t6_ktls_modunload();
14429 #endif
14430 #ifdef INET6
14431 				t4_clip_modunload();
14432 #endif
14433 #ifdef TCP_OFFLOAD
14434 				sx_destroy(&t4_uld_list_lock);
14435 #endif
14436 				sx_destroy(&t4_list_lock);
14437 				t4_sge_modunload();
14438 				loaded = 0;
14439 			} else {
14440 				rc = EBUSY;
14441 				loaded++;	/* undo earlier decrement */
14442 			}
14443 		}
14444 done_unload:
14445 		sx_xunlock(&mlu);
14446 		break;
14447 	}
14448 
14449 	return (rc);
14450 }
14451 
14452 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
14453 MODULE_VERSION(t4nex, 1);
14454 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
14455 #ifdef DEV_NETMAP
14456 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
14457 #endif /* DEV_NETMAP */
14458 
14459 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
14460 MODULE_VERSION(t5nex, 1);
14461 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
14462 #ifdef DEV_NETMAP
14463 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
14464 #endif /* DEV_NETMAP */
14465 
14466 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
14467 MODULE_VERSION(t6nex, 1);
14468 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
14469 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
14470 #ifdef DEV_NETMAP
14471 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
14472 #endif /* DEV_NETMAP */
14473 
14474 DRIVER_MODULE(chnex, pci, ch_driver, mod_event, 0);
14475 MODULE_VERSION(chnex, 1);
14476 MODULE_DEPEND(chnex, crypto, 1, 1, 1);
14477 MODULE_DEPEND(chnex, firmware, 1, 1, 1);
14478 #ifdef DEV_NETMAP
14479 MODULE_DEPEND(chnex, netmap, 1, 1, 1);
14480 #endif /* DEV_NETMAP */
14481 
14482 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
14483 MODULE_VERSION(cxgbe, 1);
14484 
14485 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
14486 MODULE_VERSION(cxl, 1);
14487 
14488 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
14489 MODULE_VERSION(cc, 1);
14490 
14491 DRIVER_MODULE(che, chnex, che_driver, 0, 0);
14492 MODULE_VERSION(che, 1);
14493 
14494 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
14495 MODULE_VERSION(vcxgbe, 1);
14496 
14497 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
14498 MODULE_VERSION(vcxl, 1);
14499 
14500 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
14501 MODULE_VERSION(vcc, 1);
14502 
14503 DRIVER_MODULE(vche, che, vche_driver, 0, 0);
14504 MODULE_VERSION(vche, 1);
14505