xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision f9bc005b8ef3b507a5ecbc2d7fe4411ef70eff38)
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_inline_keys = 0;
757 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
758     &t4_tls_inline_keys, 0,
759     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
760     "in card memory.");
761 
762 static int t4_tls_combo_wrs = 0;
763 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
764     0, "Attempt to combine TCB field updates with TLS record work requests.");
765 
766 static int t4_tls_short_records = 1;
767 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, short_records, CTLFLAG_RDTUN,
768     &t4_tls_short_records, 0, "Use cipher-only mode for short records.");
769 
770 static int t4_tls_partial_ghash = 1;
771 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, partial_ghash, CTLFLAG_RDTUN,
772     &t4_tls_partial_ghash, 0, "Use partial GHASH for AES-GCM records.");
773 #endif
774 
775 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
776 static int vi_mac_funcs[] = {
777 	FW_VI_FUNC_ETH,
778 	FW_VI_FUNC_OFLD,
779 	FW_VI_FUNC_IWARP,
780 	FW_VI_FUNC_OPENISCSI,
781 	FW_VI_FUNC_OPENFCOE,
782 	FW_VI_FUNC_FOISCSI,
783 	FW_VI_FUNC_FOFCOE,
784 };
785 
786 struct intrs_and_queues {
787 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
788 	uint16_t num_vis;	/* number of VIs for each port */
789 	uint16_t nirq;		/* Total # of vectors */
790 	uint16_t ntxq;		/* # of NIC txq's for each port */
791 	uint16_t nrxq;		/* # of NIC rxq's for each port */
792 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
793 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
794 	uint16_t nnmtxq;	/* # of netmap txq's */
795 	uint16_t nnmrxq;	/* # of netmap rxq's */
796 
797 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
798 	uint16_t ntxq_vi;	/* # of NIC txq's */
799 	uint16_t nrxq_vi;	/* # of NIC rxq's */
800 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
801 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
802 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
803 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
804 };
805 
806 static void setup_memwin(struct adapter *);
807 static void position_memwin(struct adapter *, int, uint32_t);
808 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
809 static int fwmtype_to_hwmtype(int);
810 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
811     uint32_t *);
812 static int fixup_devlog_ncores_params(struct adapter *);
813 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
814 static int contact_firmware(struct adapter *);
815 static int partition_resources(struct adapter *);
816 static int get_params__pre_init(struct adapter *);
817 static int set_params__pre_init(struct adapter *);
818 static int get_params__post_init(struct adapter *);
819 static int set_params__post_init(struct adapter *);
820 static void t4_set_desc(struct adapter *);
821 static bool fixed_ifmedia(struct port_info *);
822 static void build_medialist(struct port_info *);
823 static void init_link_config(struct port_info *);
824 static int fixup_link_config(struct port_info *);
825 static int apply_link_config(struct port_info *);
826 static int cxgbe_init_synchronized(struct vi_info *);
827 static int cxgbe_uninit_synchronized(struct vi_info *);
828 static int adapter_full_init(struct adapter *);
829 static void adapter_full_uninit(struct adapter *);
830 static int vi_full_init(struct vi_info *);
831 static void vi_full_uninit(struct vi_info *);
832 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
833 static void quiesce_txq(struct sge_txq *);
834 static void quiesce_wrq(struct sge_wrq *);
835 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
836 static void quiesce_vi(struct vi_info *);
837 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
838     driver_intr_t *, void *, char *);
839 static int t4_free_irq(struct adapter *, struct irq *);
840 static void t4_init_atid_table(struct adapter *);
841 static void t4_free_atid_table(struct adapter *);
842 static void stop_atid_allocator(struct adapter *);
843 static void restart_atid_allocator(struct adapter *);
844 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
845 static void vi_refresh_stats(struct vi_info *);
846 static void cxgbe_refresh_stats(struct vi_info *);
847 static void cxgbe_tick(void *);
848 static void vi_tick(void *);
849 static void cxgbe_sysctls(struct port_info *);
850 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
851 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
852 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
853 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
854 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
855 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
856 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
857 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
858 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
859 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
860 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
861 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
862 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
863 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
864 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
865 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
866 static int sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS);
867 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
868 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
869 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
870 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
871 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
872 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
873 static int sysctl_cim_ibq(SYSCTL_HANDLER_ARGS);
874 static int sysctl_cim_obq(SYSCTL_HANDLER_ARGS);
875 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
876 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
877 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
878 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
879 static int sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS);
880 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
881 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
882 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
883 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
884 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
885 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
886 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
887 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
888 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
889 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
890 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
891 static int sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS);
892 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
893 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
894 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
895 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
896 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
897 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
898 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
899 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
900 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
901 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
902 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
903 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
904 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
905 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
906 static int sysctl_tcb_cache(SYSCTL_HANDLER_ARGS);
907 #ifdef TCP_OFFLOAD
908 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
909 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
910 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
911 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
912 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
913 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
914 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
915 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
916 #endif
917 static int get_sge_context(struct adapter *, int, uint32_t, int, uint32_t *);
918 static int load_fw(struct adapter *, struct t4_data *);
919 static int load_cfg(struct adapter *, struct t4_data *);
920 static int load_boot(struct adapter *, struct t4_bootrom *);
921 static int load_bootcfg(struct adapter *, struct t4_data *);
922 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
923 static void free_offload_policy(struct t4_offload_policy *);
924 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
925 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
926 static int read_i2c(struct adapter *, struct t4_i2c_data *);
927 static int clear_stats(struct adapter *, u_int);
928 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
929 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
930 static inline int stop_adapter(struct adapter *);
931 static inline void set_adapter_hwstatus(struct adapter *, const bool);
932 static int stop_lld(struct adapter *);
933 static inline int restart_adapter(struct adapter *);
934 static int restart_lld(struct adapter *);
935 #ifdef TCP_OFFLOAD
936 static int deactivate_all_uld(struct adapter *);
937 static void stop_all_uld(struct adapter *);
938 static void restart_all_uld(struct adapter *);
939 #endif
940 #ifdef KERN_TLS
941 static int ktls_capability(struct adapter *, bool);
942 #endif
943 static int mod_event(module_t, int, void *);
944 static int notify_siblings(device_t, int);
945 static uint64_t vi_get_counter(if_t, ift_counter);
946 static uint64_t cxgbe_get_counter(if_t, ift_counter);
947 static void enable_vxlan_rx(struct adapter *);
948 static void reset_adapter_task(void *, int);
949 static void fatal_error_task(void *, int);
950 static void dump_devlog(struct adapter *);
951 static void dump_cim_regs(struct adapter *);
952 static void dump_cimla(struct adapter *);
953 
954 struct {
955 	uint16_t device;
956 	char *desc;
957 } t4_pciids[] = {
958 	{0xa000, "Chelsio Terminator 4 FPGA"},
959 	{0x4400, "Chelsio T440-dbg"},
960 	{0x4401, "Chelsio T420-CR"},
961 	{0x4402, "Chelsio T422-CR"},
962 	{0x4403, "Chelsio T440-CR"},
963 	{0x4404, "Chelsio T420-BCH"},
964 	{0x4405, "Chelsio T440-BCH"},
965 	{0x4406, "Chelsio T440-CH"},
966 	{0x4407, "Chelsio T420-SO"},
967 	{0x4408, "Chelsio T420-CX"},
968 	{0x4409, "Chelsio T420-BT"},
969 	{0x440a, "Chelsio T404-BT"},
970 	{0x440e, "Chelsio T440-LP-CR"},
971 }, t5_pciids[] = {
972 	{0xb000, "Chelsio Terminator 5 FPGA"},
973 	{0x5400, "Chelsio T580-dbg"},
974 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
975 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
976 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
977 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
978 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
979 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
980 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
981 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
982 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
983 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
984 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
985 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
986 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
987 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
988 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
989 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
990 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
991 
992 	/* Custom */
993 	{0x5483, "Custom T540-CR"},
994 	{0x5484, "Custom T540-BT"},
995 }, t6_pciids[] = {
996 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
997 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
998 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
999 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
1000 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
1001 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
1002 	{0x6405, "Chelsio T6225-SO-OCP3"},	/* 2 x 10/25G, nomem */
1003 	{0x6406, "Chelsio T6225-OCP3"},		/* 2 x 10/25G */
1004 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
1005 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
1006 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
1007 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
1008 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
1009 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
1010 	{0x6414, "Chelsio T62100-SO-OCP3"},	/* 2 x 40/50/100G, nomem */
1011 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
1012 
1013 	/* Custom */
1014 	{0x6480, "Custom T6225-CR"},
1015 	{0x6481, "Custom T62100-CR"},
1016 	{0x6482, "Custom T6225-CR"},
1017 	{0x6483, "Custom T62100-CR"},
1018 	{0x6484, "Custom T64100-CR"},
1019 	{0x6485, "Custom T6240-SO"},
1020 	{0x6486, "Custom T6225-SO-CR"},
1021 	{0x6487, "Custom T6225-CR"},
1022 }, t7_pciids[] = {
1023 	{0xd000, "Chelsio Terminator 7 FPGA"},	/* T7 PE12K FPGA */
1024 	{0x7400, "Chelsio T72200-DBG"},		/* 2 x 200G, debug */
1025 	{0x7401, "Chelsio T7250"},		/* 2 x 10/25/50G, 1 mem */
1026 	{0x7402, "Chelsio S7250"},		/* 2 x 10/25/50G, nomem */
1027 	{0x7403, "Chelsio T7450"},		/* 4 x 10/25/50G, 1 mem */
1028 	{0x7404, "Chelsio S7450"},		/* 4 x 10/25/50G, nomem */
1029 	{0x7405, "Chelsio T72200"},		/* 2 x 40/100/200G, 1 mem */
1030 	{0x7406, "Chelsio S72200"},		/* 2 x 40/100/200G, nomem */
1031 	{0x7407, "Chelsio T72200-FH"},		/* 2 x 40/100/200G, 2 mem */
1032 	{0x7408, "Chelsio S71400"},		/* 1 x 400G, nomem */
1033 	{0x7409, "Chelsio S7210-BT"},		/* 2 x 10GBASE-T, nomem */
1034 	{0x740a, "Chelsio T7450-RC"},		/* 4 x 10/25/50G, 1 mem, RC */
1035 	{0x740b, "Chelsio T72200-RC"},		/* 2 x 40/100/200G, 1 mem, RC */
1036 	{0x740c, "Chelsio T72200-FH-RC"},	/* 2 x 40/100/200G, 2 mem, RC */
1037 	{0x740d, "Chelsio S72200-OCP3"},	/* 2 x 40/100/200G OCP3 */
1038 	{0x740e, "Chelsio S7450-OCP3"},		/* 4 x 1/20/25/50G OCP3 */
1039 	{0x740f, "Chelsio S7410-BT-OCP3"},	/* 4 x 10GBASE-T OCP3 */
1040 	{0x7410, "Chelsio S7210-BT-A"},		/* 2 x 10GBASE-T */
1041 	{0x7411, "Chelsio T7_MAYRA_7"},		/* Motherboard */
1042 
1043 	/* Custom */
1044 	{0x7480, "Custom T7"},
1045 };
1046 
1047 #ifdef TCP_OFFLOAD
1048 /*
1049  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
1050  * be exactly the same for both rxq and ofld_rxq.
1051  */
1052 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
1053 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
1054 #endif
1055 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
1056 
1057 static int
1058 t4_probe(device_t dev)
1059 {
1060 	int i;
1061 	uint16_t v = pci_get_vendor(dev);
1062 	uint16_t d = pci_get_device(dev);
1063 	uint8_t f = pci_get_function(dev);
1064 
1065 	if (v != PCI_VENDOR_ID_CHELSIO)
1066 		return (ENXIO);
1067 
1068 	/* Attach only to PF0 of the FPGA */
1069 	if (d == 0xa000 && f != 0)
1070 		return (ENXIO);
1071 
1072 	for (i = 0; i < nitems(t4_pciids); i++) {
1073 		if (d == t4_pciids[i].device) {
1074 			device_set_desc(dev, t4_pciids[i].desc);
1075 			return (BUS_PROBE_DEFAULT);
1076 		}
1077 	}
1078 
1079 	return (ENXIO);
1080 }
1081 
1082 static int
1083 t5_probe(device_t dev)
1084 {
1085 	int i;
1086 	uint16_t v = pci_get_vendor(dev);
1087 	uint16_t d = pci_get_device(dev);
1088 	uint8_t f = pci_get_function(dev);
1089 
1090 	if (v != PCI_VENDOR_ID_CHELSIO)
1091 		return (ENXIO);
1092 
1093 	/* Attach only to PF0 of the FPGA */
1094 	if (d == 0xb000 && f != 0)
1095 		return (ENXIO);
1096 
1097 	for (i = 0; i < nitems(t5_pciids); i++) {
1098 		if (d == t5_pciids[i].device) {
1099 			device_set_desc(dev, t5_pciids[i].desc);
1100 			return (BUS_PROBE_DEFAULT);
1101 		}
1102 	}
1103 
1104 	return (ENXIO);
1105 }
1106 
1107 static int
1108 t6_probe(device_t dev)
1109 {
1110 	int i;
1111 	uint16_t v = pci_get_vendor(dev);
1112 	uint16_t d = pci_get_device(dev);
1113 
1114 	if (v != PCI_VENDOR_ID_CHELSIO)
1115 		return (ENXIO);
1116 
1117 	for (i = 0; i < nitems(t6_pciids); i++) {
1118 		if (d == t6_pciids[i].device) {
1119 			device_set_desc(dev, t6_pciids[i].desc);
1120 			return (BUS_PROBE_DEFAULT);
1121 		}
1122 	}
1123 
1124 	return (ENXIO);
1125 }
1126 
1127 static int
1128 ch_probe(device_t dev)
1129 {
1130 	int i;
1131 	uint16_t v = pci_get_vendor(dev);
1132 	uint16_t d = pci_get_device(dev);
1133 	uint8_t f = pci_get_function(dev);
1134 
1135 	if (v != PCI_VENDOR_ID_CHELSIO)
1136 		return (ENXIO);
1137 
1138 	/* Attach only to PF0 of the FPGA */
1139 	if (d == 0xd000 && f != 0)
1140 		return (ENXIO);
1141 
1142 	for (i = 0; i < nitems(t7_pciids); i++) {
1143 		if (d == t7_pciids[i].device) {
1144 			device_set_desc(dev, t7_pciids[i].desc);
1145 			return (BUS_PROBE_DEFAULT);
1146 		}
1147 	}
1148 
1149 	return (ENXIO);
1150 }
1151 
1152 static void
1153 t5_attribute_workaround(device_t dev)
1154 {
1155 	device_t root_port;
1156 	uint32_t v;
1157 
1158 	/*
1159 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1160 	 * Ordering attributes when replying to a TLP from a Root
1161 	 * Port.  As a workaround, find the parent Root Port and
1162 	 * disable No Snoop and Relaxed Ordering.  Note that this
1163 	 * affects all devices under this root port.
1164 	 */
1165 	root_port = pci_find_pcie_root_port(dev);
1166 	if (root_port == NULL) {
1167 		device_printf(dev, "Unable to find parent root port\n");
1168 		return;
1169 	}
1170 
1171 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1172 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1173 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1174 	    0)
1175 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1176 		    device_get_nameunit(root_port));
1177 }
1178 
1179 static const struct devnames devnames[] = {
1180 	{
1181 		.nexus_name = "t4nex",
1182 		.ifnet_name = "cxgbe",
1183 		.vi_ifnet_name = "vcxgbe",
1184 		.pf03_drv_name = "t4iov",
1185 		.vf_nexus_name = "t4vf",
1186 		.vf_ifnet_name = "cxgbev"
1187 	}, {
1188 		.nexus_name = "t5nex",
1189 		.ifnet_name = "cxl",
1190 		.vi_ifnet_name = "vcxl",
1191 		.pf03_drv_name = "t5iov",
1192 		.vf_nexus_name = "t5vf",
1193 		.vf_ifnet_name = "cxlv"
1194 	}, {
1195 		.nexus_name = "t6nex",
1196 		.ifnet_name = "cc",
1197 		.vi_ifnet_name = "vcc",
1198 		.pf03_drv_name = "t6iov",
1199 		.vf_nexus_name = "t6vf",
1200 		.vf_ifnet_name = "ccv"
1201 	}, {
1202 		.nexus_name = "chnex",
1203 		.ifnet_name = "che",
1204 		.vi_ifnet_name = "vche",
1205 		.pf03_drv_name = "chiov",
1206 		.vf_nexus_name = "chvf",
1207 		.vf_ifnet_name = "chev"
1208 	}
1209 };
1210 
1211 void
1212 t4_init_devnames(struct adapter *sc)
1213 {
1214 	int id;
1215 
1216 	id = chip_id(sc);
1217 	if (id < CHELSIO_T4) {
1218 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1219 		sc->names = NULL;
1220 	} else if (id - CHELSIO_T4 < nitems(devnames))
1221 		sc->names = &devnames[id - CHELSIO_T4];
1222 	else
1223 		sc->names = &devnames[nitems(devnames) - 1];
1224 }
1225 
1226 static int
1227 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1228 {
1229 	const char *parent, *name;
1230 	long value;
1231 	int line, unit;
1232 
1233 	line = 0;
1234 	parent = device_get_nameunit(sc->dev);
1235 	name = sc->names->ifnet_name;
1236 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1237 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1238 		    value == pi->port_id)
1239 			return (unit);
1240 	}
1241 	return (-1);
1242 }
1243 
1244 static void
1245 t4_calibration(void *arg)
1246 {
1247 	struct adapter *sc;
1248 	struct clock_sync *cur, *nex;
1249 	uint64_t hw;
1250 	sbintime_t sbt;
1251 	int next_up;
1252 
1253 	sc = (struct adapter *)arg;
1254 
1255 	KASSERT(!hw_off_limits(sc), ("hw_off_limits at t4_calibration"));
1256 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1257 	sbt = sbinuptime();
1258 
1259 	cur = &sc->cal_info[sc->cal_current];
1260 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1261 	nex = &sc->cal_info[next_up];
1262 	if (__predict_false(sc->cal_count == 0)) {
1263 		/* First time in, just get the values in */
1264 		cur->hw_cur = hw;
1265 		cur->sbt_cur = sbt;
1266 		sc->cal_count++;
1267 		goto done;
1268 	}
1269 
1270 	if (cur->hw_cur == hw) {
1271 		/* The clock is not advancing? */
1272 		sc->cal_count = 0;
1273 		atomic_store_rel_int(&cur->gen, 0);
1274 		goto done;
1275 	}
1276 
1277 	seqc_write_begin(&nex->gen);
1278 	nex->hw_prev = cur->hw_cur;
1279 	nex->sbt_prev = cur->sbt_cur;
1280 	nex->hw_cur = hw;
1281 	nex->sbt_cur = sbt;
1282 	seqc_write_end(&nex->gen);
1283 	sc->cal_current = next_up;
1284 done:
1285 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1286 	    sc, C_DIRECT_EXEC);
1287 }
1288 
1289 static void
1290 t4_calibration_start(struct adapter *sc)
1291 {
1292 	/*
1293 	 * Here if we have not done a calibration
1294 	 * then do so otherwise start the appropriate
1295 	 * timer.
1296 	 */
1297 	int i;
1298 
1299 	for (i = 0; i < CNT_CAL_INFO; i++) {
1300 		sc->cal_info[i].gen = 0;
1301 	}
1302 	sc->cal_current = 0;
1303 	sc->cal_count = 0;
1304 	sc->cal_gen = 0;
1305 	t4_calibration(sc);
1306 }
1307 
1308 static int
1309 t4_attach(device_t dev)
1310 {
1311 	struct adapter *sc;
1312 	int rc = 0, i, j, rqidx, tqidx, nports;
1313 	struct make_dev_args mda;
1314 	struct intrs_and_queues iaq;
1315 	struct sge *s;
1316 	uint32_t *buf;
1317 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1318 	int ofld_tqidx;
1319 #endif
1320 #ifdef TCP_OFFLOAD
1321 	int ofld_rqidx;
1322 #endif
1323 #ifdef DEV_NETMAP
1324 	int nm_rqidx, nm_tqidx;
1325 #endif
1326 	int num_vis;
1327 
1328 	sc = device_get_softc(dev);
1329 	sc->dev = dev;
1330 	sysctl_ctx_init(&sc->ctx);
1331 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1332 	if (TUNABLE_INT_FETCH("hw.cxgbe.iflags", &sc->intr_flags) == 0)
1333 		sc->intr_flags = IHF_INTR_CLEAR_ON_INIT | IHF_CLR_ALL_UNIGNORED;
1334 
1335 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1336 		t5_attribute_workaround(dev);
1337 	pci_enable_busmaster(dev);
1338 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1339 		uint32_t v;
1340 
1341 		pci_set_max_read_req(dev, 4096);
1342 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1343 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1344 		if (pcie_relaxed_ordering == 0 &&
1345 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1346 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1347 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1348 		} else if (pcie_relaxed_ordering == 1 &&
1349 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1350 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1351 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1352 		}
1353 	}
1354 
1355 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1356 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1357 	sc->traceq = -1;
1358 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1359 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1360 	    device_get_nameunit(dev));
1361 
1362 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1363 	    device_get_nameunit(dev));
1364 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1365 	t4_add_adapter(sc);
1366 
1367 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1368 	TAILQ_INIT(&sc->sfl);
1369 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1370 
1371 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1372 
1373 	sc->policy = NULL;
1374 	rw_init(&sc->policy_lock, "connection offload policy");
1375 
1376 	callout_init(&sc->ktls_tick, 1);
1377 
1378 	callout_init(&sc->cal_callout, 1);
1379 
1380 	refcount_init(&sc->vxlan_refcount, 0);
1381 
1382 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1383 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1384 
1385 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1386 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1387 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1388 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1389 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1390 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1391 
1392 	rc = t4_map_bars_0_and_4(sc);
1393 	if (rc != 0)
1394 		goto done; /* error message displayed already */
1395 
1396 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1397 	memset(sc->port_map, 0xff, sizeof(sc->port_map));
1398 
1399 	/* Prepare the adapter for operation. */
1400 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1401 	rc = -t4_prep_adapter(sc, buf);
1402 	free(buf, M_CXGBE);
1403 	if (rc != 0) {
1404 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1405 		goto done;
1406 	}
1407 
1408 	/*
1409 	 * This is the real PF# to which we're attaching.  Works from within PCI
1410 	 * passthrough environments too, where pci_get_function() could return a
1411 	 * different PF# depending on the passthrough configuration.  We need to
1412 	 * use the real PF# in all our communication with the firmware.
1413 	 */
1414 	j = t4_read_reg(sc, A_PL_WHOAMI);
1415 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1416 	sc->mbox = sc->pf;
1417 
1418 	t4_init_devnames(sc);
1419 	if (sc->names == NULL) {
1420 		rc = ENOTSUP;
1421 		goto done; /* error message displayed already */
1422 	}
1423 
1424 	/*
1425 	 * Do this really early, with the memory windows set up even before the
1426 	 * character device.  The userland tool's register i/o and mem read
1427 	 * will work even in "recovery mode".
1428 	 */
1429 	setup_memwin(sc);
1430 	if (t4_init_devlog_ncores_params(sc, 0) == 0)
1431 		fixup_devlog_ncores_params(sc);
1432 	make_dev_args_init(&mda);
1433 	mda.mda_devsw = &t4_cdevsw;
1434 	mda.mda_uid = UID_ROOT;
1435 	mda.mda_gid = GID_WHEEL;
1436 	mda.mda_mode = 0600;
1437 	mda.mda_si_drv1 = sc;
1438 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1439 	if (rc != 0)
1440 		device_printf(dev, "failed to create nexus char device: %d.\n",
1441 		    rc);
1442 
1443 	/* Go no further if recovery mode has been requested. */
1444 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1445 		device_printf(dev, "recovery mode.\n");
1446 		goto done;
1447 	}
1448 
1449 #if defined(__i386__)
1450 	if ((cpu_feature & CPUID_CX8) == 0) {
1451 		device_printf(dev, "64 bit atomics not available.\n");
1452 		rc = ENOTSUP;
1453 		goto done;
1454 	}
1455 #endif
1456 
1457 	/* Contact the firmware and try to become the master driver. */
1458 	rc = contact_firmware(sc);
1459 	if (rc != 0)
1460 		goto done; /* error message displayed already */
1461 	MPASS(sc->flags & FW_OK);
1462 
1463 	rc = get_params__pre_init(sc);
1464 	if (rc != 0)
1465 		goto done; /* error message displayed already */
1466 
1467 	if (sc->flags & MASTER_PF) {
1468 		rc = partition_resources(sc);
1469 		if (rc != 0)
1470 			goto done; /* error message displayed already */
1471 	}
1472 
1473 	rc = get_params__post_init(sc);
1474 	if (rc != 0)
1475 		goto done; /* error message displayed already */
1476 
1477 	rc = set_params__post_init(sc);
1478 	if (rc != 0)
1479 		goto done; /* error message displayed already */
1480 
1481 	rc = t4_map_bar_2(sc);
1482 	if (rc != 0)
1483 		goto done; /* error message displayed already */
1484 
1485 	rc = t4_adj_doorbells(sc);
1486 	if (rc != 0)
1487 		goto done; /* error message displayed already */
1488 
1489 	rc = t4_create_dma_tag(sc);
1490 	if (rc != 0)
1491 		goto done; /* error message displayed already */
1492 
1493 	/*
1494 	 * First pass over all the ports - allocate VIs and initialize some
1495 	 * basic parameters like mac address, port type, etc.
1496 	 */
1497 	for_each_port(sc, i) {
1498 		struct port_info *pi;
1499 
1500 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1501 		sc->port[i] = pi;
1502 
1503 		/* These must be set before t4_port_init */
1504 		pi->adapter = sc;
1505 		pi->port_id = i;
1506 		/*
1507 		 * XXX: vi[0] is special so we can't delay this allocation until
1508 		 * pi->nvi's final value is known.
1509 		 */
1510 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1511 		    M_ZERO | M_WAITOK);
1512 
1513 		/*
1514 		 * Allocate the "main" VI and initialize parameters
1515 		 * like mac addr.
1516 		 */
1517 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1518 		if (rc != 0) {
1519 			device_printf(dev, "unable to initialize port %d: %d\n",
1520 			    i, rc);
1521 			free(pi->vi, M_CXGBE);
1522 			free(pi, M_CXGBE);
1523 			sc->port[i] = NULL;
1524 			goto done;
1525 		}
1526 
1527 		if (is_bt(pi->port_type))
1528 			setbit(&sc->bt_map, pi->hw_port);
1529 		else
1530 			MPASS(!isset(&sc->bt_map, pi->hw_port));
1531 
1532 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1533 		    device_get_nameunit(dev), i);
1534 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1535 		for (j = 0; j < sc->params.tp.lb_nchan; j++)
1536 			sc->chan_map[pi->tx_chan + j] = i;
1537 		sc->port_map[pi->hw_port] = i;
1538 
1539 		/*
1540 		 * The MPS counter for FCS errors doesn't work correctly on the
1541 		 * T6 so we use the MAC counter here.  Which MAC is in use
1542 		 * depends on the link settings which will be known when the
1543 		 * link comes up.
1544 		 */
1545 		if (is_t6(sc))
1546 			pi->fcs_reg = -1;
1547 		else
1548 			pi->fcs_reg = A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L;
1549 		pi->fcs_base = 0;
1550 
1551 		/* All VIs on this port share this media. */
1552 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1553 		    cxgbe_media_status);
1554 
1555 		PORT_LOCK(pi);
1556 		init_link_config(pi);
1557 		fixup_link_config(pi);
1558 		build_medialist(pi);
1559 		if (fixed_ifmedia(pi))
1560 			pi->flags |= FIXED_IFMEDIA;
1561 		PORT_UNLOCK(pi);
1562 
1563 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1564 		    t4_ifnet_unit(sc, pi));
1565 		if (pi->dev == NULL) {
1566 			device_printf(dev,
1567 			    "failed to add device for port %d.\n", i);
1568 			rc = ENXIO;
1569 			goto done;
1570 		}
1571 		pi->vi[0].dev = pi->dev;
1572 		device_set_softc(pi->dev, pi);
1573 	}
1574 
1575 	/*
1576 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1577 	 */
1578 	nports = sc->params.nports;
1579 	rc = cfg_itype_and_nqueues(sc, &iaq);
1580 	if (rc != 0)
1581 		goto done; /* error message displayed already */
1582 
1583 	num_vis = iaq.num_vis;
1584 	sc->intr_type = iaq.intr_type;
1585 	sc->intr_count = iaq.nirq;
1586 
1587 	s = &sc->sge;
1588 	s->nctrlq = max(sc->params.nports, sc->params.ncores);
1589 	s->nrxq = nports * iaq.nrxq;
1590 	s->ntxq = nports * iaq.ntxq;
1591 	if (num_vis > 1) {
1592 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1593 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1594 	}
1595 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1596 	s->neq += nports;		/* ctrl queues: 1 per port */
1597 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1598 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1599 	if (is_offload(sc) || is_ethoffload(sc)) {
1600 		s->nofldtxq = nports * iaq.nofldtxq;
1601 		if (num_vis > 1)
1602 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1603 		s->neq += s->nofldtxq;
1604 
1605 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1606 		    M_CXGBE, M_ZERO | M_WAITOK);
1607 	}
1608 #endif
1609 #ifdef TCP_OFFLOAD
1610 	if (is_offload(sc)) {
1611 		s->nofldrxq = nports * iaq.nofldrxq;
1612 		if (num_vis > 1)
1613 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1614 		s->neq += s->nofldrxq;	/* free list */
1615 		s->niq += s->nofldrxq;
1616 
1617 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1618 		    M_CXGBE, M_ZERO | M_WAITOK);
1619 	}
1620 #endif
1621 #ifdef DEV_NETMAP
1622 	s->nnmrxq = 0;
1623 	s->nnmtxq = 0;
1624 	if (t4_native_netmap & NN_MAIN_VI) {
1625 		s->nnmrxq += nports * iaq.nnmrxq;
1626 		s->nnmtxq += nports * iaq.nnmtxq;
1627 	}
1628 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1629 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1630 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1631 	}
1632 	s->neq += s->nnmtxq + s->nnmrxq;
1633 	s->niq += s->nnmrxq;
1634 
1635 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1636 	    M_CXGBE, M_ZERO | M_WAITOK);
1637 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1638 	    M_CXGBE, M_ZERO | M_WAITOK);
1639 #endif
1640 	MPASS(s->niq <= s->iqmap_sz);
1641 	MPASS(s->neq <= s->eqmap_sz);
1642 
1643 	s->ctrlq = malloc(s->nctrlq * sizeof(struct sge_wrq), M_CXGBE,
1644 	    M_ZERO | M_WAITOK);
1645 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1646 	    M_ZERO | M_WAITOK);
1647 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1648 	    M_ZERO | M_WAITOK);
1649 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1650 	    M_ZERO | M_WAITOK);
1651 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1652 	    M_ZERO | M_WAITOK);
1653 
1654 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1655 	    M_ZERO | M_WAITOK);
1656 
1657 	t4_init_l2t(sc, M_WAITOK);
1658 	t4_init_smt(sc, M_WAITOK);
1659 	t4_init_tx_sched(sc);
1660 	t4_init_atid_table(sc);
1661 #ifdef RATELIMIT
1662 	t4_init_etid_table(sc);
1663 #endif
1664 #ifdef INET6
1665 	t4_init_clip_table(sc);
1666 #endif
1667 	if (sc->vres.key.size != 0)
1668 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1669 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1670 	t4_init_tpt(sc);
1671 
1672 	/*
1673 	 * Second pass over the ports.  This time we know the number of rx and
1674 	 * tx queues that each port should get.
1675 	 */
1676 	rqidx = tqidx = 0;
1677 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1678 	ofld_tqidx = 0;
1679 #endif
1680 #ifdef TCP_OFFLOAD
1681 	ofld_rqidx = 0;
1682 #endif
1683 #ifdef DEV_NETMAP
1684 	nm_rqidx = nm_tqidx = 0;
1685 #endif
1686 	for_each_port(sc, i) {
1687 		struct port_info *pi = sc->port[i];
1688 		struct vi_info *vi;
1689 
1690 		if (pi == NULL)
1691 			continue;
1692 
1693 		pi->nvi = num_vis;
1694 		for_each_vi(pi, j, vi) {
1695 			vi->pi = pi;
1696 			vi->adapter = sc;
1697 			vi->first_intr = -1;
1698 			vi->qsize_rxq = t4_qsize_rxq;
1699 			vi->qsize_txq = t4_qsize_txq;
1700 
1701 			vi->first_rxq = rqidx;
1702 			vi->first_txq = tqidx;
1703 			vi->tmr_idx = t4_tmr_idx;
1704 			vi->pktc_idx = t4_pktc_idx;
1705 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1706 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1707 
1708 			rqidx += vi->nrxq;
1709 			tqidx += vi->ntxq;
1710 
1711 			if (j == 0 && vi->ntxq > 1)
1712 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1713 			else
1714 				vi->rsrv_noflowq = 0;
1715 
1716 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1717 			vi->first_ofld_txq = ofld_tqidx;
1718 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1719 			ofld_tqidx += vi->nofldtxq;
1720 #endif
1721 #ifdef TCP_OFFLOAD
1722 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1723 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1724 			vi->first_ofld_rxq = ofld_rqidx;
1725 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1726 
1727 			ofld_rqidx += vi->nofldrxq;
1728 #endif
1729 #ifdef DEV_NETMAP
1730 			vi->first_nm_rxq = nm_rqidx;
1731 			vi->first_nm_txq = nm_tqidx;
1732 			if (j == 0) {
1733 				vi->nnmrxq = iaq.nnmrxq;
1734 				vi->nnmtxq = iaq.nnmtxq;
1735 			} else {
1736 				vi->nnmrxq = iaq.nnmrxq_vi;
1737 				vi->nnmtxq = iaq.nnmtxq_vi;
1738 			}
1739 			nm_rqidx += vi->nnmrxq;
1740 			nm_tqidx += vi->nnmtxq;
1741 #endif
1742 		}
1743 	}
1744 
1745 	rc = t4_setup_intr_handlers(sc);
1746 	if (rc != 0) {
1747 		device_printf(dev,
1748 		    "failed to setup interrupt handlers: %d\n", rc);
1749 		goto done;
1750 	}
1751 
1752 	bus_identify_children(dev);
1753 
1754 	/*
1755 	 * Ensure thread-safe mailbox access (in debug builds).
1756 	 *
1757 	 * So far this was the only thread accessing the mailbox but various
1758 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1759 	 * will access the mailbox from different threads.
1760 	 */
1761 	sc->flags |= CHK_MBOX_ACCESS;
1762 
1763 	bus_attach_children(dev);
1764 	t4_calibration_start(sc);
1765 
1766 	device_printf(dev,
1767 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1768 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1769 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1770 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1771 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1772 
1773 	t4_set_desc(sc);
1774 
1775 	notify_siblings(dev, 0);
1776 
1777 done:
1778 	if (rc != 0 && sc->cdev) {
1779 		/* cdev was created and so cxgbetool works; recover that way. */
1780 		device_printf(dev,
1781 		    "error during attach, adapter is now in recovery mode.\n");
1782 		rc = 0;
1783 	}
1784 
1785 	if (rc != 0)
1786 		t4_detach_common(dev);
1787 	else
1788 		t4_sysctls(sc);
1789 
1790 	return (rc);
1791 }
1792 
1793 static int
1794 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1795 {
1796 	struct adapter *sc;
1797 	struct port_info *pi;
1798 	int i;
1799 
1800 	sc = device_get_softc(bus);
1801 	for_each_port(sc, i) {
1802 		pi = sc->port[i];
1803 		if (pi != NULL && pi->dev == dev) {
1804 			sbuf_printf(sb, "port=%d", pi->port_id);
1805 			break;
1806 		}
1807 	}
1808 	return (0);
1809 }
1810 
1811 static int
1812 t4_ready(device_t dev)
1813 {
1814 	struct adapter *sc;
1815 
1816 	sc = device_get_softc(dev);
1817 	if (sc->flags & FW_OK)
1818 		return (0);
1819 	return (ENXIO);
1820 }
1821 
1822 static int
1823 t4_read_port_device(device_t dev, int port, device_t *child)
1824 {
1825 	struct adapter *sc;
1826 	struct port_info *pi;
1827 
1828 	sc = device_get_softc(dev);
1829 	if (port < 0 || port >= MAX_NPORTS)
1830 		return (EINVAL);
1831 	pi = sc->port[port];
1832 	if (pi == NULL || pi->dev == NULL)
1833 		return (ENXIO);
1834 	*child = pi->dev;
1835 	return (0);
1836 }
1837 
1838 static int
1839 notify_siblings(device_t dev, int detaching)
1840 {
1841 	device_t sibling;
1842 	int error, i;
1843 
1844 	error = 0;
1845 	for (i = 0; i < PCI_FUNCMAX; i++) {
1846 		if (i == pci_get_function(dev))
1847 			continue;
1848 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1849 		    pci_get_slot(dev), i);
1850 		if (sibling == NULL || !device_is_attached(sibling))
1851 			continue;
1852 		if (detaching)
1853 			error = T4_DETACH_CHILD(sibling);
1854 		else
1855 			(void)T4_ATTACH_CHILD(sibling);
1856 		if (error)
1857 			break;
1858 	}
1859 	return (error);
1860 }
1861 
1862 /*
1863  * Idempotent
1864  */
1865 static int
1866 t4_detach(device_t dev)
1867 {
1868 	int rc;
1869 
1870 	rc = notify_siblings(dev, 1);
1871 	if (rc) {
1872 		device_printf(dev,
1873 		    "failed to detach sibling devices: %d\n", rc);
1874 		return (rc);
1875 	}
1876 
1877 	return (t4_detach_common(dev));
1878 }
1879 
1880 int
1881 t4_detach_common(device_t dev)
1882 {
1883 	struct adapter *sc;
1884 	struct port_info *pi;
1885 	int i, rc;
1886 
1887 	sc = device_get_softc(dev);
1888 
1889 #ifdef TCP_OFFLOAD
1890 	rc = deactivate_all_uld(sc);
1891 	if (rc) {
1892 		device_printf(dev,
1893 		    "failed to detach upper layer drivers: %d\n", rc);
1894 		return (rc);
1895 	}
1896 #endif
1897 
1898 	if (sc->cdev) {
1899 		destroy_dev(sc->cdev);
1900 		sc->cdev = NULL;
1901 	}
1902 
1903 	sx_xlock(&t4_list_lock);
1904 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1905 	sx_xunlock(&t4_list_lock);
1906 
1907 	sc->flags &= ~CHK_MBOX_ACCESS;
1908 	if (sc->flags & FULL_INIT_DONE) {
1909 		if (!(sc->flags & IS_VF))
1910 			t4_intr_disable(sc);
1911 	}
1912 
1913 	if (device_is_attached(dev)) {
1914 		rc = bus_detach_children(dev);
1915 		if (rc) {
1916 			device_printf(dev,
1917 			    "failed to detach child devices: %d\n", rc);
1918 			return (rc);
1919 		}
1920 	}
1921 
1922 	for (i = 0; i < sc->intr_count; i++)
1923 		t4_free_irq(sc, &sc->irq[i]);
1924 
1925 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1926 		t4_free_tx_sched(sc);
1927 
1928 	for (i = 0; i < MAX_NPORTS; i++) {
1929 		pi = sc->port[i];
1930 		if (pi) {
1931 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1932 
1933 			mtx_destroy(&pi->pi_lock);
1934 			free(pi->vi, M_CXGBE);
1935 			free(pi, M_CXGBE);
1936 		}
1937 	}
1938 	callout_stop(&sc->cal_callout);
1939 	callout_drain(&sc->cal_callout);
1940 	device_delete_children(dev);
1941 	sysctl_ctx_free(&sc->ctx);
1942 	adapter_full_uninit(sc);
1943 
1944 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1945 		t4_fw_bye(sc, sc->mbox);
1946 
1947 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1948 		pci_release_msi(dev);
1949 
1950 	if (sc->regs_res)
1951 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1952 		    sc->regs_res);
1953 
1954 	if (sc->udbs_res)
1955 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1956 		    sc->udbs_res);
1957 
1958 	if (sc->msix_res)
1959 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1960 		    sc->msix_res);
1961 
1962 	if (sc->l2t)
1963 		t4_free_l2t(sc);
1964 	if (sc->smt)
1965 		t4_free_smt(sc->smt);
1966 	t4_free_atid_table(sc);
1967 #ifdef RATELIMIT
1968 	t4_free_etid_table(sc);
1969 #endif
1970 	if (sc->key_map)
1971 		vmem_destroy(sc->key_map);
1972 	t4_free_tpt(sc);
1973 #ifdef INET6
1974 	t4_destroy_clip_table(sc);
1975 #endif
1976 
1977 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1978 	free(sc->sge.ofld_txq, M_CXGBE);
1979 #endif
1980 #ifdef TCP_OFFLOAD
1981 	free(sc->sge.ofld_rxq, M_CXGBE);
1982 #endif
1983 #ifdef DEV_NETMAP
1984 	free(sc->sge.nm_rxq, M_CXGBE);
1985 	free(sc->sge.nm_txq, M_CXGBE);
1986 #endif
1987 	free(sc->irq, M_CXGBE);
1988 	free(sc->sge.rxq, M_CXGBE);
1989 	free(sc->sge.txq, M_CXGBE);
1990 	free(sc->sge.ctrlq, M_CXGBE);
1991 	free(sc->sge.iqmap, M_CXGBE);
1992 	free(sc->sge.eqmap, M_CXGBE);
1993 	free(sc->tids.ftid_tab, M_CXGBE);
1994 	free(sc->tids.hpftid_tab, M_CXGBE);
1995 	free_hftid_hash(&sc->tids);
1996 	free(sc->tids.tid_tab, M_CXGBE);
1997 	t4_destroy_dma_tag(sc);
1998 
1999 	callout_drain(&sc->ktls_tick);
2000 	callout_drain(&sc->sfl_callout);
2001 	if (mtx_initialized(&sc->tids.ftid_lock)) {
2002 		mtx_destroy(&sc->tids.ftid_lock);
2003 		cv_destroy(&sc->tids.ftid_cv);
2004 	}
2005 	if (mtx_initialized(&sc->tids.atid_lock))
2006 		mtx_destroy(&sc->tids.atid_lock);
2007 	if (mtx_initialized(&sc->ifp_lock))
2008 		mtx_destroy(&sc->ifp_lock);
2009 
2010 	if (rw_initialized(&sc->policy_lock)) {
2011 		rw_destroy(&sc->policy_lock);
2012 #ifdef TCP_OFFLOAD
2013 		if (sc->policy != NULL)
2014 			free_offload_policy(sc->policy);
2015 #endif
2016 	}
2017 
2018 	for (i = 0; i < NUM_MEMWIN; i++) {
2019 		struct memwin *mw = &sc->memwin[i];
2020 
2021 		if (rw_initialized(&mw->mw_lock))
2022 			rw_destroy(&mw->mw_lock);
2023 	}
2024 
2025 	mtx_destroy(&sc->sfl_lock);
2026 	mtx_destroy(&sc->reg_lock);
2027 	mtx_destroy(&sc->sc_lock);
2028 
2029 	bzero(sc, sizeof(*sc));
2030 
2031 	return (0);
2032 }
2033 
2034 static inline int
2035 stop_adapter(struct adapter *sc)
2036 {
2037 	struct port_info *pi;
2038 	int i;
2039 
2040 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2041 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2042 			 __func__, curthread, sc->flags, sc->error_flags);
2043 		return (EALREADY);
2044 	}
2045 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2046 		 sc->flags, sc->error_flags);
2047 	t4_shutdown_adapter(sc);
2048 	for_each_port(sc, i) {
2049 		pi = sc->port[i];
2050 		if (pi == NULL)
2051 			continue;
2052 		PORT_LOCK(pi);
2053 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
2054 			/*
2055 			 * t4_shutdown_adapter has already shut down all the
2056 			 * PHYs but it also disables interrupts and DMA so there
2057 			 * won't be a link interrupt.  Update the state manually
2058 			 * if the link was up previously and inform the kernel.
2059 			 */
2060 			pi->link_cfg.link_ok = false;
2061 			t4_os_link_changed(pi);
2062 		}
2063 		PORT_UNLOCK(pi);
2064 	}
2065 
2066 	return (0);
2067 }
2068 
2069 static inline int
2070 restart_adapter(struct adapter *sc)
2071 {
2072 	uint32_t val;
2073 
2074 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
2075 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
2076 			 __func__, curthread, sc->flags, sc->error_flags);
2077 		return (EALREADY);
2078 	}
2079 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
2080 		 sc->flags, sc->error_flags);
2081 
2082 	MPASS(hw_off_limits(sc));
2083 	MPASS((sc->flags & FW_OK) == 0);
2084 	MPASS((sc->flags & MASTER_PF) == 0);
2085 	MPASS(sc->reset_thread == NULL);
2086 
2087 	/*
2088 	 * The adapter is supposed to be back on PCIE with its config space and
2089 	 * BARs restored to their state before reset.  Register access via
2090 	 * t4_read_reg BAR0 should just work.
2091 	 */
2092 	sc->reset_thread = curthread;
2093 	val = t4_read_reg(sc, A_PL_WHOAMI);
2094 	if (val == 0xffffffff || val == 0xeeeeeeee) {
2095 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
2096 		sc->reset_thread = NULL;
2097 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
2098 		return (ENXIO);
2099 	}
2100 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
2101 	atomic_add_int(&sc->incarnation, 1);
2102 	atomic_add_int(&sc->num_resets, 1);
2103 
2104 	return (0);
2105 }
2106 
2107 static inline void
2108 set_adapter_hwstatus(struct adapter *sc, const bool usable)
2109 {
2110 	if (usable) {
2111 		/* Must be marked reusable by the designated thread. */
2112 		ASSERT_SYNCHRONIZED_OP(sc);
2113 		MPASS(sc->reset_thread == curthread);
2114 		mtx_lock(&sc->reg_lock);
2115 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2116 		mtx_unlock(&sc->reg_lock);
2117 	} else {
2118 		/* Mark the adapter totally off limits. */
2119 		begin_synchronized_op(sc, NULL, SLEEP_OK, "t4hwsts");
2120 		mtx_lock(&sc->reg_lock);
2121 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2122 		mtx_unlock(&sc->reg_lock);
2123 		sc->flags &= ~(FW_OK | MASTER_PF);
2124 		sc->reset_thread = NULL;
2125 		end_synchronized_op(sc, 0);
2126 	}
2127 }
2128 
2129 static int
2130 stop_lld(struct adapter *sc)
2131 {
2132 	struct port_info *pi;
2133 	struct vi_info *vi;
2134 	if_t ifp;
2135 	struct sge_rxq *rxq;
2136 	struct sge_txq *txq;
2137 	struct sge_wrq *wrq;
2138 #ifdef TCP_OFFLOAD
2139 	struct sge_ofld_rxq *ofld_rxq;
2140 #endif
2141 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2142 	struct sge_ofld_txq *ofld_txq;
2143 #endif
2144 	int rc, i, j, k;
2145 
2146 	/*
2147 	 * XXX: Can there be a synch_op in progress that will hang because
2148 	 * hardware has been stopped?  We'll hang too and the solution will be
2149 	 * to use a version of begin_synch_op that wakes up existing synch_op
2150 	 * with errors.  Maybe stop_adapter should do this wakeup?
2151 	 *
2152 	 * I don't think any synch_op could get stranded waiting for DMA or
2153 	 * interrupt so I think we're okay here.  Remove this comment block
2154 	 * after testing.
2155 	 */
2156 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2157 	if (rc != 0)
2158 		return (ENXIO);
2159 
2160 	/* Quiesce all activity. */
2161 	for_each_port(sc, i) {
2162 		pi = sc->port[i];
2163 		if (pi == NULL)
2164 			continue;
2165 		pi->vxlan_tcam_entry = false;
2166 		for_each_vi(pi, j, vi) {
2167 			vi->xact_addr_filt = -1;
2168 			mtx_lock(&vi->tick_mtx);
2169 			vi->flags |= VI_SKIP_STATS;
2170 			mtx_unlock(&vi->tick_mtx);
2171 			if (!(vi->flags & VI_INIT_DONE))
2172 				continue;
2173 
2174 			ifp = vi->ifp;
2175 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2176 				mtx_lock(&vi->tick_mtx);
2177 				callout_stop(&vi->tick);
2178 				mtx_unlock(&vi->tick_mtx);
2179 				callout_drain(&vi->tick);
2180 			}
2181 
2182 			/*
2183 			 * Note that the HW is not available.
2184 			 */
2185 			for_each_txq(vi, k, txq) {
2186 				TXQ_LOCK(txq);
2187 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2188 				TXQ_UNLOCK(txq);
2189 			}
2190 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2191 			for_each_ofld_txq(vi, k, ofld_txq) {
2192 				TXQ_LOCK(&ofld_txq->wrq);
2193 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2194 				TXQ_UNLOCK(&ofld_txq->wrq);
2195 			}
2196 #endif
2197 			for_each_rxq(vi, k, rxq) {
2198 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2199 			}
2200 #if defined(TCP_OFFLOAD)
2201 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2202 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2203 			}
2204 #endif
2205 
2206 			quiesce_vi(vi);
2207 		}
2208 
2209 		if (sc->flags & FULL_INIT_DONE) {
2210 			/* Control queue */
2211 			wrq = &sc->sge.ctrlq[i];
2212 			TXQ_LOCK(wrq);
2213 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2214 			TXQ_UNLOCK(wrq);
2215 			quiesce_wrq(wrq);
2216 		}
2217 
2218 		if (pi->flags & HAS_TRACEQ) {
2219 			pi->flags &= ~HAS_TRACEQ;
2220 			sc->traceq = -1;
2221 			sc->tracer_valid = 0;
2222 			sc->tracer_enabled = 0;
2223 		}
2224 	}
2225 	if (sc->flags & FULL_INIT_DONE) {
2226 		/* Firmware event queue */
2227 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2228 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2229 	}
2230 
2231 	/* Stop calibration */
2232 	callout_stop(&sc->cal_callout);
2233 	callout_drain(&sc->cal_callout);
2234 
2235 	if (t4_clock_gate_on_suspend) {
2236 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2237 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2238 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2239 	}
2240 
2241 	end_synchronized_op(sc, 0);
2242 
2243 	stop_atid_allocator(sc);
2244 	t4_stop_l2t(sc);
2245 
2246 	return (rc);
2247 }
2248 
2249 int
2250 suspend_adapter(struct adapter *sc)
2251 {
2252 	stop_adapter(sc);
2253 	stop_lld(sc);
2254 #ifdef TCP_OFFLOAD
2255 	stop_all_uld(sc);
2256 #endif
2257 	set_adapter_hwstatus(sc, false);
2258 
2259 	return (0);
2260 }
2261 
2262 static int
2263 t4_suspend(device_t dev)
2264 {
2265 	struct adapter *sc = device_get_softc(dev);
2266 	int rc;
2267 
2268 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2269 	rc = suspend_adapter(sc);
2270 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2271 
2272 	return (rc);
2273 }
2274 
2275 struct adapter_pre_reset_state {
2276 	u_int flags;
2277 	uint16_t nbmcaps;
2278 	uint16_t linkcaps;
2279 	uint16_t switchcaps;
2280 	uint16_t nvmecaps;
2281 	uint16_t niccaps;
2282 	uint16_t toecaps;
2283 	uint16_t rdmacaps;
2284 	uint16_t cryptocaps;
2285 	uint16_t iscsicaps;
2286 	uint16_t fcoecaps;
2287 
2288 	u_int cfcsum;
2289 	char cfg_file[32];
2290 
2291 	struct adapter_params params;
2292 	struct t4_virt_res vres;
2293 	struct tid_info tids;
2294 	struct sge sge;
2295 
2296 	int rawf_base;
2297 	int nrawf;
2298 
2299 };
2300 
2301 static void
2302 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2303 {
2304 
2305 	ASSERT_SYNCHRONIZED_OP(sc);
2306 
2307 	o->flags = sc->flags;
2308 
2309 	o->nbmcaps =  sc->nbmcaps;
2310 	o->linkcaps = sc->linkcaps;
2311 	o->switchcaps = sc->switchcaps;
2312 	o->nvmecaps = sc->nvmecaps;
2313 	o->niccaps = sc->niccaps;
2314 	o->toecaps = sc->toecaps;
2315 	o->rdmacaps = sc->rdmacaps;
2316 	o->cryptocaps = sc->cryptocaps;
2317 	o->iscsicaps = sc->iscsicaps;
2318 	o->fcoecaps = sc->fcoecaps;
2319 
2320 	o->cfcsum = sc->cfcsum;
2321 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2322 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2323 
2324 	o->params = sc->params;
2325 	o->vres = sc->vres;
2326 	o->tids = sc->tids;
2327 	o->sge = sc->sge;
2328 
2329 	o->rawf_base = sc->rawf_base;
2330 	o->nrawf = sc->nrawf;
2331 }
2332 
2333 static int
2334 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2335 {
2336 	int rc = 0;
2337 
2338 	ASSERT_SYNCHRONIZED_OP(sc);
2339 
2340 	/* Capabilities */
2341 #define COMPARE_CAPS(c) do { \
2342 	if (o->c##caps != sc->c##caps) { \
2343 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2344 		    sc->c##caps); \
2345 		rc = EINVAL; \
2346 	} \
2347 } while (0)
2348 	COMPARE_CAPS(nbm);
2349 	COMPARE_CAPS(link);
2350 	COMPARE_CAPS(switch);
2351 	COMPARE_CAPS(nvme);
2352 	COMPARE_CAPS(nic);
2353 	COMPARE_CAPS(toe);
2354 	COMPARE_CAPS(rdma);
2355 	COMPARE_CAPS(crypto);
2356 	COMPARE_CAPS(iscsi);
2357 	COMPARE_CAPS(fcoe);
2358 #undef COMPARE_CAPS
2359 
2360 	/* Firmware config file */
2361 	if (o->cfcsum != sc->cfcsum) {
2362 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2363 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2364 		rc = EINVAL;
2365 	}
2366 
2367 #define COMPARE_PARAM(p, name) do { \
2368 	if (o->p != sc->p) { \
2369 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2370 		rc = EINVAL; \
2371 	} \
2372 } while (0)
2373 	COMPARE_PARAM(sge.iq_start, iq_start);
2374 	COMPARE_PARAM(sge.eq_start, eq_start);
2375 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2376 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2377 	COMPARE_PARAM(tids.nftids, nftids);
2378 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2379 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2380 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2381 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2382 	COMPARE_PARAM(tids.tid_base, tid_base);
2383 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2384 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2385 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2386 	COMPARE_PARAM(rawf_base, rawf_base);
2387 	COMPARE_PARAM(nrawf, nrawf);
2388 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2389 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2390 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2391 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2392 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2393 	COMPARE_PARAM(tids.ntids, ntids);
2394 	COMPARE_PARAM(tids.etid_base, etid_base);
2395 	COMPARE_PARAM(tids.etid_end, etid_end);
2396 	COMPARE_PARAM(tids.netids, netids);
2397 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2398 	COMPARE_PARAM(params.ethoffload, ethoffload);
2399 	COMPARE_PARAM(tids.natids, natids);
2400 	COMPARE_PARAM(tids.stid_base, stid_base);
2401 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2402 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2403 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2404 	COMPARE_PARAM(vres.stag.start, stag_start);
2405 	COMPARE_PARAM(vres.stag.size, stag_size);
2406 	COMPARE_PARAM(vres.rq.start, rq_start);
2407 	COMPARE_PARAM(vres.rq.size, rq_size);
2408 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2409 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2410 	COMPARE_PARAM(vres.qp.start, qp_start);
2411 	COMPARE_PARAM(vres.qp.size, qp_size);
2412 	COMPARE_PARAM(vres.cq.start, cq_start);
2413 	COMPARE_PARAM(vres.cq.size, cq_size);
2414 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2415 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2416 	COMPARE_PARAM(vres.srq.start, srq_start);
2417 	COMPARE_PARAM(vres.srq.size, srq_size);
2418 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2419 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2420 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2421 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2422 	COMPARE_PARAM(vres.key.start, key_start);
2423 	COMPARE_PARAM(vres.key.size, key_size);
2424 #undef COMPARE_PARAM
2425 
2426 	return (rc);
2427 }
2428 
2429 static int
2430 restart_lld(struct adapter *sc)
2431 {
2432 	struct adapter_pre_reset_state *old_state = NULL;
2433 	struct port_info *pi;
2434 	struct vi_info *vi;
2435 	if_t ifp;
2436 	struct sge_txq *txq;
2437 	int rc, i, j, k;
2438 
2439 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2440 	if (rc != 0)
2441 		return (ENXIO);
2442 
2443 	/* Restore memory window. */
2444 	setup_memwin(sc);
2445 
2446 	/* Go no further if recovery mode has been requested. */
2447 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2448 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2449 		rc = 0;
2450 		set_adapter_hwstatus(sc, true);
2451 		goto done;
2452 	}
2453 
2454 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2455 	save_caps_and_params(sc, old_state);
2456 
2457 	/* Reestablish contact with firmware and become the primary PF. */
2458 	rc = contact_firmware(sc);
2459 	if (rc != 0)
2460 		goto done; /* error message displayed already */
2461 	MPASS(sc->flags & FW_OK);
2462 
2463 	if (sc->flags & MASTER_PF) {
2464 		rc = partition_resources(sc);
2465 		if (rc != 0)
2466 			goto done; /* error message displayed already */
2467 	}
2468 
2469 	rc = get_params__post_init(sc);
2470 	if (rc != 0)
2471 		goto done; /* error message displayed already */
2472 
2473 	rc = set_params__post_init(sc);
2474 	if (rc != 0)
2475 		goto done; /* error message displayed already */
2476 
2477 	rc = compare_caps_and_params(sc, old_state);
2478 	if (rc != 0)
2479 		goto done; /* error message displayed already */
2480 
2481 	for_each_port(sc, i) {
2482 		pi = sc->port[i];
2483 		MPASS(pi != NULL);
2484 		MPASS(pi->vi != NULL);
2485 		MPASS(pi->vi[0].dev == pi->dev);
2486 
2487 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2488 		if (rc != 0) {
2489 			CH_ERR(sc,
2490 			    "failed to re-initialize port %d: %d\n", i, rc);
2491 			goto done;
2492 		}
2493 		MPASS(sc->chan_map[pi->tx_chan] == i);
2494 
2495 		PORT_LOCK(pi);
2496 		fixup_link_config(pi);
2497 		build_medialist(pi);
2498 		PORT_UNLOCK(pi);
2499 		for_each_vi(pi, j, vi) {
2500 			if (IS_MAIN_VI(vi))
2501 				continue;
2502 			rc = alloc_extra_vi(sc, pi, vi);
2503 			if (rc != 0) {
2504 				CH_ERR(vi,
2505 				    "failed to re-allocate extra VI: %d\n", rc);
2506 				goto done;
2507 			}
2508 		}
2509 	}
2510 
2511 	/*
2512 	 * Interrupts and queues are about to be enabled and other threads will
2513 	 * want to access the hardware too.  It is safe to do so.  Note that
2514 	 * this thread is still in the middle of a synchronized_op.
2515 	 */
2516 	set_adapter_hwstatus(sc, true);
2517 
2518 	if (sc->flags & FULL_INIT_DONE) {
2519 		rc = adapter_full_init(sc);
2520 		if (rc != 0) {
2521 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2522 			goto done;
2523 		}
2524 
2525 		if (sc->vxlan_refcount > 0)
2526 			enable_vxlan_rx(sc);
2527 
2528 		for_each_port(sc, i) {
2529 			pi = sc->port[i];
2530 			for_each_vi(pi, j, vi) {
2531 				mtx_lock(&vi->tick_mtx);
2532 				vi->flags &= ~VI_SKIP_STATS;
2533 				mtx_unlock(&vi->tick_mtx);
2534 				if (!(vi->flags & VI_INIT_DONE))
2535 					continue;
2536 				rc = vi_full_init(vi);
2537 				if (rc != 0) {
2538 					CH_ERR(vi, "failed to re-initialize "
2539 					    "interface: %d\n", rc);
2540 					goto done;
2541 				}
2542 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2543 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2544 					t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
2545 					pi->flags |= HAS_TRACEQ;
2546 				}
2547 
2548 				ifp = vi->ifp;
2549 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2550 					continue;
2551 				/*
2552 				 * Note that we do not setup multicast addresses
2553 				 * in the first pass.  This ensures that the
2554 				 * unicast DMACs for all VIs on all ports get an
2555 				 * MPS TCAM entry.
2556 				 */
2557 				rc = update_mac_settings(ifp, XGMAC_ALL &
2558 				    ~XGMAC_MCADDRS);
2559 				if (rc != 0) {
2560 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2561 					goto done;
2562 				}
2563 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2564 				    true);
2565 				if (rc != 0) {
2566 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2567 					goto done;
2568 				}
2569 				for_each_txq(vi, k, txq) {
2570 					TXQ_LOCK(txq);
2571 					txq->eq.flags |= EQ_ENABLED;
2572 					TXQ_UNLOCK(txq);
2573 				}
2574 				mtx_lock(&vi->tick_mtx);
2575 				callout_schedule(&vi->tick, hz);
2576 				mtx_unlock(&vi->tick_mtx);
2577 			}
2578 			PORT_LOCK(pi);
2579 			if (pi->up_vis > 0) {
2580 				t4_update_port_info(pi);
2581 				fixup_link_config(pi);
2582 				build_medialist(pi);
2583 				apply_link_config(pi);
2584 				if (pi->link_cfg.link_ok)
2585 					t4_os_link_changed(pi);
2586 			}
2587 			PORT_UNLOCK(pi);
2588 		}
2589 
2590 		/* Now reprogram the L2 multicast addresses. */
2591 		for_each_port(sc, i) {
2592 			pi = sc->port[i];
2593 			for_each_vi(pi, j, vi) {
2594 				if (!(vi->flags & VI_INIT_DONE))
2595 					continue;
2596 				ifp = vi->ifp;
2597 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2598 					continue;
2599 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2600 				if (rc != 0) {
2601 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2602 					rc = 0;	/* carry on */
2603 				}
2604 			}
2605 		}
2606 	}
2607 
2608 	/* Reset all calibration */
2609 	t4_calibration_start(sc);
2610 done:
2611 	end_synchronized_op(sc, 0);
2612 	free(old_state, M_CXGBE);
2613 
2614 	restart_atid_allocator(sc);
2615 	t4_restart_l2t(sc);
2616 
2617 	return (rc);
2618 }
2619 
2620 int
2621 resume_adapter(struct adapter *sc)
2622 {
2623 	restart_adapter(sc);
2624 	restart_lld(sc);
2625 #ifdef TCP_OFFLOAD
2626 	restart_all_uld(sc);
2627 #endif
2628 	return (0);
2629 }
2630 
2631 static int
2632 t4_resume(device_t dev)
2633 {
2634 	struct adapter *sc = device_get_softc(dev);
2635 	int rc;
2636 
2637 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2638 	rc = resume_adapter(sc);
2639 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2640 
2641 	return (rc);
2642 }
2643 
2644 static int
2645 t4_reset_prepare(device_t dev, device_t child)
2646 {
2647 	struct adapter *sc = device_get_softc(dev);
2648 
2649 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2650 	return (0);
2651 }
2652 
2653 static int
2654 t4_reset_post(device_t dev, device_t child)
2655 {
2656 	struct adapter *sc = device_get_softc(dev);
2657 
2658 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2659 	return (0);
2660 }
2661 
2662 static int
2663 reset_adapter_with_pl_rst(struct adapter *sc)
2664 {
2665 	/* This is a t4_write_reg without the hw_off_limits check. */
2666 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2667 	bus_write_4(sc->regs_res, A_PL_RST,
2668 	    F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2669 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2670 	return (0);
2671 }
2672 
2673 static int
2674 reset_adapter_with_pcie_sbr(struct adapter *sc)
2675 {
2676 	device_t pdev = device_get_parent(sc->dev);
2677 	device_t gpdev = device_get_parent(pdev);
2678 	device_t *children;
2679 	int rc, i, lcap, lsta, nchildren;
2680 	uint32_t v;
2681 
2682 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2683 	if (rc != 0) {
2684 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2685 		    device_get_nameunit(gpdev), rc);
2686 		return (ENOTSUP);
2687 	}
2688 	lcap = v + PCIER_LINK_CAP;
2689 	lsta = v + PCIER_LINK_STA;
2690 
2691 	nchildren = 0;
2692 	device_get_children(pdev, &children, &nchildren);
2693 	for (i = 0; i < nchildren; i++)
2694 		pci_save_state(children[i]);
2695 	v = pci_read_config(gpdev, PCIR_BRIDGECTL_1, 2);
2696 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v | PCIB_BCR_SECBUS_RESET, 2);
2697 	pause("pcie_sbr1", hz / 10);	/* 100ms */
2698 	pci_write_config(gpdev, PCIR_BRIDGECTL_1, v, 2);
2699 	pause("pcie_sbr2", hz);		/* Wait 1s before restore_state. */
2700 	v = pci_read_config(gpdev, lsta, 2);
2701 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2702 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2703 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2704 		rc = ETIMEDOUT;
2705 	else
2706 		rc = 0;
2707 	if (rc != 0)
2708 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2709 		    __func__, v);
2710 	else {
2711 		for (i = 0; i < nchildren; i++)
2712 			pci_restore_state(children[i]);
2713 	}
2714 	free(children, M_TEMP);
2715 
2716 	return (rc);
2717 }
2718 
2719 static int
2720 reset_adapter_with_pcie_link_bounce(struct adapter *sc)
2721 {
2722 	device_t pdev = device_get_parent(sc->dev);
2723 	device_t gpdev = device_get_parent(pdev);
2724 	device_t *children;
2725 	int rc, i, lcap, lctl, lsta, nchildren;
2726 	uint32_t v;
2727 
2728 	rc = pci_find_cap(gpdev, PCIY_EXPRESS, &v);
2729 	if (rc != 0) {
2730 		CH_ERR(sc, "%s: pci_find_cap(%s, pcie) failed: %d\n", __func__,
2731 		    device_get_nameunit(gpdev), rc);
2732 		return (ENOTSUP);
2733 	}
2734 	lcap = v + PCIER_LINK_CAP;
2735 	lctl = v + PCIER_LINK_CTL;
2736 	lsta = v + PCIER_LINK_STA;
2737 
2738 	nchildren = 0;
2739 	device_get_children(pdev, &children, &nchildren);
2740 	for (i = 0; i < nchildren; i++)
2741 		pci_save_state(children[i]);
2742 	v = pci_read_config(gpdev, lctl, 2);
2743 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_LINK_DIS, 2);
2744 	pause("pcie_lnk1", 100 * hz / 1000);	/* 100ms */
2745 	pci_write_config(gpdev, lctl, v | PCIEM_LINK_CTL_RETRAIN_LINK, 2);
2746 	pause("pcie_lnk2", hz);		/* Wait 1s before restore_state. */
2747 	v = pci_read_config(gpdev, lsta, 2);
2748 	if (pci_read_config(gpdev, lcap, 2) & PCIEM_LINK_CAP_DL_ACTIVE)
2749 		rc = v & PCIEM_LINK_STA_DL_ACTIVE ? 0 : ETIMEDOUT;
2750 	else if (v & (PCIEM_LINK_STA_TRAINING_ERROR | PCIEM_LINK_STA_TRAINING))
2751 		rc = ETIMEDOUT;
2752 	else
2753 		rc = 0;
2754 	if (rc != 0)
2755 		CH_ERR(sc, "%s: PCIe link is down after reset, LINK_STA 0x%x\n",
2756 		    __func__, v);
2757 	else {
2758 		for (i = 0; i < nchildren; i++)
2759 			pci_restore_state(children[i]);
2760 	}
2761 	free(children, M_TEMP);
2762 
2763 	return (rc);
2764 }
2765 
2766 static inline int
2767 reset_adapter(struct adapter *sc)
2768 {
2769 	int rc;
2770 	const int reset_method = vm_guest == VM_GUEST_NO ? t4_reset_method : 0;
2771 
2772 	rc = suspend_adapter(sc);
2773 	if (rc != 0)
2774 		return (rc);
2775 
2776 	switch (reset_method) {
2777 	case 1:
2778 		rc = reset_adapter_with_pcie_sbr(sc);
2779 		break;
2780 	case 2:
2781 		rc = reset_adapter_with_pcie_link_bounce(sc);
2782 		break;
2783 	case 0:
2784 	default:
2785 		rc = reset_adapter_with_pl_rst(sc);
2786 		break;
2787 	}
2788 	if (rc == 0)
2789 		rc = resume_adapter(sc);
2790 	return (rc);
2791 }
2792 
2793 static void
2794 reset_adapter_task(void *arg, int pending)
2795 {
2796 	struct adapter *sc = arg;
2797 	const int flags = sc->flags;
2798 	const int eflags = sc->error_flags;
2799 	int rc;
2800 
2801 	if (pending > 1)
2802 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2803 	rc = reset_adapter(sc);
2804 	if (rc != 0) {
2805 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2806 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2807 		       rc, flags, sc->flags, eflags, sc->error_flags);
2808 	}
2809 }
2810 
2811 static int
2812 cxgbe_probe(device_t dev)
2813 {
2814 	struct port_info *pi = device_get_softc(dev);
2815 
2816 	device_set_descf(dev, "port %d", pi->port_id);
2817 
2818 	return (BUS_PROBE_DEFAULT);
2819 }
2820 
2821 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2822     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2823     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2824     IFCAP_HWRXTSTMP | IFCAP_MEXTPG | IFCAP_NV)
2825 #define T4_CAP_ENABLE (T4_CAP)
2826 
2827 static void
2828 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2829 {
2830 	if_t ifp;
2831 	struct sbuf *sb;
2832 	struct sysctl_ctx_list *ctx = &vi->ctx;
2833 	struct sysctl_oid_list *children;
2834 	struct pfil_head_args pa;
2835 	struct adapter *sc = vi->adapter;
2836 
2837 	sysctl_ctx_init(ctx);
2838 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2839 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2840 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2841 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2842 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2843 #ifdef DEV_NETMAP
2844 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2845 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2846 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2847 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2848 #endif
2849 #ifdef TCP_OFFLOAD
2850 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2851 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2852 #endif
2853 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2854 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2855 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2856 #endif
2857 
2858 	vi->xact_addr_filt = -1;
2859 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2860 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2861 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2862 		vi->flags |= TX_USES_VM_WR;
2863 
2864 	/* Allocate an ifnet and set it up */
2865 	ifp = if_alloc_dev(IFT_ETHER, dev);
2866 	vi->ifp = ifp;
2867 	if_setsoftc(ifp, vi);
2868 
2869 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2870 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2871 
2872 	if_setinitfn(ifp, cxgbe_init);
2873 	if_setioctlfn(ifp, cxgbe_ioctl);
2874 	if_setvfstatusfn(ifp, cxgbe_vf_status);
2875 	if_settransmitfn(ifp, cxgbe_transmit);
2876 	if_setqflushfn(ifp, cxgbe_qflush);
2877 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2878 		if_setgetcounterfn(ifp, vi_get_counter);
2879 	else
2880 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2881 #if defined(KERN_TLS) || defined(RATELIMIT)
2882 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2883 #endif
2884 #ifdef RATELIMIT
2885 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2886 #endif
2887 
2888 	if_setcapabilities(ifp, T4_CAP);
2889 	if_setcapenable(ifp, T4_CAP_ENABLE);
2890 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2891 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2892 	if (chip_id(sc) >= CHELSIO_T6) {
2893 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2894 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2895 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2896 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2897 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2898 	}
2899 
2900 #ifdef TCP_OFFLOAD
2901 	if (vi->nofldrxq != 0)
2902 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2903 #endif
2904 #ifdef RATELIMIT
2905 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2906 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2907 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2908 	}
2909 #endif
2910 
2911 	if_sethwtsomax(ifp, IP_MAXPACKET);
2912 	if (vi->flags & TX_USES_VM_WR)
2913 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2914 	else
2915 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2916 #ifdef RATELIMIT
2917 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2918 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2919 #endif
2920 	if_sethwtsomaxsegsize(ifp, 65536);
2921 #ifdef KERN_TLS
2922 	if (is_ktls(sc)) {
2923 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2924 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2925 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2926 	}
2927 #endif
2928 
2929 	ether_ifattach(ifp, vi->hw_addr);
2930 #ifdef DEV_NETMAP
2931 	if (vi->nnmrxq != 0)
2932 		cxgbe_nm_attach(vi);
2933 #endif
2934 	sb = sbuf_new_auto();
2935 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2936 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2937 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2938 	case IFCAP_TOE:
2939 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2940 		break;
2941 	case IFCAP_TOE | IFCAP_TXRTLMT:
2942 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2943 		break;
2944 	case IFCAP_TXRTLMT:
2945 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2946 		break;
2947 	}
2948 #endif
2949 #ifdef TCP_OFFLOAD
2950 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2951 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2952 #endif
2953 #ifdef DEV_NETMAP
2954 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2955 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2956 		    vi->nnmtxq, vi->nnmrxq);
2957 #endif
2958 	sbuf_finish(sb);
2959 	device_printf(dev, "%s\n", sbuf_data(sb));
2960 	sbuf_delete(sb);
2961 
2962 	vi_sysctls(vi);
2963 
2964 	pa.pa_version = PFIL_VERSION;
2965 	pa.pa_flags = PFIL_IN;
2966 	pa.pa_type = PFIL_TYPE_ETHERNET;
2967 	pa.pa_headname = if_name(ifp);
2968 	vi->pfil = pfil_head_register(&pa);
2969 }
2970 
2971 static int
2972 cxgbe_attach(device_t dev)
2973 {
2974 	struct port_info *pi = device_get_softc(dev);
2975 	struct adapter *sc = pi->adapter;
2976 	struct vi_info *vi;
2977 	int i;
2978 
2979 	sysctl_ctx_init(&pi->ctx);
2980 
2981 	cxgbe_vi_attach(dev, &pi->vi[0]);
2982 
2983 	for_each_vi(pi, i, vi) {
2984 		if (i == 0)
2985 			continue;
2986 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2987 		if (vi->dev == NULL) {
2988 			device_printf(dev, "failed to add VI %d\n", i);
2989 			continue;
2990 		}
2991 		device_set_softc(vi->dev, vi);
2992 	}
2993 
2994 	cxgbe_sysctls(pi);
2995 
2996 	bus_attach_children(dev);
2997 
2998 	return (0);
2999 }
3000 
3001 static void
3002 cxgbe_vi_detach(struct vi_info *vi)
3003 {
3004 	if_t ifp = vi->ifp;
3005 
3006 	if (vi->pfil != NULL) {
3007 		pfil_head_unregister(vi->pfil);
3008 		vi->pfil = NULL;
3009 	}
3010 
3011 	ether_ifdetach(ifp);
3012 
3013 	/* Let detach proceed even if these fail. */
3014 #ifdef DEV_NETMAP
3015 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
3016 		cxgbe_nm_detach(vi);
3017 #endif
3018 	cxgbe_uninit_synchronized(vi);
3019 	callout_drain(&vi->tick);
3020 	mtx_destroy(&vi->tick_mtx);
3021 	sysctl_ctx_free(&vi->ctx);
3022 	vi_full_uninit(vi);
3023 
3024 	if_free(vi->ifp);
3025 	vi->ifp = NULL;
3026 }
3027 
3028 static int
3029 cxgbe_detach(device_t dev)
3030 {
3031 	struct port_info *pi = device_get_softc(dev);
3032 	struct adapter *sc = pi->adapter;
3033 	int rc;
3034 
3035 	/* Detach the extra VIs first. */
3036 	rc = bus_generic_detach(dev);
3037 	if (rc)
3038 		return (rc);
3039 
3040 	sysctl_ctx_free(&pi->ctx);
3041 	begin_vi_detach(sc, &pi->vi[0]);
3042 	if (pi->flags & HAS_TRACEQ) {
3043 		sc->traceq = -1;	/* cloner should not create ifnet */
3044 		t4_tracer_port_detach(sc);
3045 	}
3046 	cxgbe_vi_detach(&pi->vi[0]);
3047 	ifmedia_removeall(&pi->media);
3048 	end_vi_detach(sc, &pi->vi[0]);
3049 
3050 	return (0);
3051 }
3052 
3053 static void
3054 cxgbe_init(void *arg)
3055 {
3056 	struct vi_info *vi = arg;
3057 	struct adapter *sc = vi->adapter;
3058 
3059 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
3060 		return;
3061 	cxgbe_init_synchronized(vi);
3062 	end_synchronized_op(sc, 0);
3063 }
3064 
3065 static int
3066 cxgbe_vf_status(if_t ifp, struct if_vf_status **statusp)
3067 {
3068 	struct port_info *pi;
3069 	struct adapter *sc;
3070 	struct t4_vf_info *snapshot;
3071 	struct if_vf_info *vf;
3072 	struct if_vf_status *status;
3073 	struct vi_info *vi;
3074 	uint16_t num_vfs;
3075 	int error, i;
3076 
3077 	vi = if_getsoftc(ifp);
3078 	pi = vi->pi;
3079 	sc = pi->adapter;
3080 	if (!IS_MAIN_VI(vi))
3081 		return (EOPNOTSUPP);
3082 	error = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK,
3083 	    "t4vfstat");
3084 	if (error != 0)
3085 		return (error);
3086 	if (!pi->iov_status_supported) {
3087 		end_synchronized_op(sc, 0);
3088 		return (EOPNOTSUPP);
3089 	}
3090 	num_vfs = pi->iov_num_vfs;
3091 	snapshot = NULL;
3092 	if (num_vfs != 0) {
3093 		snapshot = mallocarray(num_vfs, sizeof(*snapshot), M_CXGBE,
3094 		    M_WAITOK);
3095 		memcpy(snapshot, pi->iov_vfs, num_vfs * sizeof(*snapshot));
3096 	}
3097 	end_synchronized_op(sc, 0);
3098 
3099 	status = if_vf_status_alloc(num_vfs);
3100 	for (i = 0; i < num_vfs; i++) {
3101 		vf = &status->vfs[i];
3102 		vf->fields = IFVF_F_CONFIGURED;
3103 		vf->index = i;
3104 		vf->configured = snapshot[i].configured;
3105 		if (!vf->configured)
3106 			continue;
3107 		vf->fields |= IFVF_F_VLAN_MODE;
3108 		if (!ETHER_IS_ZERO(snapshot[i].mac)) {
3109 			memcpy(vf->mac, snapshot[i].mac, sizeof(vf->mac));
3110 			vf->fields |= IFVF_F_MAC;
3111 		}
3112 		if (snapshot[i].access_vlan) {
3113 			vf->vlan_mode = IFVF_VLAN_ACCESS;
3114 			vf->vlan = snapshot[i].vlan;
3115 			vf->vlan_proto = ETHERTYPE_VLAN;
3116 			vf->vlan_count = 1;
3117 			vf->fields |= IFVF_F_VLAN | IFVF_F_VLAN_PROTO |
3118 			    IFVF_F_VLAN_COUNT;
3119 		} else
3120 			vf->vlan_mode = IFVF_VLAN_TRUNK;
3121 	}
3122 	free(snapshot, M_CXGBE);
3123 	*statusp = status;
3124 	return (0);
3125 }
3126 
3127 static int
3128 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
3129 {
3130 	int rc = 0, mtu, flags;
3131 	struct vi_info *vi = if_getsoftc(ifp);
3132 	struct port_info *pi = vi->pi;
3133 	struct adapter *sc = pi->adapter;
3134 	struct ifreq *ifr = (struct ifreq *)data;
3135 	uint32_t mask, mask2;
3136 
3137 	switch (cmd) {
3138 	case SIOCSIFMTU:
3139 		mtu = ifr->ifr_mtu;
3140 		if (mtu < ETHERMIN || mtu > MAX_MTU)
3141 			return (EINVAL);
3142 
3143 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
3144 		if (rc)
3145 			return (rc);
3146 		if_setmtu(ifp, mtu);
3147 		if (vi->flags & VI_INIT_DONE) {
3148 			t4_update_fl_bufsize(ifp);
3149 			if (hw_all_ok(sc) &&
3150 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3151 				rc = update_mac_settings(ifp, XGMAC_MTU);
3152 		}
3153 		end_synchronized_op(sc, 0);
3154 		break;
3155 
3156 	case SIOCSIFFLAGS:
3157 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
3158 		if (rc)
3159 			return (rc);
3160 
3161 		if (!hw_all_ok(sc)) {
3162 			rc = ENXIO;
3163 			goto fail;
3164 		}
3165 
3166 		if (if_getflags(ifp) & IFF_UP) {
3167 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3168 				flags = vi->if_flags;
3169 				if ((if_getflags(ifp) ^ flags) &
3170 				    (IFF_PROMISC | IFF_ALLMULTI)) {
3171 					rc = update_mac_settings(ifp,
3172 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
3173 				}
3174 			} else {
3175 				rc = cxgbe_init_synchronized(vi);
3176 			}
3177 			vi->if_flags = if_getflags(ifp);
3178 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
3179 			rc = cxgbe_uninit_synchronized(vi);
3180 		}
3181 		end_synchronized_op(sc, 0);
3182 		break;
3183 
3184 	case SIOCADDMULTI:
3185 	case SIOCDELMULTI:
3186 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
3187 		if (rc)
3188 			return (rc);
3189 		if (hw_all_ok(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3190 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
3191 		end_synchronized_op(sc, 0);
3192 		break;
3193 
3194 	case SIOCGIFCAPNV:
3195 		break;
3196 	case SIOCSIFCAPNV:
3197 	case SIOCSIFCAP:
3198 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
3199 		if (rc)
3200 			return (rc);
3201 
3202 		if (cmd == SIOCSIFCAPNV) {
3203 			const struct siocsifcapnv_driver_data *ifr_nv =
3204 			    (struct siocsifcapnv_driver_data *)data;
3205 
3206 			mask = ifr_nv->reqcap ^ if_getcapenable(ifp);
3207 			mask2 = ifr_nv->reqcap2 ^ if_getcapenable2(ifp);
3208 		} else {
3209 			mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
3210 			mask2 = 0;
3211 		}
3212 		if (mask & IFCAP_TXCSUM) {
3213 			if_togglecapenable(ifp, IFCAP_TXCSUM);
3214 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
3215 
3216 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
3217 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3218 				mask &= ~IFCAP_TSO4;
3219 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
3220 				if_printf(ifp,
3221 				    "tso4 disabled due to -txcsum.\n");
3222 			}
3223 		}
3224 		if (mask & IFCAP_TXCSUM_IPV6) {
3225 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
3226 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
3227 
3228 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
3229 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3230 				mask &= ~IFCAP_TSO6;
3231 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
3232 				if_printf(ifp,
3233 				    "tso6 disabled due to -txcsum6.\n");
3234 			}
3235 		}
3236 		if (mask & IFCAP_RXCSUM)
3237 			if_togglecapenable(ifp, IFCAP_RXCSUM);
3238 		if (mask & IFCAP_RXCSUM_IPV6)
3239 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
3240 
3241 		/*
3242 		 * Note that we leave CSUM_TSO alone (it is always set).  The
3243 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
3244 		 * sending a TSO request our way, so it's sufficient to toggle
3245 		 * IFCAP_TSOx only.
3246 		 */
3247 		if (mask & IFCAP_TSO4) {
3248 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
3249 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
3250 				if_printf(ifp, "enable txcsum first.\n");
3251 				rc = EAGAIN;
3252 				goto fail;
3253 			}
3254 			if_togglecapenable(ifp, IFCAP_TSO4);
3255 		}
3256 		if (mask & IFCAP_TSO6) {
3257 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
3258 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
3259 				if_printf(ifp, "enable txcsum6 first.\n");
3260 				rc = EAGAIN;
3261 				goto fail;
3262 			}
3263 			if_togglecapenable(ifp, IFCAP_TSO6);
3264 		}
3265 		if (mask & IFCAP_LRO) {
3266 #if defined(INET) || defined(INET6)
3267 			int i;
3268 			struct sge_rxq *rxq;
3269 
3270 			if_togglecapenable(ifp, IFCAP_LRO);
3271 			for_each_rxq(vi, i, rxq) {
3272 				if (if_getcapenable(ifp) & IFCAP_LRO)
3273 					rxq->iq.flags |= IQ_LRO_ENABLED;
3274 				else
3275 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
3276 			}
3277 #endif
3278 		}
3279 #ifdef TCP_OFFLOAD
3280 		if (mask & IFCAP_TOE) {
3281 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
3282 
3283 			rc = toe_capability(vi, enable);
3284 			if (rc != 0)
3285 				goto fail;
3286 
3287 			if_togglecapenable(ifp, mask);
3288 		}
3289 #endif
3290 		if (mask & IFCAP_VLAN_HWTAGGING) {
3291 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3292 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3293 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3294 		}
3295 		if (mask & IFCAP_VLAN_MTU) {
3296 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3297 
3298 			/* Need to find out how to disable auto-mtu-inflation */
3299 		}
3300 		if (mask & IFCAP_VLAN_HWTSO)
3301 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3302 		if (mask & IFCAP_VLAN_HWCSUM)
3303 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3304 #ifdef RATELIMIT
3305 		if (mask & IFCAP_TXRTLMT)
3306 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3307 #endif
3308 		if (mask & IFCAP_HWRXTSTMP) {
3309 			int i;
3310 			struct sge_rxq *rxq;
3311 
3312 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3313 			for_each_rxq(vi, i, rxq) {
3314 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3315 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3316 				else
3317 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3318 			}
3319 		}
3320 		if (mask & IFCAP_MEXTPG)
3321 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3322 
3323 #ifdef KERN_TLS
3324 		if (mask & IFCAP_TXTLS) {
3325 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3326 
3327 			rc = ktls_capability(sc, enable);
3328 			if (rc != 0)
3329 				goto fail;
3330 
3331 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3332 		}
3333 #endif
3334 		if (mask & IFCAP_VXLAN_HWCSUM) {
3335 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3336 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3337 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3338 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3339 		}
3340 		if (mask & IFCAP_VXLAN_HWTSO) {
3341 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3342 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3343 			    CSUM_INNER_IP_TSO);
3344 		}
3345 
3346 		MPASS(mask2 == 0);
3347 		(void)mask2;
3348 
3349 #ifdef VLAN_CAPABILITIES
3350 		VLAN_CAPABILITIES(ifp);
3351 #endif
3352 fail:
3353 		end_synchronized_op(sc, 0);
3354 		break;
3355 
3356 	case SIOCSIFMEDIA:
3357 	case SIOCGIFMEDIA:
3358 	case SIOCGIFXMEDIA:
3359 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3360 		break;
3361 
3362 	case SIOCGI2C: {
3363 		struct ifi2creq i2c;
3364 
3365 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3366 		if (rc != 0)
3367 			break;
3368 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3369 			rc = EPERM;
3370 			break;
3371 		}
3372 		if (i2c.len > sizeof(i2c.data)) {
3373 			rc = EINVAL;
3374 			break;
3375 		}
3376 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3377 		if (rc)
3378 			return (rc);
3379 		if (!hw_all_ok(sc))
3380 			rc = ENXIO;
3381 		else
3382 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3383 			    i2c.offset, i2c.len, &i2c.data[0]);
3384 		end_synchronized_op(sc, 0);
3385 		if (rc == 0)
3386 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3387 		break;
3388 	}
3389 
3390 	default:
3391 		rc = ether_ioctl(ifp, cmd, data);
3392 	}
3393 
3394 	return (rc);
3395 }
3396 
3397 static int
3398 cxgbe_transmit(if_t ifp, struct mbuf *m)
3399 {
3400 	struct vi_info *vi = if_getsoftc(ifp);
3401 	struct port_info *pi = vi->pi;
3402 	struct adapter *sc;
3403 	struct sge_txq *txq;
3404 	void *items[1];
3405 	int rc;
3406 
3407 	M_ASSERTPKTHDR(m);
3408 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3409 #if defined(KERN_TLS) || defined(RATELIMIT)
3410 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3411 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3412 #endif
3413 
3414 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3415 		m_freem(m);
3416 		return (ENETDOWN);
3417 	}
3418 
3419 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3420 	if (__predict_false(rc != 0)) {
3421 		if (__predict_true(rc == EINPROGRESS)) {
3422 			/* queued by parse_pkt */
3423 			MPASS(m != NULL);
3424 			return (0);
3425 		}
3426 
3427 		MPASS(m == NULL);			/* was freed already */
3428 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3429 		return (rc);
3430 	}
3431 
3432 	/* Select a txq. */
3433 	sc = vi->adapter;
3434 	txq = &sc->sge.txq[vi->first_txq];
3435 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3436 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3437 		    vi->rsrv_noflowq);
3438 
3439 	items[0] = m;
3440 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3441 	if (__predict_false(rc != 0))
3442 		m_freem(m);
3443 
3444 	return (rc);
3445 }
3446 
3447 static void
3448 cxgbe_qflush(if_t ifp)
3449 {
3450 	struct vi_info *vi = if_getsoftc(ifp);
3451 	struct sge_txq *txq;
3452 	int i;
3453 
3454 	/* queues do not exist if !VI_INIT_DONE. */
3455 	if (vi->flags & VI_INIT_DONE) {
3456 		for_each_txq(vi, i, txq) {
3457 			TXQ_LOCK(txq);
3458 			txq->eq.flags |= EQ_QFLUSH;
3459 			TXQ_UNLOCK(txq);
3460 			while (!mp_ring_is_idle(txq->r)) {
3461 				mp_ring_check_drainage(txq->r, 4096);
3462 				pause("qflush", 1);
3463 			}
3464 			TXQ_LOCK(txq);
3465 			txq->eq.flags &= ~EQ_QFLUSH;
3466 			TXQ_UNLOCK(txq);
3467 		}
3468 	}
3469 	if_qflush(ifp);
3470 }
3471 
3472 static uint64_t
3473 vi_get_counter(if_t ifp, ift_counter c)
3474 {
3475 	struct vi_info *vi = if_getsoftc(ifp);
3476 	struct fw_vi_stats_vf *s = &vi->stats;
3477 
3478 	mtx_lock(&vi->tick_mtx);
3479 	vi_refresh_stats(vi);
3480 	mtx_unlock(&vi->tick_mtx);
3481 
3482 	switch (c) {
3483 	case IFCOUNTER_IPACKETS:
3484 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3485 		    s->rx_ucast_frames);
3486 	case IFCOUNTER_IERRORS:
3487 		return (s->rx_err_frames);
3488 	case IFCOUNTER_OPACKETS:
3489 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3490 		    s->tx_ucast_frames + s->tx_offload_frames);
3491 	case IFCOUNTER_OERRORS:
3492 		return (s->tx_drop_frames);
3493 	case IFCOUNTER_IBYTES:
3494 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3495 		    s->rx_ucast_bytes);
3496 	case IFCOUNTER_OBYTES:
3497 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3498 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3499 	case IFCOUNTER_IMCASTS:
3500 		return (s->rx_mcast_frames);
3501 	case IFCOUNTER_OMCASTS:
3502 		return (s->tx_mcast_frames);
3503 	case IFCOUNTER_OQDROPS: {
3504 		uint64_t drops;
3505 
3506 		drops = 0;
3507 		if (vi->flags & VI_INIT_DONE) {
3508 			int i;
3509 			struct sge_txq *txq;
3510 
3511 			for_each_txq(vi, i, txq)
3512 				drops += counter_u64_fetch(txq->r->dropped);
3513 		}
3514 
3515 		return (drops);
3516 
3517 	}
3518 
3519 	default:
3520 		return (if_get_counter_default(ifp, c));
3521 	}
3522 }
3523 
3524 static uint64_t
3525 cxgbe_get_counter(if_t ifp, ift_counter c)
3526 {
3527 	struct vi_info *vi = if_getsoftc(ifp);
3528 	struct port_info *pi = vi->pi;
3529 	struct port_stats *s = &pi->stats;
3530 
3531 	mtx_lock(&vi->tick_mtx);
3532 	cxgbe_refresh_stats(vi);
3533 	mtx_unlock(&vi->tick_mtx);
3534 
3535 	switch (c) {
3536 	case IFCOUNTER_IPACKETS:
3537 		return (s->rx_frames);
3538 
3539 	case IFCOUNTER_IERRORS:
3540 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3541 		    s->rx_fcs_err + s->rx_len_err);
3542 
3543 	case IFCOUNTER_OPACKETS:
3544 		return (s->tx_frames);
3545 
3546 	case IFCOUNTER_OERRORS:
3547 		return (s->tx_error_frames);
3548 
3549 	case IFCOUNTER_IBYTES:
3550 		return (s->rx_octets);
3551 
3552 	case IFCOUNTER_OBYTES:
3553 		return (s->tx_octets);
3554 
3555 	case IFCOUNTER_IMCASTS:
3556 		return (s->rx_mcast_frames);
3557 
3558 	case IFCOUNTER_OMCASTS:
3559 		return (s->tx_mcast_frames);
3560 
3561 	case IFCOUNTER_IQDROPS:
3562 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3563 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3564 		    s->rx_trunc3 + pi->tnl_cong_drops);
3565 
3566 	case IFCOUNTER_OQDROPS: {
3567 		uint64_t drops;
3568 
3569 		drops = s->tx_drop;
3570 		if (vi->flags & VI_INIT_DONE) {
3571 			int i;
3572 			struct sge_txq *txq;
3573 
3574 			for_each_txq(vi, i, txq)
3575 				drops += counter_u64_fetch(txq->r->dropped);
3576 		}
3577 
3578 		return (drops);
3579 
3580 	}
3581 
3582 	default:
3583 		return (if_get_counter_default(ifp, c));
3584 	}
3585 }
3586 
3587 #if defined(KERN_TLS) || defined(RATELIMIT)
3588 static int
3589 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3590     struct m_snd_tag **pt)
3591 {
3592 	int error;
3593 
3594 	switch (params->hdr.type) {
3595 #ifdef RATELIMIT
3596 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3597 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3598 		break;
3599 #endif
3600 #ifdef KERN_TLS
3601 	case IF_SND_TAG_TYPE_TLS:
3602 	{
3603 		struct vi_info *vi = if_getsoftc(ifp);
3604 
3605 		if (is_t6(vi->pi->adapter))
3606 			error = t6_tls_tag_alloc(ifp, params, pt);
3607 		else
3608 			error = t7_tls_tag_alloc(ifp, params, pt);
3609 		break;
3610 	}
3611 #endif
3612 	default:
3613 		error = EOPNOTSUPP;
3614 	}
3615 	return (error);
3616 }
3617 #endif
3618 
3619 /*
3620  * The kernel picks a media from the list we had provided but we still validate
3621  * the requeste.
3622  */
3623 int
3624 cxgbe_media_change(if_t ifp)
3625 {
3626 	struct vi_info *vi = if_getsoftc(ifp);
3627 	struct port_info *pi = vi->pi;
3628 	struct ifmedia *ifm = &pi->media;
3629 	struct link_config *lc = &pi->link_cfg;
3630 	struct adapter *sc = pi->adapter;
3631 	int rc;
3632 
3633 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3634 	if (rc != 0)
3635 		return (rc);
3636 	PORT_LOCK(pi);
3637 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3638 		/* ifconfig .. media autoselect */
3639 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3640 			rc = ENOTSUP; /* AN not supported by transceiver */
3641 			goto done;
3642 		}
3643 		lc->requested_aneg = AUTONEG_ENABLE;
3644 		lc->requested_speed = 0;
3645 		lc->requested_fc |= PAUSE_AUTONEG;
3646 	} else {
3647 		lc->requested_aneg = AUTONEG_DISABLE;
3648 		lc->requested_speed =
3649 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3650 		lc->requested_fc = 0;
3651 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3652 			lc->requested_fc |= PAUSE_RX;
3653 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3654 			lc->requested_fc |= PAUSE_TX;
3655 	}
3656 	if (pi->up_vis > 0 && hw_all_ok(sc)) {
3657 		fixup_link_config(pi);
3658 		rc = apply_link_config(pi);
3659 	}
3660 done:
3661 	PORT_UNLOCK(pi);
3662 	end_synchronized_op(sc, 0);
3663 	return (rc);
3664 }
3665 
3666 /*
3667  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3668  * given speed.
3669  */
3670 static int
3671 port_mword(struct port_info *pi, uint32_t speed)
3672 {
3673 
3674 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3675 	MPASS(powerof2(speed));
3676 
3677 	switch(pi->port_type) {
3678 	case FW_PORT_TYPE_BT_SGMII:
3679 	case FW_PORT_TYPE_BT_XFI:
3680 	case FW_PORT_TYPE_BT_XAUI:
3681 		/* BaseT */
3682 		switch (speed) {
3683 		case FW_PORT_CAP32_SPEED_100M:
3684 			return (IFM_100_T);
3685 		case FW_PORT_CAP32_SPEED_1G:
3686 			return (IFM_1000_T);
3687 		case FW_PORT_CAP32_SPEED_10G:
3688 			return (IFM_10G_T);
3689 		}
3690 		break;
3691 	case FW_PORT_TYPE_KX4:
3692 		if (speed == FW_PORT_CAP32_SPEED_10G)
3693 			return (IFM_10G_KX4);
3694 		break;
3695 	case FW_PORT_TYPE_CX4:
3696 		if (speed == FW_PORT_CAP32_SPEED_10G)
3697 			return (IFM_10G_CX4);
3698 		break;
3699 	case FW_PORT_TYPE_KX:
3700 		if (speed == FW_PORT_CAP32_SPEED_1G)
3701 			return (IFM_1000_KX);
3702 		break;
3703 	case FW_PORT_TYPE_KR:
3704 	case FW_PORT_TYPE_BP_AP:
3705 	case FW_PORT_TYPE_BP4_AP:
3706 	case FW_PORT_TYPE_BP40_BA:
3707 	case FW_PORT_TYPE_KR4_100G:
3708 	case FW_PORT_TYPE_KR_SFP28:
3709 	case FW_PORT_TYPE_KR_XLAUI:
3710 		switch (speed) {
3711 		case FW_PORT_CAP32_SPEED_1G:
3712 			return (IFM_1000_KX);
3713 		case FW_PORT_CAP32_SPEED_10G:
3714 			return (IFM_10G_KR);
3715 		case FW_PORT_CAP32_SPEED_25G:
3716 			return (IFM_25G_KR);
3717 		case FW_PORT_CAP32_SPEED_40G:
3718 			return (IFM_40G_KR4);
3719 		case FW_PORT_CAP32_SPEED_50G:
3720 			return (IFM_50G_KR2);
3721 		case FW_PORT_CAP32_SPEED_100G:
3722 			return (IFM_100G_KR4);
3723 		}
3724 		break;
3725 	case FW_PORT_TYPE_FIBER_XFI:
3726 	case FW_PORT_TYPE_FIBER_XAUI:
3727 	case FW_PORT_TYPE_SFP:
3728 	case FW_PORT_TYPE_QSFP_10G:
3729 	case FW_PORT_TYPE_QSA:
3730 	case FW_PORT_TYPE_QSFP:
3731 	case FW_PORT_TYPE_CR4_QSFP:
3732 	case FW_PORT_TYPE_CR_QSFP:
3733 	case FW_PORT_TYPE_CR2_QSFP:
3734 	case FW_PORT_TYPE_SFP28:
3735 	case FW_PORT_TYPE_SFP56:
3736 	case FW_PORT_TYPE_QSFP56:
3737 	case FW_PORT_TYPE_QSFPDD:
3738 		/* Pluggable transceiver */
3739 		switch (pi->mod_type) {
3740 		case FW_PORT_MOD_TYPE_LR:
3741 		case FW_PORT_MOD_TYPE_LR_SIMPLEX:
3742 			switch (speed) {
3743 			case FW_PORT_CAP32_SPEED_1G:
3744 				return (IFM_1000_LX);
3745 			case FW_PORT_CAP32_SPEED_10G:
3746 				return (IFM_10G_LR);
3747 			case FW_PORT_CAP32_SPEED_25G:
3748 				return (IFM_25G_LR);
3749 			case FW_PORT_CAP32_SPEED_40G:
3750 				return (IFM_40G_LR4);
3751 			case FW_PORT_CAP32_SPEED_50G:
3752 				return (IFM_50G_LR2);
3753 			case FW_PORT_CAP32_SPEED_100G:
3754 				return (IFM_100G_LR4);
3755 			case FW_PORT_CAP32_SPEED_200G:
3756 				return (IFM_200G_LR4);
3757 			case FW_PORT_CAP32_SPEED_400G:
3758 				return (IFM_400G_LR8);
3759 			}
3760 			break;
3761 		case FW_PORT_MOD_TYPE_SR:
3762 			switch (speed) {
3763 			case FW_PORT_CAP32_SPEED_1G:
3764 				return (IFM_1000_SX);
3765 			case FW_PORT_CAP32_SPEED_10G:
3766 				return (IFM_10G_SR);
3767 			case FW_PORT_CAP32_SPEED_25G:
3768 				return (IFM_25G_SR);
3769 			case FW_PORT_CAP32_SPEED_40G:
3770 				return (IFM_40G_SR4);
3771 			case FW_PORT_CAP32_SPEED_50G:
3772 				return (IFM_50G_SR2);
3773 			case FW_PORT_CAP32_SPEED_100G:
3774 				return (IFM_100G_SR4);
3775 			case FW_PORT_CAP32_SPEED_200G:
3776 				return (IFM_200G_SR4);
3777 			case FW_PORT_CAP32_SPEED_400G:
3778 				return (IFM_400G_SR8);
3779 			}
3780 			break;
3781 		case FW_PORT_MOD_TYPE_ER:
3782 			if (speed == FW_PORT_CAP32_SPEED_10G)
3783 				return (IFM_10G_ER);
3784 			break;
3785 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3786 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3787 			switch (speed) {
3788 			case FW_PORT_CAP32_SPEED_1G:
3789 				return (IFM_1000_CX);
3790 			case FW_PORT_CAP32_SPEED_10G:
3791 				return (IFM_10G_TWINAX);
3792 			case FW_PORT_CAP32_SPEED_25G:
3793 				return (IFM_25G_CR);
3794 			case FW_PORT_CAP32_SPEED_40G:
3795 				return (IFM_40G_CR4);
3796 			case FW_PORT_CAP32_SPEED_50G:
3797 				return (IFM_50G_CR2);
3798 			case FW_PORT_CAP32_SPEED_100G:
3799 				return (IFM_100G_CR4);
3800 			case FW_PORT_CAP32_SPEED_200G:
3801 				return (IFM_200G_CR4_PAM4);
3802 			case FW_PORT_CAP32_SPEED_400G:
3803 				return (IFM_400G_CR8);
3804 			}
3805 			break;
3806 		case FW_PORT_MOD_TYPE_LRM:
3807 			if (speed == FW_PORT_CAP32_SPEED_10G)
3808 				return (IFM_10G_LRM);
3809 			break;
3810 		case FW_PORT_MOD_TYPE_DR:
3811 			if (speed == FW_PORT_CAP32_SPEED_100G)
3812 				return (IFM_100G_DR);
3813 			if (speed == FW_PORT_CAP32_SPEED_200G)
3814 				return (IFM_200G_DR4);
3815 			if (speed == FW_PORT_CAP32_SPEED_400G)
3816 				return (IFM_400G_DR4);
3817 			break;
3818 		case FW_PORT_MOD_TYPE_NA:
3819 			MPASS(0);	/* Not pluggable? */
3820 			/* fall through */
3821 		case FW_PORT_MOD_TYPE_ERROR:
3822 		case FW_PORT_MOD_TYPE_UNKNOWN:
3823 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3824 			break;
3825 		case FW_PORT_MOD_TYPE_NONE:
3826 			return (IFM_NONE);
3827 		}
3828 		break;
3829 	case FW_PORT_TYPE_KR4_200G: {
3830 		/*
3831 		 * Pre-T7 firmware used M_FW_PORT_CMD_PTYPE for PORT_TYPE_NONE
3832 		 * and driver needs to deal with both.
3833 		 */
3834 		_Static_assert(M_FW_PORT_CMD_PTYPE == FW_PORT_TYPE_KR4_200G,
3835 		    "driver/firmware mismatch");
3836 		if (chip_id(pi->adapter) < CHELSIO_T7)
3837 			return (IFM_NONE);
3838 		return (IFM_200G_KR4_PAM4);
3839 	}
3840 	case FW_PORT_TYPE_NONE:
3841 		return (IFM_NONE);
3842 	}
3843 
3844 	return (IFM_UNKNOWN);
3845 }
3846 
3847 void
3848 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3849 {
3850 	struct vi_info *vi = if_getsoftc(ifp);
3851 	struct port_info *pi = vi->pi;
3852 	struct adapter *sc = pi->adapter;
3853 	struct link_config *lc = &pi->link_cfg;
3854 
3855 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3856 		return;
3857 	PORT_LOCK(pi);
3858 
3859 	if (pi->up_vis == 0 && hw_all_ok(sc)) {
3860 		/*
3861 		 * If all the interfaces are administratively down the firmware
3862 		 * does not report transceiver changes.  Refresh port info here
3863 		 * so that ifconfig displays accurate ifmedia at all times.
3864 		 * This is the only reason we have a synchronized op in this
3865 		 * function.  Just PORT_LOCK would have been enough otherwise.
3866 		 */
3867 		t4_update_port_info(pi);
3868 		build_medialist(pi);
3869 	}
3870 
3871 	/* ifm_status */
3872 	ifmr->ifm_status = IFM_AVALID;
3873 	if (lc->link_ok == false)
3874 		goto done;
3875 	ifmr->ifm_status |= IFM_ACTIVE;
3876 
3877 	/* ifm_active */
3878 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3879 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3880 	if (lc->fc & PAUSE_RX)
3881 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3882 	if (lc->fc & PAUSE_TX)
3883 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3884 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3885 done:
3886 	PORT_UNLOCK(pi);
3887 	end_synchronized_op(sc, 0);
3888 }
3889 
3890 static int
3891 vcxgbe_probe(device_t dev)
3892 {
3893 	struct vi_info *vi = device_get_softc(dev);
3894 
3895 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3896 	    vi - vi->pi->vi);
3897 
3898 	return (BUS_PROBE_DEFAULT);
3899 }
3900 
3901 static int
3902 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3903 {
3904 	int func, index, rc;
3905 	uint32_t param, val;
3906 
3907 	ASSERT_SYNCHRONIZED_OP(sc);
3908 
3909 	index = vi - pi->vi;
3910 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3911 	KASSERT(index < nitems(vi_mac_funcs),
3912 	    ("%s: VI %s doesn't have a MAC func", __func__,
3913 	    device_get_nameunit(vi->dev)));
3914 	func = vi_mac_funcs[index];
3915 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->hw_port, sc->pf, 0, 1,
3916 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3917 	if (rc < 0) {
3918 		CH_ERR(vi, "failed to allocate virtual interface %d"
3919 		    "for port %d: %d\n", index, pi->port_id, -rc);
3920 		return (-rc);
3921 	}
3922 	vi->viid = rc;
3923 
3924 	if (vi->rss_size == 1) {
3925 		/*
3926 		 * This VI didn't get a slice of the RSS table.  Reduce the
3927 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3928 		 * configuration file (nvi, rssnvi for this PF) if this is a
3929 		 * problem.
3930 		 */
3931 		device_printf(vi->dev, "RSS table not available.\n");
3932 		vi->rss_base = 0xffff;
3933 
3934 		return (0);
3935 	}
3936 
3937 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3938 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3939 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3940 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3941 	if (rc)
3942 		vi->rss_base = 0xffff;
3943 	else {
3944 		MPASS((val >> 16) == vi->rss_size);
3945 		vi->rss_base = val & 0xffff;
3946 	}
3947 
3948 	return (0);
3949 }
3950 
3951 static int
3952 vcxgbe_attach(device_t dev)
3953 {
3954 	struct vi_info *vi;
3955 	struct port_info *pi;
3956 	struct adapter *sc;
3957 	int rc;
3958 
3959 	vi = device_get_softc(dev);
3960 	pi = vi->pi;
3961 	sc = pi->adapter;
3962 
3963 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3964 	if (rc)
3965 		return (rc);
3966 	rc = alloc_extra_vi(sc, pi, vi);
3967 	end_synchronized_op(sc, 0);
3968 	if (rc)
3969 		return (rc);
3970 
3971 	cxgbe_vi_attach(dev, vi);
3972 
3973 	return (0);
3974 }
3975 
3976 static int
3977 vcxgbe_detach(device_t dev)
3978 {
3979 	struct vi_info *vi;
3980 	struct adapter *sc;
3981 
3982 	vi = device_get_softc(dev);
3983 	sc = vi->adapter;
3984 
3985 	begin_vi_detach(sc, vi);
3986 	cxgbe_vi_detach(vi);
3987 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3988 	end_vi_detach(sc, vi);
3989 
3990 	return (0);
3991 }
3992 
3993 static struct callout fatal_callout;
3994 static struct taskqueue *reset_tq;
3995 
3996 static void
3997 delayed_panic(void *arg)
3998 {
3999 	struct adapter *sc = arg;
4000 
4001 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
4002 }
4003 
4004 static void
4005 fatal_error_task(void *arg, int pending)
4006 {
4007 	struct adapter *sc = arg;
4008 	int rc;
4009 
4010 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
4011 		dump_cim_regs(sc);
4012 		dump_cimla(sc);
4013 		dump_devlog(sc);
4014 	}
4015 
4016 	if (t4_reset_on_fatal_err) {
4017 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
4018 		rc = reset_adapter(sc);
4019 		if (rc == 0 && t4_panic_on_fatal_err) {
4020 			CH_ALERT(sc, "reset was successful, "
4021 			    "system will NOT panic.\n");
4022 			return;
4023 		}
4024 	}
4025 
4026 	if (t4_panic_on_fatal_err) {
4027 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
4028 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
4029 	}
4030 }
4031 
4032 void
4033 t4_fatal_err(struct adapter *sc, bool fw_error)
4034 {
4035 	stop_adapter(sc);
4036 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
4037 		return;
4038 	if (fw_error) {
4039 		/*
4040 		 * We are here because of a firmware error/timeout and not
4041 		 * because of a hardware interrupt.  It is possible (although
4042 		 * not very likely) that an error interrupt was also raised but
4043 		 * this thread ran first and inhibited t4_intr_err.  We walk the
4044 		 * main INT_CAUSE registers here to make sure we haven't missed
4045 		 * anything interesting.
4046 		 */
4047 		t4_slow_intr_handler(sc, sc->intr_flags);
4048 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
4049 	}
4050 	t4_report_fw_error(sc);
4051 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
4052 	    device_get_nameunit(sc->dev), fw_error);
4053 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
4054 }
4055 
4056 void
4057 t4_add_adapter(struct adapter *sc)
4058 {
4059 	sx_xlock(&t4_list_lock);
4060 	SLIST_INSERT_HEAD(&t4_list, sc, link);
4061 	sx_xunlock(&t4_list_lock);
4062 }
4063 
4064 int
4065 t4_map_bars_0_and_4(struct adapter *sc)
4066 {
4067 	sc->regs_rid = PCIR_BAR(0);
4068 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4069 	    &sc->regs_rid, RF_ACTIVE);
4070 	if (sc->regs_res == NULL) {
4071 		device_printf(sc->dev, "cannot map registers.\n");
4072 		return (ENXIO);
4073 	}
4074 	sc->mmio_len = rman_get_size(sc->regs_res);
4075 	setbit(&sc->doorbells, DOORBELL_KDB);
4076 
4077 	sc->msix_rid = PCIR_BAR(4);
4078 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4079 	    &sc->msix_rid, RF_ACTIVE);
4080 	if (sc->msix_res == NULL) {
4081 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
4082 		return (ENXIO);
4083 	}
4084 
4085 	return (0);
4086 }
4087 
4088 int
4089 t4_map_bar_2(struct adapter *sc)
4090 {
4091 
4092 	/*
4093 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
4094 	 * to map it if RDMA is disabled.
4095 	 */
4096 	if (is_t4(sc) && sc->rdmacaps == 0)
4097 		return (0);
4098 
4099 	sc->udbs_rid = PCIR_BAR(2);
4100 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
4101 	    &sc->udbs_rid, RF_ACTIVE);
4102 	if (sc->udbs_res == NULL) {
4103 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
4104 		return (ENXIO);
4105 	}
4106 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
4107 
4108 	if (chip_id(sc) >= CHELSIO_T5) {
4109 		setbit(&sc->doorbells, DOORBELL_UDB);
4110 #if defined(__i386__) || defined(__amd64__)
4111 		if (t5_write_combine) {
4112 			int rc, mode;
4113 
4114 			/*
4115 			 * Enable write combining on BAR2.  This is the
4116 			 * userspace doorbell BAR and is split into 128B
4117 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
4118 			 * with an egress queue.  The first 64B has the doorbell
4119 			 * and the second 64B can be used to submit a tx work
4120 			 * request with an implicit doorbell.
4121 			 */
4122 
4123 			rc = pmap_change_attr(__DEVOLATILE(void *, sc->udbs_base),
4124 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
4125 			if (rc == 0) {
4126 				clrbit(&sc->doorbells, DOORBELL_UDB);
4127 				setbit(&sc->doorbells, DOORBELL_WCWR);
4128 				setbit(&sc->doorbells, DOORBELL_UDBWC);
4129 			} else {
4130 				device_printf(sc->dev,
4131 				    "couldn't enable write combining: %d\n",
4132 				    rc);
4133 			}
4134 
4135 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
4136 			t4_write_reg(sc, A_SGE_STAT_CFG,
4137 			    V_STATSOURCE_T5(7) | mode);
4138 		}
4139 #endif
4140 	}
4141 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
4142 
4143 	return (0);
4144 }
4145 
4146 int
4147 t4_adj_doorbells(struct adapter *sc)
4148 {
4149 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
4150 		sc->doorbells &= t4_doorbells_allowed;
4151 		return (0);
4152 	}
4153 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
4154 	       sc->doorbells, t4_doorbells_allowed);
4155 	return (EINVAL);
4156 }
4157 
4158 struct memwin_init {
4159 	uint32_t base;
4160 	uint32_t aperture;
4161 };
4162 
4163 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
4164 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4165 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4166 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
4167 };
4168 
4169 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
4170 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
4171 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
4172 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
4173 };
4174 
4175 static void
4176 setup_memwin(struct adapter *sc)
4177 {
4178 	const struct memwin_init *mw_init;
4179 	struct memwin *mw;
4180 	int i;
4181 	uint32_t bar0, reg;
4182 
4183 	if (is_t4(sc)) {
4184 		/*
4185 		 * Read low 32b of bar0 indirectly via the hardware backdoor
4186 		 * mechanism.  Works from within PCI passthrough environments
4187 		 * too, where rman_get_start() can return a different value.  We
4188 		 * need to program the T4 memory window decoders with the actual
4189 		 * addresses that will be coming across the PCIe link.
4190 		 */
4191 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
4192 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
4193 
4194 		mw_init = &t4_memwin[0];
4195 	} else {
4196 		/* T5+ use the relative offset inside the PCIe BAR */
4197 		bar0 = 0;
4198 
4199 		mw_init = &t5_memwin[0];
4200 	}
4201 
4202 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
4203 		if (!rw_initialized(&mw->mw_lock)) {
4204 			rw_init(&mw->mw_lock, "memory window access");
4205 			mw->mw_base = mw_init->base;
4206 			mw->mw_aperture = mw_init->aperture;
4207 			mw->mw_curpos = 0;
4208 		}
4209 		reg = chip_id(sc) > CHELSIO_T6 ?
4210 		    PCIE_MEM_ACCESS_T7_REG(A_T7_PCIE_MEM_ACCESS_BASE_WIN, i) :
4211 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i);
4212 		t4_write_reg(sc, reg, (mw->mw_base + bar0) | V_BIR(0) |
4213 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
4214 		rw_wlock(&mw->mw_lock);
4215 		position_memwin(sc, i, mw->mw_curpos);
4216 		rw_wunlock(&mw->mw_lock);
4217 	}
4218 
4219 	/* flush */
4220 	t4_read_reg(sc, reg);
4221 }
4222 
4223 /*
4224  * Positions the memory window at the given address in the card's address space.
4225  * There are some alignment requirements and the actual position may be at an
4226  * address prior to the requested address.  mw->mw_curpos always has the actual
4227  * position of the window.
4228  */
4229 static void
4230 position_memwin(struct adapter *sc, int idx, uint32_t addr)
4231 {
4232 	struct memwin *mw;
4233 	uint32_t pf, reg, val;
4234 
4235 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4236 	mw = &sc->memwin[idx];
4237 	rw_assert(&mw->mw_lock, RA_WLOCKED);
4238 
4239 	if (is_t4(sc)) {
4240 		pf = 0;
4241 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
4242 	} else {
4243 		pf = V_PFNUM(sc->pf);
4244 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
4245 	}
4246 	if (chip_id(sc) > CHELSIO_T6) {
4247 		reg = PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, idx);
4248 		val = (mw->mw_curpos >> X_T7_MEMOFST_SHIFT) | pf;
4249 	} else {
4250 		reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
4251 		val = mw->mw_curpos | pf;
4252 	}
4253 	t4_write_reg(sc, reg, val);
4254 	t4_read_reg(sc, reg);	/* flush */
4255 }
4256 
4257 int
4258 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
4259     int len, int rw)
4260 {
4261 	struct memwin *mw;
4262 	uint32_t mw_end, v;
4263 
4264 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
4265 
4266 	/* Memory can only be accessed in naturally aligned 4 byte units */
4267 	if (addr & 3 || len & 3 || len <= 0)
4268 		return (EINVAL);
4269 
4270 	mw = &sc->memwin[idx];
4271 	while (len > 0) {
4272 		rw_rlock(&mw->mw_lock);
4273 		mw_end = mw->mw_curpos + mw->mw_aperture;
4274 		if (addr >= mw_end || addr < mw->mw_curpos) {
4275 			/* Will need to reposition the window */
4276 			if (!rw_try_upgrade(&mw->mw_lock)) {
4277 				rw_runlock(&mw->mw_lock);
4278 				rw_wlock(&mw->mw_lock);
4279 			}
4280 			rw_assert(&mw->mw_lock, RA_WLOCKED);
4281 			position_memwin(sc, idx, addr);
4282 			rw_downgrade(&mw->mw_lock);
4283 			mw_end = mw->mw_curpos + mw->mw_aperture;
4284 		}
4285 		rw_assert(&mw->mw_lock, RA_RLOCKED);
4286 		while (addr < mw_end && len > 0) {
4287 			if (rw == 0) {
4288 				v = t4_read_reg(sc, mw->mw_base + addr -
4289 				    mw->mw_curpos);
4290 				*val++ = le32toh(v);
4291 			} else {
4292 				v = *val++;
4293 				t4_write_reg(sc, mw->mw_base + addr -
4294 				    mw->mw_curpos, htole32(v));
4295 			}
4296 			addr += 4;
4297 			len -= 4;
4298 		}
4299 		rw_runlock(&mw->mw_lock);
4300 	}
4301 
4302 	return (0);
4303 }
4304 
4305 CTASSERT(M_TID_COOKIE == M_COOKIE);
4306 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
4307 
4308 static void
4309 t4_init_atid_table(struct adapter *sc)
4310 {
4311 	struct tid_info *t;
4312 	int i;
4313 
4314 	t = &sc->tids;
4315 	if (t->natids == 0)
4316 		return;
4317 
4318 	MPASS(t->atid_tab == NULL);
4319 
4320 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
4321 	    M_ZERO | M_WAITOK);
4322 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
4323 	t->afree = t->atid_tab;
4324 	t->atids_in_use = 0;
4325 	t->atid_alloc_stopped = false;
4326 	for (i = 1; i < t->natids; i++)
4327 		t->atid_tab[i - 1].next = &t->atid_tab[i];
4328 	t->atid_tab[t->natids - 1].next = NULL;
4329 }
4330 
4331 static void
4332 t4_free_atid_table(struct adapter *sc)
4333 {
4334 	struct tid_info *t;
4335 
4336 	t = &sc->tids;
4337 
4338 	KASSERT(t->atids_in_use == 0,
4339 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4340 
4341 	if (mtx_initialized(&t->atid_lock))
4342 		mtx_destroy(&t->atid_lock);
4343 	free(t->atid_tab, M_CXGBE);
4344 	t->atid_tab = NULL;
4345 }
4346 
4347 static void
4348 stop_atid_allocator(struct adapter *sc)
4349 {
4350 	struct tid_info *t = &sc->tids;
4351 
4352 	if (t->natids == 0)
4353 		return;
4354 	mtx_lock(&t->atid_lock);
4355 	t->atid_alloc_stopped = true;
4356 	mtx_unlock(&t->atid_lock);
4357 }
4358 
4359 static void
4360 restart_atid_allocator(struct adapter *sc)
4361 {
4362 	struct tid_info *t = &sc->tids;
4363 
4364 	if (t->natids == 0)
4365 		return;
4366 	mtx_lock(&t->atid_lock);
4367 	KASSERT(t->atids_in_use == 0,
4368 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4369 	t->atid_alloc_stopped = false;
4370 	mtx_unlock(&t->atid_lock);
4371 }
4372 
4373 int
4374 alloc_atid(struct adapter *sc, void *ctx)
4375 {
4376 	struct tid_info *t = &sc->tids;
4377 	int atid = -1;
4378 
4379 	mtx_lock(&t->atid_lock);
4380 	if (t->afree && !t->atid_alloc_stopped) {
4381 		union aopen_entry *p = t->afree;
4382 
4383 		atid = p - t->atid_tab;
4384 		MPASS(atid <= M_TID_TID);
4385 		t->afree = p->next;
4386 		p->data = ctx;
4387 		t->atids_in_use++;
4388 	}
4389 	mtx_unlock(&t->atid_lock);
4390 	return (atid);
4391 }
4392 
4393 void *
4394 lookup_atid(struct adapter *sc, int atid)
4395 {
4396 	struct tid_info *t = &sc->tids;
4397 
4398 	return (t->atid_tab[atid].data);
4399 }
4400 
4401 void
4402 free_atid(struct adapter *sc, int atid)
4403 {
4404 	struct tid_info *t = &sc->tids;
4405 	union aopen_entry *p = &t->atid_tab[atid];
4406 
4407 	mtx_lock(&t->atid_lock);
4408 	p->next = t->afree;
4409 	t->afree = p;
4410 	t->atids_in_use--;
4411 	mtx_unlock(&t->atid_lock);
4412 }
4413 
4414 static void
4415 queue_tid_release(struct adapter *sc, int tid)
4416 {
4417 
4418 	CXGBE_UNIMPLEMENTED("deferred tid release");
4419 }
4420 
4421 void
4422 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4423 {
4424 	struct wrqe *wr;
4425 	struct cpl_tid_release *req;
4426 
4427 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4428 	if (wr == NULL) {
4429 		queue_tid_release(sc, tid);	/* defer */
4430 		return;
4431 	}
4432 	req = wrtod(wr);
4433 
4434 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4435 
4436 	t4_wrq_tx(sc, wr);
4437 }
4438 
4439 static int
4440 t4_range_cmp(const void *a, const void *b)
4441 {
4442 	return ((const struct t4_range *)a)->start -
4443 	       ((const struct t4_range *)b)->start;
4444 }
4445 
4446 /*
4447  * Verify that the memory range specified by the addr/len pair is valid within
4448  * the card's address space.
4449  */
4450 static int
4451 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4452 {
4453 	struct t4_range mem_ranges[4], *r, *next;
4454 	uint32_t em, addr_len;
4455 	int i, n, remaining;
4456 
4457 	/* Memory can only be accessed in naturally aligned 4 byte units */
4458 	if (addr & 3 || len & 3 || len == 0)
4459 		return (EINVAL);
4460 
4461 	/* Enabled memories */
4462 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4463 
4464 	r = &mem_ranges[0];
4465 	n = 0;
4466 	bzero(r, sizeof(mem_ranges));
4467 	if (em & F_EDRAM0_ENABLE) {
4468 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4469 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4470 		if (r->size > 0) {
4471 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4472 			if (addr >= r->start &&
4473 			    addr + len <= r->start + r->size)
4474 				return (0);
4475 			r++;
4476 			n++;
4477 		}
4478 	}
4479 	if (em & F_EDRAM1_ENABLE) {
4480 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4481 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4482 		if (r->size > 0) {
4483 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4484 			if (addr >= r->start &&
4485 			    addr + len <= r->start + r->size)
4486 				return (0);
4487 			r++;
4488 			n++;
4489 		}
4490 	}
4491 	if (em & F_EXT_MEM_ENABLE) {
4492 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4493 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4494 		if (r->size > 0) {
4495 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4496 			if (addr >= r->start &&
4497 			    addr + len <= r->start + r->size)
4498 				return (0);
4499 			r++;
4500 			n++;
4501 		}
4502 	}
4503 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4504 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4505 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4506 		if (r->size > 0) {
4507 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4508 			if (addr >= r->start &&
4509 			    addr + len <= r->start + r->size)
4510 				return (0);
4511 			r++;
4512 			n++;
4513 		}
4514 	}
4515 	MPASS(n <= nitems(mem_ranges));
4516 
4517 	if (n > 1) {
4518 		/* Sort and merge the ranges. */
4519 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4520 
4521 		/* Start from index 0 and examine the next n - 1 entries. */
4522 		r = &mem_ranges[0];
4523 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4524 
4525 			MPASS(r->size > 0);	/* r is a valid entry. */
4526 			next = r + 1;
4527 			MPASS(next->size > 0);	/* and so is the next one. */
4528 
4529 			while (r->start + r->size >= next->start) {
4530 				/* Merge the next one into the current entry. */
4531 				r->size = max(r->start + r->size,
4532 				    next->start + next->size) - r->start;
4533 				n--;	/* One fewer entry in total. */
4534 				if (--remaining == 0)
4535 					goto done;	/* short circuit */
4536 				next++;
4537 			}
4538 			if (next != r + 1) {
4539 				/*
4540 				 * Some entries were merged into r and next
4541 				 * points to the first valid entry that couldn't
4542 				 * be merged.
4543 				 */
4544 				MPASS(next->size > 0);	/* must be valid */
4545 				memcpy(r + 1, next, remaining * sizeof(*r));
4546 #ifdef INVARIANTS
4547 				/*
4548 				 * This so that the foo->size assertion in the
4549 				 * next iteration of the loop do the right
4550 				 * thing for entries that were pulled up and are
4551 				 * no longer valid.
4552 				 */
4553 				MPASS(n < nitems(mem_ranges));
4554 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4555 				    sizeof(struct t4_range));
4556 #endif
4557 			}
4558 		}
4559 done:
4560 		/* Done merging the ranges. */
4561 		MPASS(n > 0);
4562 		r = &mem_ranges[0];
4563 		for (i = 0; i < n; i++, r++) {
4564 			if (addr >= r->start &&
4565 			    addr + len <= r->start + r->size)
4566 				return (0);
4567 		}
4568 	}
4569 
4570 	return (EFAULT);
4571 }
4572 
4573 static int
4574 fwmtype_to_hwmtype(int mtype)
4575 {
4576 
4577 	switch (mtype) {
4578 	case FW_MEMTYPE_EDC0:
4579 		return (MEM_EDC0);
4580 	case FW_MEMTYPE_EDC1:
4581 		return (MEM_EDC1);
4582 	case FW_MEMTYPE_EXTMEM:
4583 		return (MEM_MC0);
4584 	case FW_MEMTYPE_EXTMEM1:
4585 		return (MEM_MC1);
4586 	default:
4587 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4588 	}
4589 }
4590 
4591 /*
4592  * Verify that the memory range specified by the memtype/offset/len pair is
4593  * valid and lies entirely within the memtype specified.  The global address of
4594  * the start of the range is returned in addr.
4595  */
4596 static int
4597 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4598     uint32_t *addr)
4599 {
4600 	uint32_t em, addr_len, maddr;
4601 
4602 	/* Memory can only be accessed in naturally aligned 4 byte units */
4603 	if (off & 3 || len & 3 || len == 0)
4604 		return (EINVAL);
4605 
4606 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4607 	switch (fwmtype_to_hwmtype(mtype)) {
4608 	case MEM_EDC0:
4609 		if (!(em & F_EDRAM0_ENABLE))
4610 			return (EINVAL);
4611 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4612 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4613 		break;
4614 	case MEM_EDC1:
4615 		if (!(em & F_EDRAM1_ENABLE))
4616 			return (EINVAL);
4617 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4618 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4619 		break;
4620 	case MEM_MC:
4621 		if (!(em & F_EXT_MEM_ENABLE))
4622 			return (EINVAL);
4623 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4624 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4625 		break;
4626 	case MEM_MC1:
4627 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4628 			return (EINVAL);
4629 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4630 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4631 		break;
4632 	default:
4633 		return (EINVAL);
4634 	}
4635 
4636 	*addr = maddr + off;	/* global address */
4637 	return (validate_mem_range(sc, *addr, len));
4638 }
4639 
4640 static int
4641 fixup_devlog_ncores_params(struct adapter *sc)
4642 {
4643 	struct devlog_params *dparams = &sc->params.devlog;
4644 	int rc;
4645 
4646 #ifdef INVARIANTS
4647 	if (sc->params.ncores > 1)
4648 		MPASS(chip_id(sc) >= CHELSIO_T7);
4649 #endif
4650 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4651 	    dparams->size, &dparams->addr);
4652 
4653 	return (rc);
4654 }
4655 
4656 static void
4657 update_nirq(struct intrs_and_queues *iaq, int nports)
4658 {
4659 
4660 	iaq->nirq = T4_EXTRA_INTR;
4661 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4662 	iaq->nirq += nports * iaq->nofldrxq;
4663 	iaq->nirq += nports * (iaq->num_vis - 1) *
4664 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4665 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4666 }
4667 
4668 /*
4669  * Adjust requirements to fit the number of interrupts available.
4670  */
4671 static void
4672 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4673     int navail)
4674 {
4675 	int old_nirq;
4676 	const int nports = sc->params.nports;
4677 
4678 	MPASS(nports > 0);
4679 	MPASS(navail > 0);
4680 
4681 	bzero(iaq, sizeof(*iaq));
4682 	iaq->intr_type = itype;
4683 	iaq->num_vis = t4_num_vis;
4684 	iaq->ntxq = t4_ntxq;
4685 	iaq->ntxq_vi = t4_ntxq_vi;
4686 	iaq->nrxq = t4_nrxq;
4687 	iaq->nrxq_vi = t4_nrxq_vi;
4688 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4689 	if (is_offload(sc) || is_ethoffload(sc)) {
4690 		if (sc->params.tid_qid_sel_mask == 0) {
4691 			iaq->nofldtxq = t4_nofldtxq;
4692 			iaq->nofldtxq_vi = t4_nofldtxq_vi;
4693 		} else {
4694 			iaq->nofldtxq = roundup(t4_nofldtxq, sc->params.ncores);
4695 			iaq->nofldtxq_vi = roundup(t4_nofldtxq_vi,
4696 			    sc->params.ncores);
4697 			if (iaq->nofldtxq != t4_nofldtxq)
4698 				device_printf(sc->dev,
4699 				    "nofldtxq updated (%d -> %d) for correct"
4700 				    " operation with %d firmware cores.\n",
4701 				    t4_nofldtxq, iaq->nofldtxq,
4702 				    sc->params.ncores);
4703 			if (iaq->num_vis > 1 &&
4704 			    iaq->nofldtxq_vi != t4_nofldtxq_vi)
4705 				device_printf(sc->dev,
4706 				    "nofldtxq_vi updated (%d -> %d) for correct"
4707 				    " operation with %d firmware cores.\n",
4708 				    t4_nofldtxq_vi, iaq->nofldtxq_vi,
4709 				    sc->params.ncores);
4710 		}
4711 	}
4712 #endif
4713 #ifdef TCP_OFFLOAD
4714 	if (is_offload(sc)) {
4715 		iaq->nofldrxq = t4_nofldrxq;
4716 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4717 	}
4718 #endif
4719 #ifdef DEV_NETMAP
4720 	if (t4_native_netmap & NN_MAIN_VI) {
4721 		iaq->nnmtxq = t4_nnmtxq;
4722 		iaq->nnmrxq = t4_nnmrxq;
4723 	}
4724 	if (t4_native_netmap & NN_EXTRA_VI) {
4725 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4726 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4727 	}
4728 #endif
4729 
4730 	update_nirq(iaq, nports);
4731 	if (iaq->nirq <= navail &&
4732 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4733 		/*
4734 		 * This is the normal case -- there are enough interrupts for
4735 		 * everything.
4736 		 */
4737 		goto done;
4738 	}
4739 
4740 	/*
4741 	 * If extra VIs have been configured try reducing their count and see if
4742 	 * that works.
4743 	 */
4744 	while (iaq->num_vis > 1) {
4745 		iaq->num_vis--;
4746 		update_nirq(iaq, nports);
4747 		if (iaq->nirq <= navail &&
4748 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4749 			device_printf(sc->dev, "virtual interfaces per port "
4750 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4751 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4752 			    "itype %d, navail %u, nirq %d.\n",
4753 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4754 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4755 			    itype, navail, iaq->nirq);
4756 			goto done;
4757 		}
4758 	}
4759 
4760 	/*
4761 	 * Extra VIs will not be created.  Log a message if they were requested.
4762 	 */
4763 	MPASS(iaq->num_vis == 1);
4764 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4765 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4766 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4767 	if (iaq->num_vis != t4_num_vis) {
4768 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4769 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4770 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4771 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4772 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4773 	}
4774 
4775 	/*
4776 	 * Keep reducing the number of NIC rx queues to the next lower power of
4777 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4778 	 * if that works.
4779 	 */
4780 	do {
4781 		if (iaq->nrxq > 1) {
4782 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4783 			if (iaq->nnmrxq > iaq->nrxq)
4784 				iaq->nnmrxq = iaq->nrxq;
4785 		}
4786 		if (iaq->nofldrxq > 1)
4787 			iaq->nofldrxq >>= 1;
4788 
4789 		old_nirq = iaq->nirq;
4790 		update_nirq(iaq, nports);
4791 		if (iaq->nirq <= navail &&
4792 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4793 			device_printf(sc->dev, "running with reduced number of "
4794 			    "rx queues because of shortage of interrupts.  "
4795 			    "nrxq=%u, nofldrxq=%u.  "
4796 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4797 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4798 			goto done;
4799 		}
4800 	} while (old_nirq != iaq->nirq);
4801 
4802 	/* One interrupt for everything.  Ugh. */
4803 	device_printf(sc->dev, "running with minimal number of queues.  "
4804 	    "itype %d, navail %u.\n", itype, navail);
4805 	iaq->nirq = 1;
4806 	iaq->nrxq = 1;
4807 	iaq->ntxq = 1;
4808 	if (iaq->nofldrxq > 0) {
4809 		iaq->nofldrxq = 1;
4810 		iaq->nofldtxq = 1;
4811 		if (sc->params.tid_qid_sel_mask == 0)
4812 			iaq->nofldtxq = 1;
4813 		else
4814 			iaq->nofldtxq = sc->params.ncores;
4815 	}
4816 	iaq->nnmtxq = 0;
4817 	iaq->nnmrxq = 0;
4818 done:
4819 	MPASS(iaq->num_vis > 0);
4820 	if (iaq->num_vis > 1) {
4821 		MPASS(iaq->nrxq_vi > 0);
4822 		MPASS(iaq->ntxq_vi > 0);
4823 	}
4824 	MPASS(iaq->nirq > 0);
4825 	MPASS(iaq->nrxq > 0);
4826 	MPASS(iaq->ntxq > 0);
4827 	if (itype == INTR_MSI)
4828 		MPASS(powerof2(iaq->nirq));
4829 	if (sc->params.tid_qid_sel_mask != 0)
4830 		MPASS(iaq->nofldtxq % sc->params.ncores == 0);
4831 }
4832 
4833 static int
4834 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4835 {
4836 	int rc, itype, navail, nalloc;
4837 
4838 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4839 
4840 		if ((itype & t4_intr_types) == 0)
4841 			continue;	/* not allowed */
4842 
4843 		if (itype == INTR_MSIX)
4844 			navail = pci_msix_count(sc->dev);
4845 		else if (itype == INTR_MSI)
4846 			navail = pci_msi_count(sc->dev);
4847 		else
4848 			navail = 1;
4849 restart:
4850 		if (navail == 0)
4851 			continue;
4852 
4853 		calculate_iaq(sc, iaq, itype, navail);
4854 		nalloc = iaq->nirq;
4855 		rc = 0;
4856 		if (itype == INTR_MSIX)
4857 			rc = pci_alloc_msix(sc->dev, &nalloc);
4858 		else if (itype == INTR_MSI)
4859 			rc = pci_alloc_msi(sc->dev, &nalloc);
4860 
4861 		if (rc == 0 && nalloc > 0) {
4862 			if (nalloc == iaq->nirq)
4863 				return (0);
4864 
4865 			/*
4866 			 * Didn't get the number requested.  Use whatever number
4867 			 * the kernel is willing to allocate.
4868 			 */
4869 			device_printf(sc->dev, "fewer vectors than requested, "
4870 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4871 			    itype, iaq->nirq, nalloc);
4872 			pci_release_msi(sc->dev);
4873 			navail = nalloc;
4874 			goto restart;
4875 		}
4876 
4877 		device_printf(sc->dev,
4878 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4879 		    itype, rc, iaq->nirq, nalloc);
4880 	}
4881 
4882 	device_printf(sc->dev,
4883 	    "failed to find a usable interrupt type.  "
4884 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4885 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4886 
4887 	return (ENXIO);
4888 }
4889 
4890 #define FW_VERSION(chip) ( \
4891     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4892     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4893     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4894     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4895 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4896 
4897 /* Just enough of fw_hdr to cover all version info. */
4898 struct fw_h {
4899 	__u8	ver;
4900 	__u8	chip;
4901 	__be16	len512;
4902 	__be32	fw_ver;
4903 	__be32	tp_microcode_ver;
4904 	__u8	intfver_nic;
4905 	__u8	intfver_vnic;
4906 	__u8	intfver_ofld;
4907 	__u8	intfver_ri;
4908 	__u8	intfver_iscsipdu;
4909 	__u8	intfver_iscsi;
4910 	__u8	intfver_fcoepdu;
4911 	__u8	intfver_fcoe;
4912 };
4913 /* Spot check a couple of fields. */
4914 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4915 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4916 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4917 
4918 struct fw_info {
4919 	uint8_t chip;
4920 	char *kld_name;
4921 	char *fw_mod_name;
4922 	struct fw_h fw_h;
4923 } fw_info[] = {
4924 	{
4925 		.chip = CHELSIO_T4,
4926 		.kld_name = "t4fw_cfg",
4927 		.fw_mod_name = "t4fw",
4928 		.fw_h = {
4929 			.chip = FW_HDR_CHIP_T4,
4930 			.fw_ver = htobe32(FW_VERSION(T4)),
4931 			.intfver_nic = FW_INTFVER(T4, NIC),
4932 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4933 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4934 			.intfver_ri = FW_INTFVER(T4, RI),
4935 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4936 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4937 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4938 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4939 		},
4940 	}, {
4941 		.chip = CHELSIO_T5,
4942 		.kld_name = "t5fw_cfg",
4943 		.fw_mod_name = "t5fw",
4944 		.fw_h = {
4945 			.chip = FW_HDR_CHIP_T5,
4946 			.fw_ver = htobe32(FW_VERSION(T5)),
4947 			.intfver_nic = FW_INTFVER(T5, NIC),
4948 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4949 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4950 			.intfver_ri = FW_INTFVER(T5, RI),
4951 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4952 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4953 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4954 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4955 		},
4956 	}, {
4957 		.chip = CHELSIO_T6,
4958 		.kld_name = "t6fw_cfg",
4959 		.fw_mod_name = "t6fw",
4960 		.fw_h = {
4961 			.chip = FW_HDR_CHIP_T6,
4962 			.fw_ver = htobe32(FW_VERSION(T6)),
4963 			.intfver_nic = FW_INTFVER(T6, NIC),
4964 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4965 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4966 			.intfver_ri = FW_INTFVER(T6, RI),
4967 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4968 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4969 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4970 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4971 		},
4972 	}, {
4973 		.chip = CHELSIO_T7,
4974 		.kld_name = "t7fw_cfg",
4975 		.fw_mod_name = "t7fw",
4976 		.fw_h = {
4977 			.chip = FW_HDR_CHIP_T7,
4978 			.fw_ver = htobe32(FW_VERSION(T7)),
4979 			.intfver_nic = FW_INTFVER(T7, NIC),
4980 			.intfver_vnic = FW_INTFVER(T7, VNIC),
4981 			.intfver_ofld = FW_INTFVER(T7, OFLD),
4982 			.intfver_ri = FW_INTFVER(T7, RI),
4983 			.intfver_iscsipdu = FW_INTFVER(T7, ISCSIPDU),
4984 			.intfver_iscsi = FW_INTFVER(T7, ISCSI),
4985 			.intfver_fcoepdu = FW_INTFVER(T7, FCOEPDU),
4986 			.intfver_fcoe = FW_INTFVER(T7, FCOE),
4987 		},
4988 	}
4989 };
4990 
4991 static struct fw_info *
4992 find_fw_info(int chip)
4993 {
4994 	int i;
4995 
4996 	for (i = 0; i < nitems(fw_info); i++) {
4997 		if (fw_info[i].chip == chip)
4998 			return (&fw_info[i]);
4999 	}
5000 	return (NULL);
5001 }
5002 
5003 /*
5004  * Is the given firmware API compatible with the one the driver was compiled
5005  * with?
5006  */
5007 static int
5008 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
5009 {
5010 
5011 	/* short circuit if it's the exact same firmware version */
5012 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
5013 		return (1);
5014 
5015 	/*
5016 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
5017 	 * features that are supported in the driver.
5018 	 */
5019 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
5020 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
5021 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
5022 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
5023 		return (1);
5024 #undef SAME_INTF
5025 
5026 	return (0);
5027 }
5028 
5029 static int
5030 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
5031     const struct firmware **fw)
5032 {
5033 	struct fw_info *fw_info;
5034 
5035 	*dcfg = NULL;
5036 	if (fw != NULL)
5037 		*fw = NULL;
5038 
5039 	fw_info = find_fw_info(chip_id(sc));
5040 	if (fw_info == NULL) {
5041 		device_printf(sc->dev,
5042 		    "unable to look up firmware information for chip %d.\n",
5043 		    chip_id(sc));
5044 		return (EINVAL);
5045 	}
5046 
5047 	*dcfg = firmware_get(fw_info->kld_name);
5048 	if (*dcfg != NULL) {
5049 		if (fw != NULL)
5050 			*fw = firmware_get(fw_info->fw_mod_name);
5051 		return (0);
5052 	}
5053 
5054 	return (ENOENT);
5055 }
5056 
5057 static void
5058 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
5059     const struct firmware *fw)
5060 {
5061 
5062 	if (fw != NULL)
5063 		firmware_put(fw, FIRMWARE_UNLOAD);
5064 	if (dcfg != NULL)
5065 		firmware_put(dcfg, FIRMWARE_UNLOAD);
5066 }
5067 
5068 /*
5069  * Return values:
5070  * 0 means no firmware install attempted.
5071  * ERESTART means a firmware install was attempted and was successful.
5072  * +ve errno means a firmware install was attempted but failed.
5073  */
5074 static int
5075 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
5076     const struct fw_h *drv_fw, const char *reason, int *already)
5077 {
5078 	const struct firmware *cfg, *fw;
5079 	const uint32_t c = be32toh(card_fw->fw_ver);
5080 	uint32_t d, k;
5081 	int rc, fw_install;
5082 	struct fw_h bundled_fw;
5083 	bool load_attempted;
5084 
5085 	cfg = fw = NULL;
5086 	load_attempted = false;
5087 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
5088 
5089 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
5090 	if (t4_fw_install < 0) {
5091 		rc = load_fw_module(sc, &cfg, &fw);
5092 		if (rc != 0 || fw == NULL) {
5093 			device_printf(sc->dev,
5094 			    "failed to load firmware module: %d. cfg %p, fw %p;"
5095 			    " will use compiled-in firmware version for"
5096 			    "hw.cxgbe.fw_install checks.\n",
5097 			    rc, cfg, fw);
5098 		} else {
5099 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
5100 		}
5101 		load_attempted = true;
5102 	}
5103 	d = be32toh(bundled_fw.fw_ver);
5104 
5105 	if (reason != NULL)
5106 		goto install;
5107 
5108 	if ((sc->flags & FW_OK) == 0) {
5109 
5110 		if (c == 0xffffffff) {
5111 			reason = "missing";
5112 			goto install;
5113 		}
5114 
5115 		rc = 0;
5116 		goto done;
5117 	}
5118 
5119 	if (!fw_compatible(card_fw, &bundled_fw)) {
5120 		reason = "incompatible or unusable";
5121 		goto install;
5122 	}
5123 
5124 	if (d > c) {
5125 		reason = "older than the version bundled with this driver";
5126 		goto install;
5127 	}
5128 
5129 	if (fw_install == 2 && d != c) {
5130 		reason = "different than the version bundled with this driver";
5131 		goto install;
5132 	}
5133 
5134 	/* No reason to do anything to the firmware already on the card. */
5135 	rc = 0;
5136 	goto done;
5137 
5138 install:
5139 	rc = 0;
5140 	if ((*already)++)
5141 		goto done;
5142 
5143 	if (fw_install == 0) {
5144 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5145 		    "but the driver is prohibited from installing a firmware "
5146 		    "on the card.\n",
5147 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5148 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5149 
5150 		goto done;
5151 	}
5152 
5153 	/*
5154 	 * We'll attempt to install a firmware.  Load the module first (if it
5155 	 * hasn't been loaded already).
5156 	 */
5157 	if (!load_attempted) {
5158 		rc = load_fw_module(sc, &cfg, &fw);
5159 		if (rc != 0 || fw == NULL) {
5160 			device_printf(sc->dev,
5161 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
5162 			    rc, cfg, fw);
5163 			/* carry on */
5164 		}
5165 	}
5166 	if (fw == NULL) {
5167 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5168 		    "but the driver cannot take corrective action because it "
5169 		    "is unable to load the firmware module.\n",
5170 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5171 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
5172 		rc = sc->flags & FW_OK ? 0 : ENOENT;
5173 		goto done;
5174 	}
5175 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
5176 	if (k != d) {
5177 		MPASS(t4_fw_install > 0);
5178 		device_printf(sc->dev,
5179 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
5180 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
5181 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
5182 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
5183 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5184 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5185 		rc = sc->flags & FW_OK ? 0 : EINVAL;
5186 		goto done;
5187 	}
5188 
5189 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
5190 	    "installing firmware %u.%u.%u.%u on card.\n",
5191 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
5192 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
5193 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
5194 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
5195 
5196 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
5197 	if (rc != 0) {
5198 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
5199 	} else {
5200 		/* Installed successfully, update the cached header too. */
5201 		rc = ERESTART;
5202 		memcpy(card_fw, fw->data, sizeof(*card_fw));
5203 	}
5204 done:
5205 	unload_fw_module(sc, cfg, fw);
5206 
5207 	return (rc);
5208 }
5209 
5210 /*
5211  * Establish contact with the firmware and attempt to become the master driver.
5212  *
5213  * A firmware will be installed to the card if needed (if the driver is allowed
5214  * to do so).
5215  */
5216 static int
5217 contact_firmware(struct adapter *sc)
5218 {
5219 	int rc, already = 0;
5220 	enum dev_state state;
5221 	struct fw_info *fw_info;
5222 	struct fw_hdr *card_fw;		/* fw on the card */
5223 	const struct fw_h *drv_fw;
5224 
5225 	fw_info = find_fw_info(chip_id(sc));
5226 	if (fw_info == NULL) {
5227 		device_printf(sc->dev,
5228 		    "unable to look up firmware information for chip %d.\n",
5229 		    chip_id(sc));
5230 		return (EINVAL);
5231 	}
5232 	drv_fw = &fw_info->fw_h;
5233 
5234 	/* Read the header of the firmware on the card */
5235 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
5236 restart:
5237 	rc = -t4_get_fw_hdr(sc, card_fw);
5238 	if (rc != 0) {
5239 		device_printf(sc->dev,
5240 		    "unable to read firmware header from card's flash: %d\n",
5241 		    rc);
5242 		goto done;
5243 	}
5244 
5245 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
5246 	    &already);
5247 	if (rc == ERESTART)
5248 		goto restart;
5249 	if (rc != 0)
5250 		goto done;
5251 
5252 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
5253 	if (rc < 0 || state == DEV_STATE_ERR) {
5254 		rc = -rc;
5255 		device_printf(sc->dev,
5256 		    "failed to connect to the firmware: %d, %d.  "
5257 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5258 #if 0
5259 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5260 		    "not responding properly to HELLO", &already) == ERESTART)
5261 			goto restart;
5262 #endif
5263 		goto done;
5264 	}
5265 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
5266 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
5267 
5268 	if (rc == sc->pf) {
5269 		sc->flags |= MASTER_PF;
5270 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
5271 		    NULL, &already);
5272 		if (rc == ERESTART)
5273 			rc = 0;
5274 		else if (rc != 0)
5275 			goto done;
5276 	} else if (state == DEV_STATE_UNINIT) {
5277 		/*
5278 		 * We didn't get to be the master so we definitely won't be
5279 		 * configuring the chip.  It's a bug if someone else hasn't
5280 		 * configured it already.
5281 		 */
5282 		device_printf(sc->dev, "couldn't be master(%d), "
5283 		    "device not already initialized either(%d).  "
5284 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5285 		rc = EPROTO;
5286 		goto done;
5287 	} else {
5288 		/*
5289 		 * Some other PF is the master and has configured the chip.
5290 		 * This is allowed but untested.
5291 		 */
5292 		device_printf(sc->dev, "PF%d is master, device state %d.  "
5293 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
5294 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
5295 		sc->cfcsum = 0;
5296 		rc = 0;
5297 	}
5298 done:
5299 	if (rc != 0 && sc->flags & FW_OK) {
5300 		t4_fw_bye(sc, sc->mbox);
5301 		sc->flags &= ~FW_OK;
5302 	}
5303 	free(card_fw, M_CXGBE);
5304 	return (rc);
5305 }
5306 
5307 static int
5308 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
5309     uint32_t mtype, uint32_t moff, u_int maxlen)
5310 {
5311 	struct fw_info *fw_info;
5312 	const struct firmware *dcfg, *rcfg = NULL;
5313 	const uint32_t *cfdata;
5314 	uint32_t cflen, addr;
5315 	int rc;
5316 
5317 	load_fw_module(sc, &dcfg, NULL);
5318 
5319 	/* Card specific interpretation of "default". */
5320 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5321 		if (pci_get_device(sc->dev) == 0x440a)
5322 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
5323 		if (is_fpga(sc))
5324 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
5325 	}
5326 
5327 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
5328 		if (dcfg == NULL) {
5329 			device_printf(sc->dev,
5330 			    "KLD with default config is not available.\n");
5331 			rc = ENOENT;
5332 			goto done;
5333 		}
5334 		cfdata = dcfg->data;
5335 		cflen = dcfg->datasize & ~3;
5336 	} else {
5337 		char s[32];
5338 
5339 		fw_info = find_fw_info(chip_id(sc));
5340 		if (fw_info == NULL) {
5341 			device_printf(sc->dev,
5342 			    "unable to look up firmware information for chip %d.\n",
5343 			    chip_id(sc));
5344 			rc = EINVAL;
5345 			goto done;
5346 		}
5347 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
5348 
5349 		rcfg = firmware_get(s);
5350 		if (rcfg == NULL) {
5351 			device_printf(sc->dev,
5352 			    "unable to load module \"%s\" for configuration "
5353 			    "profile \"%s\".\n", s, cfg_file);
5354 			rc = ENOENT;
5355 			goto done;
5356 		}
5357 		cfdata = rcfg->data;
5358 		cflen = rcfg->datasize & ~3;
5359 	}
5360 
5361 	if (cflen > maxlen) {
5362 		device_printf(sc->dev,
5363 		    "config file too long (%d, max allowed is %d).\n",
5364 		    cflen, maxlen);
5365 		rc = EINVAL;
5366 		goto done;
5367 	}
5368 
5369 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
5370 	if (rc != 0) {
5371 		device_printf(sc->dev,
5372 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
5373 		    __func__, mtype, moff, cflen, rc);
5374 		rc = EINVAL;
5375 		goto done;
5376 	}
5377 	write_via_memwin(sc, 2, addr, cfdata, cflen);
5378 done:
5379 	if (rcfg != NULL)
5380 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5381 	unload_fw_module(sc, dcfg, NULL);
5382 	return (rc);
5383 }
5384 
5385 struct caps_allowed {
5386 	uint16_t nbmcaps;
5387 	uint16_t linkcaps;
5388 	uint16_t switchcaps;
5389 	uint16_t nvmecaps;
5390 	uint16_t niccaps;
5391 	uint16_t toecaps;
5392 	uint16_t rdmacaps;
5393 	uint16_t cryptocaps;
5394 	uint16_t iscsicaps;
5395 	uint16_t fcoecaps;
5396 };
5397 
5398 #define FW_PARAM_DEV(param) \
5399 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5400 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5401 #define FW_PARAM_PFVF(param) \
5402 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5403 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5404 
5405 /*
5406  * Provide a configuration profile to the firmware and have it initialize the
5407  * chip accordingly.  This may involve uploading a configuration file to the
5408  * card.
5409  */
5410 static int
5411 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5412     const struct caps_allowed *caps_allowed)
5413 {
5414 	int rc;
5415 	struct fw_caps_config_cmd caps;
5416 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5417 	unsigned int maxlen = 0;
5418 	const int cfg_addr = t4_flash_cfg_addr(sc, &maxlen);
5419 
5420 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5421 	if (rc != 0) {
5422 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5423 		return (rc);
5424 	}
5425 
5426 	bzero(&caps, sizeof(caps));
5427 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5428 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5429 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5430 		mtype = 0;
5431 		moff = 0;
5432 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5433 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5434 		mtype = FW_MEMTYPE_FLASH;
5435 		moff = cfg_addr;
5436 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5437 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5438 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5439 		    FW_LEN16(caps));
5440 	} else {
5441 		/*
5442 		 * Ask the firmware where it wants us to upload the config file.
5443 		 */
5444 		param = FW_PARAM_DEV(CF);
5445 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5446 		if (rc != 0) {
5447 			/* No support for config file?  Shouldn't happen. */
5448 			device_printf(sc->dev,
5449 			    "failed to query config file location: %d.\n", rc);
5450 			goto done;
5451 		}
5452 		mtype = G_FW_PARAMS_PARAM_Y(val);
5453 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5454 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5455 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5456 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5457 		    FW_LEN16(caps));
5458 
5459 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff, maxlen);
5460 		if (rc != 0) {
5461 			device_printf(sc->dev,
5462 			    "failed to upload config file to card: %d.\n", rc);
5463 			goto done;
5464 		}
5465 	}
5466 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5467 	if (rc != 0) {
5468 		device_printf(sc->dev, "failed to pre-process config file: %d "
5469 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5470 		goto done;
5471 	}
5472 
5473 	finicsum = be32toh(caps.finicsum);
5474 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5475 	if (finicsum != cfcsum) {
5476 		device_printf(sc->dev,
5477 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5478 		    finicsum, cfcsum);
5479 	}
5480 	sc->cfcsum = cfcsum;
5481 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5482 
5483 	/*
5484 	 * Let the firmware know what features will (not) be used so it can tune
5485 	 * things accordingly.
5486 	 */
5487 #define LIMIT_CAPS(x) do { \
5488 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5489 } while (0)
5490 	LIMIT_CAPS(nbm);
5491 	LIMIT_CAPS(link);
5492 	LIMIT_CAPS(switch);
5493 	LIMIT_CAPS(nvme);
5494 	LIMIT_CAPS(nic);
5495 	LIMIT_CAPS(toe);
5496 	LIMIT_CAPS(rdma);
5497 	LIMIT_CAPS(crypto);
5498 	LIMIT_CAPS(iscsi);
5499 	LIMIT_CAPS(fcoe);
5500 #undef LIMIT_CAPS
5501 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5502 		/*
5503 		 * TOE and hashfilters are mutually exclusive.  It is a config
5504 		 * file or firmware bug if both are reported as available.  Try
5505 		 * to cope with the situation in non-debug builds by disabling
5506 		 * TOE.
5507 		 */
5508 		MPASS(caps.toecaps == 0);
5509 
5510 		caps.toecaps = 0;
5511 		caps.rdmacaps = 0;
5512 		caps.iscsicaps = 0;
5513 		caps.nvmecaps = 0;
5514 	}
5515 
5516 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5517 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5518 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5519 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5520 	if (rc != 0) {
5521 		device_printf(sc->dev,
5522 		    "failed to process config file: %d.\n", rc);
5523 		goto done;
5524 	}
5525 
5526 	t4_tweak_chip_settings(sc);
5527 	set_params__pre_init(sc);
5528 
5529 	/* get basic stuff going */
5530 	rc = -t4_fw_initialize(sc, sc->mbox);
5531 	if (rc != 0) {
5532 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5533 		goto done;
5534 	}
5535 done:
5536 	return (rc);
5537 }
5538 
5539 /*
5540  * Partition chip resources for use between various PFs, VFs, etc.
5541  */
5542 static int
5543 partition_resources(struct adapter *sc)
5544 {
5545 	char cfg_file[sizeof(t4_cfg_file)];
5546 	struct caps_allowed caps_allowed;
5547 	int rc;
5548 	bool fallback;
5549 
5550 	/* Only the master driver gets to configure the chip resources. */
5551 	MPASS(sc->flags & MASTER_PF);
5552 
5553 #define COPY_CAPS(x) do { \
5554 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5555 } while (0)
5556 	bzero(&caps_allowed, sizeof(caps_allowed));
5557 	COPY_CAPS(nbm);
5558 	COPY_CAPS(link);
5559 	COPY_CAPS(switch);
5560 	COPY_CAPS(nvme);
5561 	COPY_CAPS(nic);
5562 	COPY_CAPS(toe);
5563 	COPY_CAPS(rdma);
5564 	COPY_CAPS(crypto);
5565 	COPY_CAPS(iscsi);
5566 	COPY_CAPS(fcoe);
5567 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5568 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5569 retry:
5570 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5571 	if (rc != 0 && fallback) {
5572 		dump_devlog(sc);
5573 		device_printf(sc->dev,
5574 		    "failed (%d) to configure card with \"%s\" profile, "
5575 		    "will fall back to a basic configuration and retry.\n",
5576 		    rc, cfg_file);
5577 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5578 		bzero(&caps_allowed, sizeof(caps_allowed));
5579 		COPY_CAPS(switch);
5580 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5581 		fallback = false;
5582 		goto retry;
5583 	}
5584 #undef COPY_CAPS
5585 	return (rc);
5586 }
5587 
5588 /*
5589  * Retrieve parameters that are needed (or nice to have) very early.
5590  */
5591 static int
5592 get_params__pre_init(struct adapter *sc)
5593 {
5594 	int rc;
5595 	uint32_t param[2], val[2];
5596 
5597 	t4_get_version_info(sc);
5598 
5599 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5600 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5601 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5602 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5603 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5604 
5605 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5606 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5607 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5608 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5609 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5610 
5611 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5612 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5613 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5614 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5615 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5616 
5617 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5618 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5619 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5620 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5621 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5622 
5623 	param[0] = FW_PARAM_DEV(PORTVEC);
5624 	param[1] = FW_PARAM_DEV(CCLK);
5625 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5626 	if (rc != 0) {
5627 		device_printf(sc->dev,
5628 		    "failed to query parameters (pre_init): %d.\n", rc);
5629 		return (rc);
5630 	}
5631 
5632 	sc->params.portvec = val[0];
5633 	sc->params.nports = bitcount32(val[0]);
5634 	sc->params.vpd.cclk = val[1];
5635 
5636 	/* Read device log parameters. */
5637 	rc = -t4_init_devlog_ncores_params(sc, 1);
5638 	if (rc == 0)
5639 		fixup_devlog_ncores_params(sc);
5640 	else {
5641 		device_printf(sc->dev,
5642 		    "failed to get devlog parameters: %d.\n", rc);
5643 		rc = 0;	/* devlog isn't critical for device operation */
5644 	}
5645 
5646 	return (rc);
5647 }
5648 
5649 /*
5650  * Any params that need to be set before FW_INITIALIZE.
5651  */
5652 static int
5653 set_params__pre_init(struct adapter *sc)
5654 {
5655 	int rc = 0;
5656 	uint32_t param, val;
5657 
5658 	if (chip_id(sc) >= CHELSIO_T6) {
5659 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5660 		val = 1;
5661 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5662 		/* firmwares < 1.20.1.0 do not have this param. */
5663 		if (rc == FW_EINVAL &&
5664 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5665 			rc = 0;
5666 		}
5667 		if (rc != 0) {
5668 			device_printf(sc->dev,
5669 			    "failed to enable high priority filters :%d.\n",
5670 			    rc);
5671 		}
5672 
5673 		param = FW_PARAM_DEV(PPOD_EDRAM);
5674 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5675 		if (rc == 0 && val == 1) {
5676 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5677 			    &val);
5678 			if (rc != 0) {
5679 				device_printf(sc->dev,
5680 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5681 			}
5682 		}
5683 	}
5684 
5685 	/* Enable opaque VIIDs with firmwares that support it. */
5686 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5687 	val = 1;
5688 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5689 	if (rc == 0 && val == 1)
5690 		sc->params.viid_smt_extn_support = true;
5691 	else
5692 		sc->params.viid_smt_extn_support = false;
5693 
5694 	return (rc);
5695 }
5696 
5697 /*
5698  * Retrieve various parameters that are of interest to the driver.  The device
5699  * has been initialized by the firmware at this point.
5700  */
5701 static int
5702 get_params__post_init(struct adapter *sc)
5703 {
5704 	int rc;
5705 	uint32_t param[7], val[7];
5706 	struct fw_caps_config_cmd caps;
5707 
5708 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5709 	param[1] = FW_PARAM_PFVF(EQ_START);
5710 	param[2] = FW_PARAM_PFVF(FILTER_START);
5711 	param[3] = FW_PARAM_PFVF(FILTER_END);
5712 	param[4] = FW_PARAM_PFVF(L2T_START);
5713 	param[5] = FW_PARAM_PFVF(L2T_END);
5714 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5715 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5716 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5717 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5718 	if (rc != 0) {
5719 		device_printf(sc->dev,
5720 		    "failed to query parameters (post_init): %d.\n", rc);
5721 		return (rc);
5722 	}
5723 
5724 	sc->sge.iq_start = val[0];
5725 	sc->sge.eq_start = val[1];
5726 	if ((int)val[3] > (int)val[2]) {
5727 		sc->tids.ftid_base = val[2];
5728 		sc->tids.ftid_end = val[3];
5729 		sc->tids.nftids = val[3] - val[2] + 1;
5730 	}
5731 	sc->vres.l2t.start = val[4];
5732 	sc->vres.l2t.size = val[5] - val[4] + 1;
5733 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5734 	if (sc->vres.l2t.size > 0)
5735 		MPASS(fls(val[5]) <= S_SYNC_WR);
5736 	sc->params.core_vdd = val[6];
5737 
5738 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5739 	param[1] = FW_PARAM_PFVF(EQ_END);
5740 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5741 	if (rc != 0) {
5742 		device_printf(sc->dev,
5743 		    "failed to query parameters (post_init2): %d.\n", rc);
5744 		return (rc);
5745 	}
5746 	MPASS((int)val[0] >= sc->sge.iq_start);
5747 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5748 	MPASS((int)val[1] >= sc->sge.eq_start);
5749 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5750 
5751 	if (chip_id(sc) >= CHELSIO_T6) {
5752 
5753 		sc->tids.tid_base = t4_read_reg(sc,
5754 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5755 
5756 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5757 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5758 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5759 		if (rc != 0) {
5760 			device_printf(sc->dev,
5761 			   "failed to query hpfilter parameters: %d.\n", rc);
5762 			return (rc);
5763 		}
5764 		if ((int)val[1] > (int)val[0]) {
5765 			sc->tids.hpftid_base = val[0];
5766 			sc->tids.hpftid_end = val[1];
5767 			sc->tids.nhpftids = val[1] - val[0] + 1;
5768 
5769 			/*
5770 			 * These should go off if the layout changes and the
5771 			 * driver needs to catch up.
5772 			 */
5773 			MPASS(sc->tids.hpftid_base == 0);
5774 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5775 		}
5776 
5777 		param[0] = FW_PARAM_PFVF(RAWF_START);
5778 		param[1] = FW_PARAM_PFVF(RAWF_END);
5779 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5780 		if (rc != 0) {
5781 			device_printf(sc->dev,
5782 			   "failed to query rawf parameters: %d.\n", rc);
5783 			return (rc);
5784 		}
5785 		if ((int)val[1] > (int)val[0]) {
5786 			sc->rawf_base = val[0];
5787 			sc->nrawf = val[1] - val[0] + 1;
5788 		}
5789 	}
5790 
5791 	if (sc->params.ncores > 1) {
5792 		param[0] = FW_PARAM_DEV(TID_QID_SEL_MASK);
5793 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5794 		sc->params.tid_qid_sel_mask = rc == 0 ? val[0] : 0;
5795 	}
5796 
5797 	/*
5798 	 * The parameters that follow may not be available on all firmwares.  We
5799 	 * query them individually rather than in a compound query because old
5800 	 * firmwares fail the entire query if an unknown parameter is queried.
5801 	 */
5802 
5803 	/*
5804 	 * MPS buffer group configuration.
5805 	 */
5806 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5807 	val[0] = 0;
5808 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5809 	if (rc == 0)
5810 		sc->params.mps_bg_map = val[0];
5811 	else
5812 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5813 
5814 	param[0] = FW_PARAM_DEV(TPCHMAP);
5815 	val[0] = 0;
5816 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5817 	if (rc == 0)
5818 		sc->params.tp_ch_map = val[0];
5819 	else
5820 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5821 
5822 	param[0] = FW_PARAM_DEV(TX_TPCHMAP);
5823 	val[0] = 0;
5824 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5825 	if (rc == 0)
5826 		sc->params.tx_tp_ch_map = val[0];
5827 	else
5828 		sc->params.tx_tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5829 
5830 	/*
5831 	 * Determine whether the firmware supports the filter2 work request.
5832 	 */
5833 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5834 	val[0] = 0;
5835 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5836 	if (rc == 0)
5837 		sc->params.filter2_wr_support = val[0] != 0;
5838 	else
5839 		sc->params.filter2_wr_support = 0;
5840 
5841 	/*
5842 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5843 	 */
5844 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5845 	val[0] = 0;
5846 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5847 	if (rc == 0)
5848 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5849 	else
5850 		sc->params.ulptx_memwrite_dsgl = false;
5851 
5852 	/* FW_RI_FR_NSMR_TPTE_WR support */
5853 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5854 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5855 	if (rc == 0)
5856 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5857 	else
5858 		sc->params.fr_nsmr_tpte_wr_support = false;
5859 
5860 	/* Support for 512 SGL entries per FR MR. */
5861 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5862 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5863 	if (rc == 0)
5864 		sc->params.dev_512sgl_mr = val[0] != 0;
5865 	else
5866 		sc->params.dev_512sgl_mr = false;
5867 
5868 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5869 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5870 	if (rc == 0)
5871 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5872 	else
5873 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5874 
5875 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5876 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5877 	if (rc == 0) {
5878 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5879 		sc->params.nsched_cls = val[0];
5880 	} else
5881 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5882 
5883 	/* get capabilites */
5884 	bzero(&caps, sizeof(caps));
5885 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5886 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5887 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5888 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5889 	if (rc != 0) {
5890 		device_printf(sc->dev,
5891 		    "failed to get card capabilities: %d.\n", rc);
5892 		return (rc);
5893 	}
5894 
5895 #define READ_CAPS(x) do { \
5896 	sc->x = htobe16(caps.x); \
5897 } while (0)
5898 	READ_CAPS(nbmcaps);
5899 	READ_CAPS(linkcaps);
5900 	READ_CAPS(switchcaps);
5901 	READ_CAPS(nvmecaps);
5902 	READ_CAPS(niccaps);
5903 	READ_CAPS(toecaps);
5904 	READ_CAPS(rdmacaps);
5905 	READ_CAPS(cryptocaps);
5906 	READ_CAPS(iscsicaps);
5907 	READ_CAPS(fcoecaps);
5908 
5909 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5910 		MPASS(chip_id(sc) > CHELSIO_T4);
5911 		MPASS(sc->toecaps == 0);
5912 		sc->toecaps = 0;
5913 
5914 		param[0] = FW_PARAM_DEV(NTID);
5915 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5916 		if (rc != 0) {
5917 			device_printf(sc->dev,
5918 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5919 			return (rc);
5920 		}
5921 		sc->tids.ntids = val[0];
5922 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5923 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5924 			sc->tids.ntids -= sc->tids.nhpftids;
5925 		}
5926 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5927 		sc->params.hash_filter = 1;
5928 	}
5929 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5930 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5931 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5932 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5933 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5934 		if (rc != 0) {
5935 			device_printf(sc->dev,
5936 			    "failed to query NIC parameters: %d.\n", rc);
5937 			return (rc);
5938 		}
5939 		if ((int)val[1] > (int)val[0]) {
5940 			sc->tids.etid_base = val[0];
5941 			sc->tids.etid_end = val[1];
5942 			sc->tids.netids = val[1] - val[0] + 1;
5943 			sc->params.eo_wr_cred = val[2];
5944 			sc->params.ethoffload = 1;
5945 		}
5946 	}
5947 	if (sc->toecaps) {
5948 		/* query offload-related parameters */
5949 		param[0] = FW_PARAM_DEV(NTID);
5950 		param[1] = FW_PARAM_PFVF(SERVER_START);
5951 		param[2] = FW_PARAM_PFVF(SERVER_END);
5952 		param[3] = FW_PARAM_PFVF(TDDP_START);
5953 		param[4] = FW_PARAM_PFVF(TDDP_END);
5954 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5955 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5956 		if (rc != 0) {
5957 			device_printf(sc->dev,
5958 			    "failed to query TOE parameters: %d.\n", rc);
5959 			return (rc);
5960 		}
5961 		sc->tids.ntids = val[0];
5962 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5963 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5964 			sc->tids.ntids -= sc->tids.nhpftids;
5965 		}
5966 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5967 		if ((int)val[2] > (int)val[1]) {
5968 			sc->tids.stid_base = val[1];
5969 			sc->tids.nstids = val[2] - val[1] + 1;
5970 		}
5971 		sc->vres.ddp.start = val[3];
5972 		sc->vres.ddp.size = val[4] - val[3] + 1;
5973 		sc->params.ofldq_wr_cred = val[5];
5974 		sc->params.offload = 1;
5975 	} else {
5976 		/*
5977 		 * The firmware attempts memfree TOE configuration for -SO cards
5978 		 * and will report toecaps=0 if it runs out of resources (this
5979 		 * depends on the config file).  It may not report 0 for other
5980 		 * capabilities dependent on the TOE in this case.  Set them to
5981 		 * 0 here so that the driver doesn't bother tracking resources
5982 		 * that will never be used.
5983 		 */
5984 		sc->iscsicaps = 0;
5985 		sc->nvmecaps = 0;
5986 		sc->rdmacaps = 0;
5987 	}
5988 	if (sc->nvmecaps || sc->rdmacaps) {
5989 		param[0] = FW_PARAM_PFVF(STAG_START);
5990 		param[1] = FW_PARAM_PFVF(STAG_END);
5991 		param[2] = FW_PARAM_PFVF(PBL_START);
5992 		param[3] = FW_PARAM_PFVF(PBL_END);
5993 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5994 		if (rc != 0) {
5995 			device_printf(sc->dev,
5996 			    "failed to query NVMe/RDMA parameters: %d.\n", rc);
5997 			return (rc);
5998 		}
5999 		sc->vres.stag.start = val[0];
6000 		sc->vres.stag.size = val[1] - val[0] + 1;
6001 		sc->vres.pbl.start = val[2];
6002 		sc->vres.pbl.size = val[3] - val[2] + 1;
6003 	}
6004 	if (sc->rdmacaps) {
6005 		param[0] = FW_PARAM_PFVF(RQ_START);
6006 		param[1] = FW_PARAM_PFVF(RQ_END);
6007 		param[2] = FW_PARAM_PFVF(SQRQ_START);
6008 		param[3] = FW_PARAM_PFVF(SQRQ_END);
6009 		param[4] = FW_PARAM_PFVF(CQ_START);
6010 		param[5] = FW_PARAM_PFVF(CQ_END);
6011 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
6012 		if (rc != 0) {
6013 			device_printf(sc->dev,
6014 			    "failed to query RDMA parameters(1): %d.\n", rc);
6015 			return (rc);
6016 		}
6017 		sc->vres.rq.start = val[0];
6018 		sc->vres.rq.size = val[1] - val[0] + 1;
6019 		sc->vres.qp.start = val[2];
6020 		sc->vres.qp.size = val[3] - val[2] + 1;
6021 		sc->vres.cq.start = val[4];
6022 		sc->vres.cq.size = val[5] - val[4] + 1;
6023 
6024 		param[0] = FW_PARAM_PFVF(OCQ_START);
6025 		param[1] = FW_PARAM_PFVF(OCQ_END);
6026 		param[2] = FW_PARAM_PFVF(SRQ_START);
6027 		param[3] = FW_PARAM_PFVF(SRQ_END);
6028 		param[4] = FW_PARAM_DEV(MAXORDIRD_QP);
6029 		param[5] = FW_PARAM_DEV(MAXIRD_ADAPTER);
6030 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
6031 		if (rc != 0) {
6032 			device_printf(sc->dev,
6033 			    "failed to query RDMA parameters(2): %d.\n", rc);
6034 			return (rc);
6035 		}
6036 		sc->vres.ocq.start = val[0];
6037 		sc->vres.ocq.size = val[1] - val[0] + 1;
6038 		sc->vres.srq.start = val[2];
6039 		sc->vres.srq.size = val[3] - val[2] + 1;
6040 		sc->params.max_ordird_qp = val[4];
6041 		sc->params.max_ird_adapter = val[5];
6042 
6043 		param[0] = FW_PARAM_DEV(RDMA_WRITE_WITH_IMM);
6044 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6045 		if (rc == 0 && val[0] != 0)
6046 			sc->params.write_w_imm_support = true;
6047 
6048 		param[0] = FW_PARAM_DEV(RI_WRITE_CMPL_WR);
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_cmpl_support = true;
6052 	}
6053 	if (sc->iscsicaps) {
6054 		param[0] = FW_PARAM_PFVF(ISCSI_START);
6055 		param[1] = FW_PARAM_PFVF(ISCSI_END);
6056 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6057 		if (rc != 0) {
6058 			device_printf(sc->dev,
6059 			    "failed to query iSCSI parameters: %d.\n", rc);
6060 			return (rc);
6061 		}
6062 		sc->vres.iscsi.start = val[0];
6063 		sc->vres.iscsi.size = val[1] - val[0] + 1;
6064 	}
6065 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
6066 		param[0] = FW_PARAM_PFVF(TLS_START);
6067 		param[1] = FW_PARAM_PFVF(TLS_END);
6068 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6069 		if (rc != 0) {
6070 			device_printf(sc->dev,
6071 			    "failed to query TLS parameters: %d.\n", rc);
6072 			return (rc);
6073 		}
6074 		sc->vres.key.start = val[0];
6075 		sc->vres.key.size = val[1] - val[0] + 1;
6076 	}
6077 	if (sc->cryptocaps & FW_CAPS_CONFIG_IPSEC_INLINE) {
6078 		param[0] = FW_PARAM_PFVF(NIPSEC_TUNNEL);
6079 		param[1] = FW_PARAM_PFVF(NIPSEC_TRANSPORT);
6080 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
6081 		if (rc == 0) {
6082 			sc->params.nipsec_tunnel = val[0];
6083 			sc->params.nipsec_transport = val[1];
6084 		} else {
6085 			CH_ERR(sc, "failed to query IPsec params: %d.\n", rc);
6086 			MPASS(sc->params.nipsec_tunnel == 0);
6087 			MPASS(sc->params.nipsec_transport == 0);
6088 		}
6089 	}
6090 	if (sc->cryptocaps & FW_CAPS_CONFIG_OFLD_OVER_IPSEC_INLINE) {
6091 		param[0] = FW_PARAM_PFVF(OFLD_NIPSEC_TUNNEL);
6092 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
6093 		if (rc == 0) {
6094 			sc->params.nofld_ipsec_tunnel = val[0];
6095 		} else {
6096 			CH_ERR(sc, "failed to query TOE IPsec params: %d.\n", rc);
6097 			MPASS(sc->params.nofld_ipsec_tunnel == 0);
6098 		}
6099 	}
6100 	/*
6101 	 * We've got the params we wanted to query directly from the firmware.
6102 	 * Grab some others via other means.
6103 	 */
6104 	t4_init_sge_params(sc);
6105 	t4_init_tp_params(sc);
6106 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
6107 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
6108 
6109 	rc = t4_verify_chip_settings(sc);
6110 	if (rc != 0)
6111 		return (rc);
6112 	t4_init_rx_buf_info(sc);
6113 
6114 	return (rc);
6115 }
6116 
6117 #ifdef KERN_TLS
6118 static void
6119 ktls_tick(void *arg)
6120 {
6121 	struct adapter *sc;
6122 	uint32_t tstamp;
6123 
6124 	sc = arg;
6125 	tstamp = tcp_ts_getticks();
6126 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
6127 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
6128 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
6129 }
6130 
6131 static int
6132 t6_config_kern_tls(struct adapter *sc, bool enable)
6133 {
6134 	int rc;
6135 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6136 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
6137 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
6138 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
6139 
6140 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
6141 	if (rc != 0) {
6142 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
6143 		    enable ?  "enable" : "disable", rc);
6144 		return (rc);
6145 	}
6146 
6147 	if (enable) {
6148 		sc->flags |= KERN_TLS_ON;
6149 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
6150 		    C_HARDCLOCK);
6151 	} else {
6152 		sc->flags &= ~KERN_TLS_ON;
6153 		callout_stop(&sc->ktls_tick);
6154 	}
6155 
6156 	return (rc);
6157 }
6158 #endif
6159 
6160 static int
6161 set_params__post_init(struct adapter *sc)
6162 {
6163 	uint32_t mask, param, val;
6164 #ifdef TCP_OFFLOAD
6165 	int i, v, shift;
6166 #endif
6167 
6168 	/* ask for encapsulated CPLs */
6169 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
6170 	val = 1;
6171 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6172 
6173 	/* Enable 32b port caps if the firmware supports it. */
6174 	param = FW_PARAM_PFVF(PORT_CAPS32);
6175 	val = 1;
6176 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
6177 		sc->params.port_caps32 = 1;
6178 
6179 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
6180 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
6181 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
6182 	    V_MASKFILTER(val - 1));
6183 
6184 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
6185 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
6186 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6187 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
6188 	val = 0;
6189 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
6190 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
6191 		    F_ATTACKFILTERENABLE);
6192 		val |= F_DROPERRORATTACK;
6193 	}
6194 	if (t4_drop_ip_fragments != 0) {
6195 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
6196 		    F_FRAGMENTDROP);
6197 		val |= F_DROPERRORFRAG;
6198 	}
6199 	if (t4_drop_pkts_with_l2_errors != 0)
6200 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
6201 	if (t4_drop_pkts_with_l3_errors != 0) {
6202 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
6203 		    F_DROPERRORCSUMIP;
6204 	}
6205 	if (t4_drop_pkts_with_l4_errors != 0) {
6206 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
6207 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
6208 	}
6209 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
6210 
6211 #ifdef TCP_OFFLOAD
6212 	/*
6213 	 * Override the TOE timers with user provided tunables.  This is not the
6214 	 * recommended way to change the timers (the firmware config file is) so
6215 	 * these tunables are not documented.
6216 	 *
6217 	 * All the timer tunables are in microseconds.
6218 	 */
6219 	if (t4_toe_keepalive_idle != 0) {
6220 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
6221 		v &= M_KEEPALIVEIDLE;
6222 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
6223 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
6224 	}
6225 	if (t4_toe_keepalive_interval != 0) {
6226 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
6227 		v &= M_KEEPALIVEINTVL;
6228 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
6229 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
6230 	}
6231 	if (t4_toe_keepalive_count != 0) {
6232 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
6233 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6234 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
6235 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
6236 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
6237 	}
6238 	if (t4_toe_rexmt_min != 0) {
6239 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
6240 		v &= M_RXTMIN;
6241 		t4_set_reg_field(sc, A_TP_RXT_MIN,
6242 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
6243 	}
6244 	if (t4_toe_rexmt_max != 0) {
6245 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
6246 		v &= M_RXTMAX;
6247 		t4_set_reg_field(sc, A_TP_RXT_MAX,
6248 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
6249 	}
6250 	if (t4_toe_rexmt_count != 0) {
6251 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
6252 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
6253 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
6254 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
6255 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
6256 	}
6257 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
6258 		if (t4_toe_rexmt_backoff[i] != -1) {
6259 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
6260 			shift = (i & 3) << 3;
6261 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
6262 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
6263 		}
6264 	}
6265 #endif
6266 
6267 	/*
6268 	 * Limit TOE connections to 2 reassembly "islands".  This is
6269 	 * required to permit migrating TOE connections to either
6270 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
6271 	 */
6272 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
6273 	    V_PASSMODE(2));
6274 
6275 #ifdef KERN_TLS
6276 	if (is_ktls(sc)) {
6277 		sc->tlst.inline_keys = t4_tls_inline_keys;
6278 		if (t4_kern_tls != 0 && is_t6(sc)) {
6279 			sc->tlst.combo_wrs = t4_tls_combo_wrs;
6280 			t6_config_kern_tls(sc, true);
6281 		} else {
6282 			sc->tlst.short_records = t4_tls_short_records;
6283 			sc->tlst.partial_ghash = t4_tls_partial_ghash;
6284 		}
6285 	}
6286 #endif
6287 	return (0);
6288 }
6289 
6290 #undef FW_PARAM_PFVF
6291 #undef FW_PARAM_DEV
6292 
6293 static void
6294 t4_set_desc(struct adapter *sc)
6295 {
6296 	struct adapter_params *p = &sc->params;
6297 
6298 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
6299 }
6300 
6301 static inline void
6302 ifmedia_add4(struct ifmedia *ifm, int m)
6303 {
6304 
6305 	ifmedia_add(ifm, m, 0, NULL);
6306 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
6307 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
6308 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
6309 }
6310 
6311 /*
6312  * This is the selected media, which is not quite the same as the active media.
6313  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
6314  * and active are not the same, and "media: Ethernet selected" otherwise.
6315  */
6316 static void
6317 set_current_media(struct port_info *pi)
6318 {
6319 	struct link_config *lc;
6320 	struct ifmedia *ifm;
6321 	int mword;
6322 	u_int speed;
6323 
6324 	PORT_LOCK_ASSERT_OWNED(pi);
6325 
6326 	/* Leave current media alone if it's already set to IFM_NONE. */
6327 	ifm = &pi->media;
6328 	if (ifm->ifm_cur != NULL &&
6329 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
6330 		return;
6331 
6332 	lc = &pi->link_cfg;
6333 	if (lc->requested_aneg != AUTONEG_DISABLE &&
6334 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
6335 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
6336 		return;
6337 	}
6338 	mword = IFM_ETHER | IFM_FDX;
6339 	if (lc->requested_fc & PAUSE_TX)
6340 		mword |= IFM_ETH_TXPAUSE;
6341 	if (lc->requested_fc & PAUSE_RX)
6342 		mword |= IFM_ETH_RXPAUSE;
6343 	if (lc->requested_speed == 0)
6344 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
6345 	else
6346 		speed = lc->requested_speed;
6347 	mword |= port_mword(pi, speed_to_fwcap(speed));
6348 	ifmedia_set(ifm, mword);
6349 }
6350 
6351 /*
6352  * Returns true if the ifmedia list for the port cannot change.
6353  */
6354 static bool
6355 fixed_ifmedia(struct port_info *pi)
6356 {
6357 
6358 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
6359 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
6360 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
6361 	    pi->port_type == FW_PORT_TYPE_KX4 ||
6362 	    pi->port_type == FW_PORT_TYPE_KX ||
6363 	    pi->port_type == FW_PORT_TYPE_KR ||
6364 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
6365 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
6366 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
6367 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
6368 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
6369 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
6370 }
6371 
6372 static void
6373 build_medialist(struct port_info *pi)
6374 {
6375 	uint32_t ss, speed;
6376 	int unknown, mword, bit;
6377 	struct link_config *lc;
6378 	struct ifmedia *ifm;
6379 
6380 	PORT_LOCK_ASSERT_OWNED(pi);
6381 
6382 	if (pi->flags & FIXED_IFMEDIA)
6383 		return;
6384 
6385 	/*
6386 	 * Rebuild the ifmedia list.
6387 	 */
6388 	ifm = &pi->media;
6389 	ifmedia_removeall(ifm);
6390 	lc = &pi->link_cfg;
6391 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
6392 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
6393 		MPASS(ss != 0);
6394 no_media:
6395 		MPASS(LIST_EMPTY(&ifm->ifm_list));
6396 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
6397 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
6398 		return;
6399 	}
6400 
6401 	unknown = 0;
6402 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
6403 		speed = 1 << bit;
6404 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
6405 		if (ss & speed) {
6406 			mword = port_mword(pi, speed);
6407 			if (mword == IFM_NONE) {
6408 				goto no_media;
6409 			} else if (mword == IFM_UNKNOWN)
6410 				unknown++;
6411 			else
6412 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
6413 		}
6414 	}
6415 	if (unknown > 0) /* Add one unknown for all unknown media types. */
6416 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
6417 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
6418 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
6419 
6420 	set_current_media(pi);
6421 }
6422 
6423 /*
6424  * Initialize the requested fields in the link config based on driver tunables.
6425  */
6426 static void
6427 init_link_config(struct port_info *pi)
6428 {
6429 	struct link_config *lc = &pi->link_cfg;
6430 
6431 	PORT_LOCK_ASSERT_OWNED(pi);
6432 
6433 	lc->requested_caps = 0;
6434 	lc->requested_speed = 0;
6435 
6436 	if (t4_autoneg == 0)
6437 		lc->requested_aneg = AUTONEG_DISABLE;
6438 	else if (t4_autoneg == 1)
6439 		lc->requested_aneg = AUTONEG_ENABLE;
6440 	else
6441 		lc->requested_aneg = AUTONEG_AUTO;
6442 
6443 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6444 	    PAUSE_AUTONEG);
6445 
6446 	if (t4_fec & FEC_AUTO)
6447 		lc->requested_fec = FEC_AUTO;
6448 	else if (t4_fec == 0)
6449 		lc->requested_fec = FEC_NONE;
6450 	else {
6451 		/* -1 is handled by the FEC_AUTO block above and not here. */
6452 		lc->requested_fec = t4_fec &
6453 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6454 		if (lc->requested_fec == 0)
6455 			lc->requested_fec = FEC_AUTO;
6456 	}
6457 	if (t4_force_fec < 0)
6458 		lc->force_fec = -1;
6459 	else if (t4_force_fec > 0)
6460 		lc->force_fec = 1;
6461 	else
6462 		lc->force_fec = 0;
6463 }
6464 
6465 /*
6466  * Makes sure that all requested settings comply with what's supported by the
6467  * port.  Returns the number of settings that were invalid and had to be fixed.
6468  */
6469 static int
6470 fixup_link_config(struct port_info *pi)
6471 {
6472 	int n = 0;
6473 	struct link_config *lc = &pi->link_cfg;
6474 	uint32_t fwspeed;
6475 
6476 	PORT_LOCK_ASSERT_OWNED(pi);
6477 
6478 	/* Speed (when not autonegotiating) */
6479 	if (lc->requested_speed != 0) {
6480 		fwspeed = speed_to_fwcap(lc->requested_speed);
6481 		if ((fwspeed & lc->pcaps) == 0) {
6482 			n++;
6483 			lc->requested_speed = 0;
6484 		}
6485 	}
6486 
6487 	/* Link autonegotiation */
6488 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6489 	    lc->requested_aneg == AUTONEG_DISABLE ||
6490 	    lc->requested_aneg == AUTONEG_AUTO);
6491 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6492 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6493 		n++;
6494 		lc->requested_aneg = AUTONEG_AUTO;
6495 	}
6496 
6497 	/* Flow control */
6498 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6499 	if (lc->requested_fc & PAUSE_TX &&
6500 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6501 		n++;
6502 		lc->requested_fc &= ~PAUSE_TX;
6503 	}
6504 	if (lc->requested_fc & PAUSE_RX &&
6505 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6506 		n++;
6507 		lc->requested_fc &= ~PAUSE_RX;
6508 	}
6509 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6510 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6511 		n++;
6512 		lc->requested_fc |= PAUSE_AUTONEG;
6513 	}
6514 
6515 	/* FEC */
6516 	if ((lc->requested_fec & FEC_RS &&
6517 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6518 	    (lc->requested_fec & FEC_BASER_RS &&
6519 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6520 		n++;
6521 		lc->requested_fec = FEC_AUTO;
6522 	}
6523 
6524 	return (n);
6525 }
6526 
6527 /*
6528  * Apply the requested L1 settings, which are expected to be valid, to the
6529  * hardware.
6530  */
6531 static int
6532 apply_link_config(struct port_info *pi)
6533 {
6534 	struct adapter *sc = pi->adapter;
6535 	struct link_config *lc = &pi->link_cfg;
6536 	int rc;
6537 
6538 #ifdef INVARIANTS
6539 	ASSERT_SYNCHRONIZED_OP(sc);
6540 	PORT_LOCK_ASSERT_OWNED(pi);
6541 
6542 	if (lc->requested_aneg == AUTONEG_ENABLE)
6543 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6544 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6545 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6546 	if (lc->requested_fc & PAUSE_TX)
6547 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6548 	if (lc->requested_fc & PAUSE_RX)
6549 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6550 	if (lc->requested_fec & FEC_RS)
6551 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6552 	if (lc->requested_fec & FEC_BASER_RS)
6553 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6554 #endif
6555 	if (!(sc->flags & IS_VF)) {
6556 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->hw_port, lc);
6557 		if (rc != 0) {
6558 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6559 			return (rc);
6560 		}
6561 	}
6562 
6563 	/*
6564 	 * An L1_CFG will almost always result in a link-change event if the
6565 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6566 	 * the notification is processed.  If the link is down then the actual
6567 	 * settings are meaningless.
6568 	 *
6569 	 * This takes care of the case where a change in the L1 settings may not
6570 	 * result in a notification.
6571 	 */
6572 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6573 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6574 
6575 	return (0);
6576 }
6577 
6578 #define FW_MAC_EXACT_CHUNK	7
6579 struct mcaddr_ctx {
6580 	if_t ifp;
6581 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6582 	uint64_t hash;
6583 	int i;
6584 	int del;
6585 	int rc;
6586 };
6587 
6588 static u_int
6589 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6590 {
6591 	struct mcaddr_ctx *ctx = arg;
6592 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6593 	struct port_info *pi = vi->pi;
6594 	struct adapter *sc = pi->adapter;
6595 
6596 	if (ctx->rc < 0)
6597 		return (0);
6598 
6599 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6600 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6601 	ctx->i++;
6602 
6603 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6604 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6605 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6606 		if (ctx->rc < 0) {
6607 			int j;
6608 
6609 			for (j = 0; j < ctx->i; j++) {
6610 				if_printf(ctx->ifp,
6611 				    "failed to add mc address"
6612 				    " %02x:%02x:%02x:"
6613 				    "%02x:%02x:%02x rc=%d\n",
6614 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6615 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6616 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6617 				    -ctx->rc);
6618 			}
6619 			return (0);
6620 		}
6621 		ctx->del = 0;
6622 		ctx->i = 0;
6623 	}
6624 
6625 	return (1);
6626 }
6627 
6628 /*
6629  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6630  * indicates which parameters should be programmed (the rest are left alone).
6631  */
6632 int
6633 update_mac_settings(if_t ifp, int flags)
6634 {
6635 	int rc = 0;
6636 	struct vi_info *vi = if_getsoftc(ifp);
6637 	struct port_info *pi = vi->pi;
6638 	struct adapter *sc = pi->adapter;
6639 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6640 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6641 
6642 	ASSERT_SYNCHRONIZED_OP(sc);
6643 	KASSERT(flags, ("%s: not told what to update.", __func__));
6644 
6645 	if (flags & XGMAC_MTU)
6646 		mtu = if_getmtu(ifp);
6647 
6648 	if (flags & XGMAC_PROMISC)
6649 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6650 
6651 	if (flags & XGMAC_ALLMULTI)
6652 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6653 
6654 	if (flags & XGMAC_VLANEX)
6655 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6656 
6657 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6658 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6659 		    allmulti, 1, vlanex, false);
6660 		if (rc) {
6661 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6662 			    rc);
6663 			return (rc);
6664 		}
6665 	}
6666 
6667 	if (flags & XGMAC_UCADDR) {
6668 		uint8_t ucaddr[ETHER_ADDR_LEN];
6669 
6670 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6671 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6672 		    ucaddr, true, &vi->smt_idx);
6673 		if (rc < 0) {
6674 			rc = -rc;
6675 			if_printf(ifp, "change_mac failed: %d\n", rc);
6676 			return (rc);
6677 		} else {
6678 			vi->xact_addr_filt = rc;
6679 			rc = 0;
6680 		}
6681 	}
6682 
6683 	if (flags & XGMAC_MCADDRS) {
6684 		struct epoch_tracker et;
6685 		struct mcaddr_ctx ctx;
6686 		int j;
6687 
6688 		ctx.ifp = ifp;
6689 		ctx.hash = 0;
6690 		ctx.i = 0;
6691 		ctx.del = 1;
6692 		ctx.rc = 0;
6693 		/*
6694 		 * Unlike other drivers, we accumulate list of pointers into
6695 		 * interface address lists and we need to keep it safe even
6696 		 * after if_foreach_llmaddr() returns, thus we must enter the
6697 		 * network epoch.
6698 		 */
6699 		NET_EPOCH_ENTER(et);
6700 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6701 		if (ctx.rc < 0) {
6702 			NET_EPOCH_EXIT(et);
6703 			rc = -ctx.rc;
6704 			return (rc);
6705 		}
6706 		if (ctx.i > 0) {
6707 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6708 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6709 			NET_EPOCH_EXIT(et);
6710 			if (rc < 0) {
6711 				rc = -rc;
6712 				for (j = 0; j < ctx.i; j++) {
6713 					if_printf(ifp,
6714 					    "failed to add mcast address"
6715 					    " %02x:%02x:%02x:"
6716 					    "%02x:%02x:%02x rc=%d\n",
6717 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6718 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6719 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6720 					    rc);
6721 				}
6722 				return (rc);
6723 			}
6724 			ctx.del = 0;
6725 		} else
6726 			NET_EPOCH_EXIT(et);
6727 
6728 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6729 		if (rc != 0)
6730 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6731 			    rc);
6732 		if (ctx.del == 0) {
6733 			/* We clobbered the VXLAN entry if there was one. */
6734 			pi->vxlan_tcam_entry = false;
6735 		}
6736 	}
6737 
6738 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6739 	    pi->vxlan_tcam_entry == false) {
6740 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6741 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6742 		    true);
6743 		if (rc < 0) {
6744 			rc = -rc;
6745 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6746 			    rc);
6747 		} else {
6748 			MPASS(rc == sc->rawf_base + pi->port_id);
6749 			rc = 0;
6750 			pi->vxlan_tcam_entry = true;
6751 		}
6752 	}
6753 
6754 	return (rc);
6755 }
6756 
6757 /*
6758  * {begin|end}_synchronized_op must be called from the same thread.
6759  */
6760 int
6761 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6762     char *wmesg)
6763 {
6764 	int rc;
6765 
6766 #ifdef WITNESS
6767 	/* the caller thinks it's ok to sleep, but is it really? */
6768 	if (flags & SLEEP_OK)
6769 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL, __func__);
6770 #endif
6771 	ADAPTER_LOCK(sc);
6772 	for (;;) {
6773 
6774 		if (vi && IS_DETACHING(vi)) {
6775 			rc = ENXIO;
6776 			goto done;
6777 		}
6778 
6779 		if (!IS_BUSY(sc)) {
6780 			rc = 0;
6781 			break;
6782 		}
6783 
6784 		if (!(flags & SLEEP_OK)) {
6785 			rc = EBUSY;
6786 			goto done;
6787 		}
6788 
6789 		if (mtx_sleep(&sc->flags, &sc->sc_lock,
6790 		    flags & INTR_OK ? PCATCH : 0, wmesg, 0)) {
6791 			rc = EINTR;
6792 			goto done;
6793 		}
6794 	}
6795 
6796 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6797 	SET_BUSY(sc);
6798 #ifdef INVARIANTS
6799 	sc->last_op = wmesg;
6800 	sc->last_op_thr = curthread;
6801 	sc->last_op_flags = flags;
6802 #endif
6803 
6804 done:
6805 	if (!(flags & HOLD_LOCK) || rc)
6806 		ADAPTER_UNLOCK(sc);
6807 
6808 	return (rc);
6809 }
6810 
6811 /*
6812  * Tell if_ioctl and if_init that the VI is going away.  This is
6813  * special variant of begin_synchronized_op and must be paired with a
6814  * call to end_vi_detach.
6815  */
6816 void
6817 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6818 {
6819 	ADAPTER_LOCK(sc);
6820 	SET_DETACHING(vi);
6821 	wakeup(&sc->flags);
6822 	while (IS_BUSY(sc))
6823 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6824 	SET_BUSY(sc);
6825 #ifdef INVARIANTS
6826 	sc->last_op = "t4detach";
6827 	sc->last_op_thr = curthread;
6828 	sc->last_op_flags = 0;
6829 #endif
6830 	ADAPTER_UNLOCK(sc);
6831 }
6832 
6833 void
6834 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6835 {
6836 	ADAPTER_LOCK(sc);
6837 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6838 	CLR_BUSY(sc);
6839 	CLR_DETACHING(vi);
6840 	wakeup(&sc->flags);
6841 	ADAPTER_UNLOCK(sc);
6842 }
6843 
6844 /*
6845  * {begin|end}_synchronized_op must be called from the same thread.
6846  */
6847 void
6848 end_synchronized_op(struct adapter *sc, int flags)
6849 {
6850 
6851 	if (flags & LOCK_HELD)
6852 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6853 	else
6854 		ADAPTER_LOCK(sc);
6855 
6856 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6857 	CLR_BUSY(sc);
6858 	wakeup(&sc->flags);
6859 	ADAPTER_UNLOCK(sc);
6860 }
6861 
6862 static int
6863 cxgbe_init_synchronized(struct vi_info *vi)
6864 {
6865 	struct port_info *pi = vi->pi;
6866 	struct adapter *sc = pi->adapter;
6867 	if_t ifp = vi->ifp;
6868 	int rc = 0, i;
6869 	struct sge_txq *txq;
6870 
6871 	ASSERT_SYNCHRONIZED_OP(sc);
6872 
6873 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6874 		return (0);	/* already running */
6875 
6876 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6877 		return (rc);	/* error message displayed already */
6878 
6879 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6880 		return (rc); /* error message displayed already */
6881 
6882 	rc = update_mac_settings(ifp, XGMAC_ALL);
6883 	if (rc)
6884 		goto done;	/* error message displayed already */
6885 
6886 	PORT_LOCK(pi);
6887 	if (pi->up_vis == 0) {
6888 		t4_update_port_info(pi);
6889 		fixup_link_config(pi);
6890 		build_medialist(pi);
6891 		apply_link_config(pi);
6892 	}
6893 
6894 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6895 	if (rc != 0) {
6896 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6897 		PORT_UNLOCK(pi);
6898 		goto done;
6899 	}
6900 
6901 	/*
6902 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6903 	 * if this changes.
6904 	 */
6905 
6906 	for_each_txq(vi, i, txq) {
6907 		TXQ_LOCK(txq);
6908 		txq->eq.flags |= EQ_ENABLED;
6909 		TXQ_UNLOCK(txq);
6910 	}
6911 
6912 	/*
6913 	 * The first iq of the first port to come up is used for tracing.
6914 	 */
6915 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6916 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6917 		t4_set_trace_rss_control(sc, pi->tx_chan, sc->traceq);
6918 		pi->flags |= HAS_TRACEQ;
6919 	}
6920 
6921 	/* all ok */
6922 	pi->up_vis++;
6923 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6924 	if (pi->link_cfg.link_ok)
6925 		t4_os_link_changed(pi);
6926 	PORT_UNLOCK(pi);
6927 
6928 	mtx_lock(&vi->tick_mtx);
6929 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6930 		callout_reset(&vi->tick, hz, vi_tick, vi);
6931 	else
6932 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6933 	mtx_unlock(&vi->tick_mtx);
6934 done:
6935 	if (rc != 0)
6936 		cxgbe_uninit_synchronized(vi);
6937 
6938 	return (rc);
6939 }
6940 
6941 /*
6942  * Idempotent.
6943  */
6944 static int
6945 cxgbe_uninit_synchronized(struct vi_info *vi)
6946 {
6947 	struct port_info *pi = vi->pi;
6948 	struct adapter *sc = pi->adapter;
6949 	if_t ifp = vi->ifp;
6950 	int rc, i;
6951 	struct sge_txq *txq;
6952 
6953 	ASSERT_SYNCHRONIZED_OP(sc);
6954 
6955 	if (!(vi->flags & VI_INIT_DONE)) {
6956 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6957 			KASSERT(0, ("uninited VI is running"));
6958 			if_printf(ifp, "uninited VI with running ifnet.  "
6959 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6960 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6961 			    if_getdrvflags(ifp));
6962 		}
6963 		return (0);
6964 	}
6965 
6966 	/*
6967 	 * Disable the VI so that all its data in either direction is discarded
6968 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6969 	 * tick) intact as the TP can deliver negative advice or data that it's
6970 	 * holding in its RAM (for an offloaded connection) even after the VI is
6971 	 * disabled.
6972 	 */
6973 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6974 	if (rc) {
6975 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6976 		return (rc);
6977 	}
6978 
6979 	for_each_txq(vi, i, txq) {
6980 		TXQ_LOCK(txq);
6981 		txq->eq.flags &= ~EQ_ENABLED;
6982 		TXQ_UNLOCK(txq);
6983 	}
6984 
6985 	mtx_lock(&vi->tick_mtx);
6986 	callout_stop(&vi->tick);
6987 	mtx_unlock(&vi->tick_mtx);
6988 
6989 	PORT_LOCK(pi);
6990 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6991 		PORT_UNLOCK(pi);
6992 		return (0);
6993 	}
6994 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6995 	pi->up_vis--;
6996 	if (pi->up_vis > 0) {
6997 		PORT_UNLOCK(pi);
6998 		return (0);
6999 	}
7000 
7001 	pi->link_cfg.link_ok = false;
7002 	pi->link_cfg.speed = 0;
7003 	pi->link_cfg.link_down_rc = 255;
7004 	t4_os_link_changed(pi);
7005 	PORT_UNLOCK(pi);
7006 
7007 	return (0);
7008 }
7009 
7010 /*
7011  * It is ok for this function to fail midway and return right away.  t4_detach
7012  * will walk the entire sc->irq list and clean up whatever is valid.
7013  */
7014 int
7015 t4_setup_intr_handlers(struct adapter *sc)
7016 {
7017 	int rc, rid, p, q, v;
7018 	char s[8];
7019 	struct irq *irq;
7020 	struct port_info *pi;
7021 	struct vi_info *vi;
7022 	struct sge *sge = &sc->sge;
7023 	struct sge_rxq *rxq;
7024 #ifdef TCP_OFFLOAD
7025 	struct sge_ofld_rxq *ofld_rxq;
7026 #endif
7027 #ifdef DEV_NETMAP
7028 	struct sge_nm_rxq *nm_rxq;
7029 #endif
7030 #ifdef RSS
7031 	int nbuckets = rss_getnumbuckets();
7032 #endif
7033 
7034 	/*
7035 	 * Setup interrupts.
7036 	 */
7037 	irq = &sc->irq[0];
7038 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
7039 	if (forwarding_intr_to_fwq(sc))
7040 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
7041 
7042 	/* Multiple interrupts. */
7043 	if (sc->flags & IS_VF)
7044 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
7045 		    ("%s: too few intr.", __func__));
7046 	else
7047 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
7048 		    ("%s: too few intr.", __func__));
7049 
7050 	/* The first one is always error intr on PFs */
7051 	if (!(sc->flags & IS_VF)) {
7052 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
7053 		if (rc != 0)
7054 			return (rc);
7055 		irq++;
7056 		rid++;
7057 	}
7058 
7059 	/* The second one is always the firmware event queue (first on VFs) */
7060 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
7061 	if (rc != 0)
7062 		return (rc);
7063 	irq++;
7064 	rid++;
7065 
7066 	for_each_port(sc, p) {
7067 		pi = sc->port[p];
7068 		for_each_vi(pi, v, vi) {
7069 			vi->first_intr = rid - 1;
7070 
7071 			if (vi->nnmrxq > 0) {
7072 				int n = max(vi->nrxq, vi->nnmrxq);
7073 
7074 				rxq = &sge->rxq[vi->first_rxq];
7075 #ifdef DEV_NETMAP
7076 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
7077 #endif
7078 				for (q = 0; q < n; q++) {
7079 					snprintf(s, sizeof(s), "%x%c%x", p,
7080 					    'a' + v, q);
7081 					if (q < vi->nrxq)
7082 						irq->rxq = rxq++;
7083 #ifdef DEV_NETMAP
7084 					if (q < vi->nnmrxq)
7085 						irq->nm_rxq = nm_rxq++;
7086 
7087 					if (irq->nm_rxq != NULL &&
7088 					    irq->rxq == NULL) {
7089 						/* Netmap rx only */
7090 						rc = t4_alloc_irq(sc, irq, rid,
7091 						    t4_nm_intr, irq->nm_rxq, s);
7092 					}
7093 					if (irq->nm_rxq != NULL &&
7094 					    irq->rxq != NULL) {
7095 						/* NIC and Netmap rx */
7096 						rc = t4_alloc_irq(sc, irq, rid,
7097 						    t4_vi_intr, irq, s);
7098 					}
7099 #endif
7100 					if (irq->rxq != NULL &&
7101 					    irq->nm_rxq == NULL) {
7102 						/* NIC rx only */
7103 						rc = t4_alloc_irq(sc, irq, rid,
7104 						    t4_intr, irq->rxq, s);
7105 					}
7106 					if (rc != 0)
7107 						return (rc);
7108 #ifdef RSS
7109 					if (q < vi->nrxq) {
7110 						bus_bind_intr(sc->dev, irq->res,
7111 						    rss_getcpu(q % nbuckets));
7112 					}
7113 #endif
7114 					irq++;
7115 					rid++;
7116 					vi->nintr++;
7117 				}
7118 			} else {
7119 				for_each_rxq(vi, q, rxq) {
7120 					snprintf(s, sizeof(s), "%x%c%x", p,
7121 					    'a' + v, q);
7122 					rc = t4_alloc_irq(sc, irq, rid,
7123 					    t4_intr, rxq, s);
7124 					if (rc != 0)
7125 						return (rc);
7126 #ifdef RSS
7127 					bus_bind_intr(sc->dev, irq->res,
7128 					    rss_getcpu(q % nbuckets));
7129 #endif
7130 					irq++;
7131 					rid++;
7132 					vi->nintr++;
7133 				}
7134 			}
7135 #ifdef TCP_OFFLOAD
7136 			for_each_ofld_rxq(vi, q, ofld_rxq) {
7137 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
7138 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
7139 				    ofld_rxq, s);
7140 				if (rc != 0)
7141 					return (rc);
7142 				irq++;
7143 				rid++;
7144 				vi->nintr++;
7145 			}
7146 #endif
7147 		}
7148 	}
7149 	MPASS(irq == &sc->irq[sc->intr_count]);
7150 
7151 	return (0);
7152 }
7153 
7154 static void
7155 write_global_rss_key(struct adapter *sc)
7156 {
7157 	int i;
7158 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7159 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
7160 
7161 	CTASSERT(RSS_KEYSIZE == 40);
7162 
7163 	rss_getkey((void *)&raw_rss_key[0]);
7164 	for (i = 0; i < nitems(rss_key); i++) {
7165 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
7166 	}
7167 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
7168 }
7169 
7170 /*
7171  * Idempotent.
7172  */
7173 static int
7174 adapter_full_init(struct adapter *sc)
7175 {
7176 	int rc, i;
7177 
7178 	ASSERT_SYNCHRONIZED_OP(sc);
7179 
7180 	/*
7181 	 * queues that belong to the adapter (not any particular port).
7182 	 */
7183 	rc = t4_setup_adapter_queues(sc);
7184 	if (rc != 0)
7185 		return (rc);
7186 
7187 	MPASS(sc->params.nports <= nitems(sc->tq));
7188 	for (i = 0; i < sc->params.nports; i++) {
7189 		if (sc->tq[i] != NULL)
7190 			continue;
7191 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
7192 		    taskqueue_thread_enqueue, &sc->tq[i]);
7193 		if (sc->tq[i] == NULL) {
7194 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
7195 			return (ENOMEM);
7196 		}
7197 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
7198 		    device_get_nameunit(sc->dev), i);
7199 	}
7200 
7201 	if (!(sc->flags & IS_VF)) {
7202 		write_global_rss_key(sc);
7203 		t4_intr_enable(sc);
7204 	}
7205 	return (0);
7206 }
7207 
7208 int
7209 adapter_init(struct adapter *sc)
7210 {
7211 	int rc;
7212 
7213 	ASSERT_SYNCHRONIZED_OP(sc);
7214 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
7215 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
7216 	    ("%s: FULL_INIT_DONE already", __func__));
7217 
7218 	rc = adapter_full_init(sc);
7219 	if (rc != 0)
7220 		adapter_full_uninit(sc);
7221 	else
7222 		sc->flags |= FULL_INIT_DONE;
7223 
7224 	return (rc);
7225 }
7226 
7227 /*
7228  * Idempotent.
7229  */
7230 static void
7231 adapter_full_uninit(struct adapter *sc)
7232 {
7233 	int i;
7234 
7235 	t4_teardown_adapter_queues(sc);
7236 
7237 	for (i = 0; i < nitems(sc->tq); i++) {
7238 		if (sc->tq[i] == NULL)
7239 			continue;
7240 		taskqueue_free(sc->tq[i]);
7241 		sc->tq[i] = NULL;
7242 	}
7243 
7244 	sc->flags &= ~FULL_INIT_DONE;
7245 }
7246 
7247 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
7248     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
7249     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
7250     RSS_HASHTYPE_RSS_UDP_IPV6)
7251 
7252 /* Translates kernel hash types to hardware. */
7253 static int
7254 hashconfig_to_hashen(int hashconfig)
7255 {
7256 	int hashen = 0;
7257 
7258 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
7259 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
7260 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
7261 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
7262 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
7263 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7264 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7265 	}
7266 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
7267 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
7268 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7269 	}
7270 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
7271 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
7272 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
7273 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
7274 
7275 	return (hashen);
7276 }
7277 
7278 /* Translates hardware hash types to kernel. */
7279 static int
7280 hashen_to_hashconfig(int hashen)
7281 {
7282 	int hashconfig = 0;
7283 
7284 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
7285 		/*
7286 		 * If UDP hashing was enabled it must have been enabled for
7287 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
7288 		 * enabling any 4-tuple hash is nonsense configuration.
7289 		 */
7290 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
7291 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
7292 
7293 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7294 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
7295 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7296 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
7297 	}
7298 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
7299 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
7300 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
7301 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
7302 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
7303 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
7304 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
7305 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
7306 
7307 	return (hashconfig);
7308 }
7309 
7310 /*
7311  * Idempotent.
7312  */
7313 static int
7314 vi_full_init(struct vi_info *vi)
7315 {
7316 	struct adapter *sc = vi->adapter;
7317 	struct sge_rxq *rxq;
7318 	int rc, i, j, extra;
7319 	int hashconfig = rss_gethashconfig();
7320 #ifdef RSS
7321 	int nbuckets = rss_getnumbuckets();
7322 #endif
7323 
7324 	ASSERT_SYNCHRONIZED_OP(sc);
7325 
7326 	/*
7327 	 * Allocate tx/rx/fl queues for this VI.
7328 	 */
7329 	rc = t4_setup_vi_queues(vi);
7330 	if (rc != 0)
7331 		return (rc);
7332 
7333 	/*
7334 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
7335 	 */
7336 	if (vi->nrxq > vi->rss_size) {
7337 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
7338 		    "some queues will never receive traffic.\n", vi->nrxq,
7339 		    vi->rss_size);
7340 	} else if (vi->rss_size % vi->nrxq) {
7341 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
7342 		    "expect uneven traffic distribution.\n", vi->nrxq,
7343 		    vi->rss_size);
7344 	}
7345 #ifdef RSS
7346 	if (vi->nrxq != nbuckets) {
7347 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
7348 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
7349 	}
7350 #endif
7351 	if (vi->rss == NULL)
7352 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
7353 		    M_ZERO | M_WAITOK);
7354 	for (i = 0; i < vi->rss_size;) {
7355 #ifdef RSS
7356 		j = rss_get_indirection_to_bucket(i);
7357 		j %= vi->nrxq;
7358 		rxq = &sc->sge.rxq[vi->first_rxq + j];
7359 		vi->rss[i++] = rxq->iq.abs_id;
7360 #else
7361 		for_each_rxq(vi, j, rxq) {
7362 			vi->rss[i++] = rxq->iq.abs_id;
7363 			if (i == vi->rss_size)
7364 				break;
7365 		}
7366 #endif
7367 	}
7368 
7369 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
7370 	    vi->rss, vi->rss_size);
7371 	if (rc != 0) {
7372 		CH_ERR(vi, "rss_config failed: %d\n", rc);
7373 		return (rc);
7374 	}
7375 
7376 	vi->hashen = hashconfig_to_hashen(hashconfig);
7377 
7378 	/*
7379 	 * We may have had to enable some hashes even though the global config
7380 	 * wants them disabled.  This is a potential problem that must be
7381 	 * reported to the user.
7382 	 */
7383 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
7384 
7385 	/*
7386 	 * If we consider only the supported hash types, then the enabled hashes
7387 	 * are a superset of the requested hashes.  In other words, there cannot
7388 	 * be any supported hash that was requested but not enabled, but there
7389 	 * can be hashes that were not requested but had to be enabled.
7390 	 */
7391 	extra &= SUPPORTED_RSS_HASHTYPES;
7392 	MPASS((extra & hashconfig) == 0);
7393 
7394 	if (extra) {
7395 		CH_ALERT(vi,
7396 		    "global RSS config (0x%x) cannot be accommodated.\n",
7397 		    hashconfig);
7398 	}
7399 	if (extra & RSS_HASHTYPE_RSS_IPV4)
7400 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
7401 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
7402 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
7403 	if (extra & RSS_HASHTYPE_RSS_IPV6)
7404 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
7405 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
7406 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
7407 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
7408 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
7409 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
7410 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
7411 
7412 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
7413 	    0, 0);
7414 	if (rc != 0) {
7415 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
7416 		return (rc);
7417 	}
7418 
7419 	return (0);
7420 }
7421 
7422 int
7423 vi_init(struct vi_info *vi)
7424 {
7425 	int rc;
7426 
7427 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7428 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7429 	    ("%s: VI_INIT_DONE already", __func__));
7430 
7431 	rc = vi_full_init(vi);
7432 	if (rc != 0)
7433 		vi_full_uninit(vi);
7434 	else
7435 		vi->flags |= VI_INIT_DONE;
7436 
7437 	return (rc);
7438 }
7439 
7440 /*
7441  * Idempotent.
7442  */
7443 static void
7444 vi_full_uninit(struct vi_info *vi)
7445 {
7446 
7447 	if (vi->flags & VI_INIT_DONE) {
7448 		quiesce_vi(vi);
7449 		free(vi->rss, M_CXGBE);
7450 		free(vi->nm_rss, M_CXGBE);
7451 	}
7452 
7453 	t4_teardown_vi_queues(vi);
7454 	vi->flags &= ~VI_INIT_DONE;
7455 }
7456 
7457 static void
7458 quiesce_txq(struct sge_txq *txq)
7459 {
7460 	struct sge_eq *eq = &txq->eq;
7461 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7462 
7463 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7464 	MPASS(!(eq->flags & EQ_ENABLED));
7465 
7466 	/* Wait for the mp_ring to empty. */
7467 	while (!mp_ring_is_idle(txq->r)) {
7468 		mp_ring_check_drainage(txq->r, 4096);
7469 		pause("rquiesce", 1);
7470 	}
7471 	MPASS(txq->txp.npkt == 0);
7472 
7473 	if (eq->flags & EQ_HW_ALLOCATED) {
7474 		/*
7475 		 * Hardware is alive and working normally.  Wait for it to
7476 		 * finish and then wait for the driver to catch up and reclaim
7477 		 * all descriptors.
7478 		 */
7479 		while (spg->cidx != htobe16(eq->pidx))
7480 			pause("equiesce", 1);
7481 		while (eq->cidx != eq->pidx)
7482 			pause("dquiesce", 1);
7483 	} else {
7484 		/*
7485 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7486 		 * descriptors directly.
7487 		 */
7488 		TXQ_LOCK(txq);
7489 		while (eq->cidx != eq->pidx) {
7490 			struct mbuf *m, *nextpkt;
7491 			struct tx_sdesc *txsd;
7492 
7493 			txsd = &txq->sdesc[eq->cidx];
7494 			for (m = txsd->m; m != NULL; m = nextpkt) {
7495 				nextpkt = m->m_nextpkt;
7496 				m->m_nextpkt = NULL;
7497 				m_freem(m);
7498 			}
7499 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7500 		}
7501 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7502 		TXQ_UNLOCK(txq);
7503 	}
7504 }
7505 
7506 static void
7507 quiesce_wrq(struct sge_wrq *wrq)
7508 {
7509 	struct wrqe *wr;
7510 
7511 	TXQ_LOCK(wrq);
7512 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7513 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7514 #ifdef INVARIANTS
7515 		wrq->nwr_pending--;
7516 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7517 #endif
7518 		free(wr, M_CXGBE);
7519 	}
7520 	MPASS(wrq->nwr_pending == 0);
7521 	MPASS(wrq->ndesc_needed == 0);
7522 	wrq->nwr_pending = 0;
7523 	wrq->ndesc_needed = 0;
7524 	TXQ_UNLOCK(wrq);
7525 }
7526 
7527 static void
7528 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7529 {
7530 	/* Synchronize with the interrupt handler */
7531 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7532 		pause("iqfree", 1);
7533 
7534 	if (fl != NULL) {
7535 		MPASS(iq->flags & IQ_HAS_FL);
7536 
7537 		mtx_lock(&sc->sfl_lock);
7538 		FL_LOCK(fl);
7539 		fl->flags |= FL_DOOMED;
7540 		FL_UNLOCK(fl);
7541 		callout_stop(&sc->sfl_callout);
7542 		mtx_unlock(&sc->sfl_lock);
7543 
7544 		KASSERT((fl->flags & FL_STARVING) == 0,
7545 		    ("%s: still starving", __func__));
7546 
7547 		/* Release all buffers if hardware is no longer available. */
7548 		if (!(iq->flags & IQ_HW_ALLOCATED))
7549 			free_fl_buffers(sc, fl);
7550 	}
7551 }
7552 
7553 /*
7554  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7555  * that no new work is being enqueued by the hardware or the driver.  That part
7556  * should be arranged before calling this function.
7557  */
7558 static void
7559 quiesce_vi(struct vi_info *vi)
7560 {
7561 	int i;
7562 	struct adapter *sc = vi->adapter;
7563 	struct sge_rxq *rxq;
7564 	struct sge_txq *txq;
7565 #ifdef TCP_OFFLOAD
7566 	struct sge_ofld_rxq *ofld_rxq;
7567 #endif
7568 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7569 	struct sge_ofld_txq *ofld_txq;
7570 #endif
7571 
7572 	if (!(vi->flags & VI_INIT_DONE))
7573 		return;
7574 
7575 	for_each_txq(vi, i, txq) {
7576 		quiesce_txq(txq);
7577 	}
7578 
7579 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7580 	for_each_ofld_txq(vi, i, ofld_txq) {
7581 		quiesce_wrq(&ofld_txq->wrq);
7582 	}
7583 #endif
7584 
7585 	for_each_rxq(vi, i, rxq) {
7586 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7587 	}
7588 
7589 #ifdef TCP_OFFLOAD
7590 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7591 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7592 	}
7593 #endif
7594 }
7595 
7596 static int
7597 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7598     driver_intr_t *handler, void *arg, char *name)
7599 {
7600 	int rc;
7601 
7602 	irq->rid = rid;
7603 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7604 	    RF_SHAREABLE | RF_ACTIVE);
7605 	if (irq->res == NULL) {
7606 		device_printf(sc->dev,
7607 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7608 		return (ENOMEM);
7609 	}
7610 
7611 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7612 	    NULL, handler, arg, &irq->tag);
7613 	if (rc != 0) {
7614 		device_printf(sc->dev,
7615 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7616 		    rid, name, rc);
7617 	} else if (name)
7618 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7619 
7620 	return (rc);
7621 }
7622 
7623 static int
7624 t4_free_irq(struct adapter *sc, struct irq *irq)
7625 {
7626 	if (irq->tag)
7627 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7628 	if (irq->res)
7629 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7630 
7631 	bzero(irq, sizeof(*irq));
7632 
7633 	return (0);
7634 }
7635 
7636 static void
7637 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7638 {
7639 
7640 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7641 	t4_get_regs(sc, buf, regs->len);
7642 }
7643 
7644 #define	A_PL_INDIR_CMD	0x1f8
7645 
7646 #define	S_PL_AUTOINC	31
7647 #define	M_PL_AUTOINC	0x1U
7648 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7649 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7650 
7651 #define	S_PL_VFID	20
7652 #define	M_PL_VFID	0xffU
7653 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7654 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7655 
7656 #define	S_PL_ADDR	0
7657 #define	M_PL_ADDR	0xfffffU
7658 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7659 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7660 
7661 #define	A_PL_INDIR_DATA	0x1fc
7662 
7663 static uint64_t
7664 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7665 {
7666 	u32 stats[2];
7667 
7668 	if (sc->flags & IS_VF) {
7669 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7670 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7671 	} else {
7672 		mtx_assert(&sc->reg_lock, MA_OWNED);
7673 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7674 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7675 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7676 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7677 	}
7678 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7679 }
7680 
7681 static void
7682 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7683 {
7684 
7685 #define GET_STAT(name) \
7686 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7687 
7688 	if (!(sc->flags & IS_VF))
7689 		mtx_lock(&sc->reg_lock);
7690 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7691 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7692 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7693 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7694 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7695 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7696 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7697 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7698 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7699 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7700 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7701 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7702 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7703 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7704 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7705 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7706 	if (!(sc->flags & IS_VF))
7707 		mtx_unlock(&sc->reg_lock);
7708 
7709 #undef GET_STAT
7710 }
7711 
7712 static void
7713 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7714 {
7715 	int reg;
7716 
7717 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7718 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7719 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7720 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7721 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7722 }
7723 
7724 static void
7725 vi_refresh_stats(struct vi_info *vi)
7726 {
7727 	struct timeval tv;
7728 	const struct timeval interval = {0, 250000};	/* 250ms */
7729 
7730 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7731 
7732 	if (vi->flags & VI_SKIP_STATS)
7733 		return;
7734 
7735 	getmicrotime(&tv);
7736 	timevalsub(&tv, &interval);
7737 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7738 		return;
7739 
7740 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7741 	getmicrotime(&vi->last_refreshed);
7742 }
7743 
7744 static void
7745 cxgbe_refresh_stats(struct vi_info *vi)
7746 {
7747 	u_int i, v, tnl_cong_drops, chan_map;
7748 	struct timeval tv;
7749 	const struct timeval interval = {0, 250000};	/* 250ms */
7750 	struct port_info *pi;
7751 	struct adapter *sc;
7752 
7753 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7754 
7755 	if (vi->flags & VI_SKIP_STATS)
7756 		return;
7757 
7758 	getmicrotime(&tv);
7759 	timevalsub(&tv, &interval);
7760 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7761 		return;
7762 
7763 	pi = vi->pi;
7764 	sc = vi->adapter;
7765 	tnl_cong_drops = 0;
7766 	t4_get_port_stats(sc, pi->hw_port, &pi->stats);
7767 	chan_map = pi->rx_e_chan_map;
7768 	while (chan_map) {
7769 		i = ffs(chan_map) - 1;
7770 		mtx_lock(&sc->reg_lock);
7771 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7772 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7773 		mtx_unlock(&sc->reg_lock);
7774 		tnl_cong_drops += v;
7775 		chan_map &= ~(1 << i);
7776 	}
7777 	pi->tnl_cong_drops = tnl_cong_drops;
7778 	getmicrotime(&vi->last_refreshed);
7779 }
7780 
7781 static void
7782 cxgbe_tick(void *arg)
7783 {
7784 	struct vi_info *vi = arg;
7785 
7786 	MPASS(IS_MAIN_VI(vi));
7787 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7788 
7789 	cxgbe_refresh_stats(vi);
7790 	callout_schedule(&vi->tick, hz);
7791 }
7792 
7793 static void
7794 vi_tick(void *arg)
7795 {
7796 	struct vi_info *vi = arg;
7797 
7798 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7799 
7800 	vi_refresh_stats(vi);
7801 	callout_schedule(&vi->tick, hz);
7802 }
7803 
7804 /* CIM inbound queues */
7805 static const char *t4_ibq[CIM_NUM_IBQ] = {
7806 	"ibq_tp0", "ibq_tp1", "ibq_ulp", "ibq_sge0", "ibq_sge1", "ibq_ncsi"
7807 };
7808 static const char *t7_ibq[CIM_NUM_IBQ_T7] = {
7809 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7810 	"ibq_sge1", "ibq_ncsi", NULL, "ibq_ipc1", "ibq_ipc2", "ibq_ipc3",
7811 	"ibq_ipc4", "ibq_ipc5", "ibq_ipc6", "ibq_ipc7"
7812 };
7813 static const char *t7_ibq_sec[] = {
7814 	"ibq_tp0", "ibq_tp1", "ibq_tp2", "ibq_tp3", "ibq_ulp", "ibq_sge0",
7815 	NULL, NULL, NULL, "ibq_ipc0"
7816 };
7817 
7818 /* CIM outbound queues */
7819 static const char *t4_obq[CIM_NUM_OBQ_T5] = {
7820 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7821 	"obq_sge_rx_q0", "obq_sge_rx_q1" /* These two are T5/T6 only */
7822 };
7823 static const char *t7_obq[CIM_NUM_OBQ_T7] = {
7824 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", "obq_ncsi",
7825 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc1", "obq_ipc2", "obq_ipc3",
7826 	"obq_ipc4", "obq_ipc5", "obq_ipc6", "obq_ipc7"
7827 };
7828 static const char *t7_obq_sec[] = {
7829 	"obq_ulp0", "obq_ulp1", "obq_ulp2", "obq_ulp3", "obq_sge", NULL,
7830 	"obq_sge_rx_q0", NULL, NULL, "obq_ipc0"
7831 };
7832 
7833 static void
7834 cim_sysctls(struct adapter *sc, struct sysctl_ctx_list *ctx,
7835     struct sysctl_oid_list *c0)
7836 {
7837 	struct sysctl_oid *oid;
7838 	struct sysctl_oid_list *children1;
7839 	int i, j, qcount;
7840 	char s[16];
7841 	const char **qname;
7842 
7843 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "cim",
7844 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM block");
7845 	c0 = SYSCTL_CHILDREN(oid);
7846 
7847 	SYSCTL_ADD_U8(ctx, c0, OID_AUTO, "ncores", CTLFLAG_RD, NULL,
7848 	    sc->params.ncores, "# of active CIM cores");
7849 
7850 	for (i = 0; i < sc->params.ncores; i++) {
7851 		snprintf(s, sizeof(s), "%u", i);
7852 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, s,
7853 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "CIM core");
7854 		children1 = SYSCTL_CHILDREN(oid);
7855 
7856 		/*
7857 		 * CTLFLAG_SKIP because the misc.devlog sysctl already displays
7858 		 * the log for all cores.  Use this sysctl to get the log for a
7859 		 * particular core only.
7860 		 */
7861 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "devlog",
7862 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_SKIP,
7863 		    sc, i, sysctl_devlog, "A", "firmware's device log");
7864 
7865 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "loadavg",
7866 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7867 		    sysctl_loadavg, "A",
7868 		    "microprocessor load averages (select firmwares only)");
7869 
7870 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "qcfg",
7871 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7872 		    chip_id(sc) > CHELSIO_T6 ? sysctl_cim_qcfg_t7 : sysctl_cim_qcfg,
7873 		    "A", "Queue configuration");
7874 
7875 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "la",
7876 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7877 		    sysctl_cim_la, "A", "Logic analyzer");
7878 
7879 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "ma_la",
7880 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7881 		    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7882 
7883 		SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, "pif_la",
7884 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, i,
7885 		    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7886 
7887 		/* IBQs */
7888 		switch (chip_id(sc)) {
7889 		case CHELSIO_T4:
7890 		case CHELSIO_T5:
7891 		case CHELSIO_T6:
7892 			qname = &t4_ibq[0];
7893 			qcount = nitems(t4_ibq);
7894 			break;
7895 		case CHELSIO_T7:
7896 		default:
7897 			if (i == 0) {
7898 				qname = &t7_ibq[0];
7899 				qcount = nitems(t7_ibq);
7900 			} else {
7901 				qname = &t7_ibq_sec[0];
7902 				qcount = nitems(t7_ibq_sec);
7903 			}
7904 			break;
7905 		}
7906 		MPASS(qcount <= sc->chip_params->cim_num_ibq);
7907 		for (j = 0; j < qcount; j++) {
7908 			if (qname[j] == NULL)
7909 				continue;
7910 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7911 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7912 			    (i << 16) | j, sysctl_cim_ibq, "A", NULL);
7913 		}
7914 
7915 		/* OBQs */
7916 		switch (chip_id(sc)) {
7917 		case CHELSIO_T4:
7918 			qname = t4_obq;
7919 			qcount = CIM_NUM_OBQ;
7920 			break;
7921 		case CHELSIO_T5:
7922 		case CHELSIO_T6:
7923 			qname = t4_obq;
7924 			qcount = nitems(t4_obq);
7925 			break;
7926 		case CHELSIO_T7:
7927 		default:
7928 			if (i == 0) {
7929 				qname = t7_obq;
7930 				qcount = nitems(t7_obq);
7931 			} else {
7932 				qname = t7_obq_sec;
7933 				qcount = nitems(t7_obq_sec);
7934 			}
7935 			break;
7936 		}
7937 		MPASS(qcount <= sc->chip_params->cim_num_obq);
7938 		for (j = 0; j < qcount; j++) {
7939 			if (qname[j] == NULL)
7940 				continue;
7941 			SYSCTL_ADD_PROC(ctx, children1, OID_AUTO, qname[j],
7942 			    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7943 			    (i << 16) | j, sysctl_cim_obq, "A", NULL);
7944 		}
7945 	}
7946 }
7947 
7948 /*
7949  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7950  */
7951 static char *caps_decoder[] = {
7952 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7953 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7954 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7955 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7956 	    "\006HASHFILTER\007ETHOFLD",
7957 	"\20\001TOE\002SENDPATH",			/* 4: TOE */
7958 	"\20\001RDDP\002RDMAC\003ROCEv2",		/* 5: RDMA */
7959 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7960 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7961 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7962 	    "\007T10DIF"
7963 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7964 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7965 	    "\004TLS_HW,\005TOE_IPSEC",
7966 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7967 		    "\004PO_INITIATOR\005PO_TARGET",
7968 	"\20\001NVMe_TCP",				/* 9: NVMe */
7969 };
7970 
7971 void
7972 t4_sysctls(struct adapter *sc)
7973 {
7974 	struct sysctl_ctx_list *ctx = &sc->ctx;
7975 	struct sysctl_oid *oid;
7976 	struct sysctl_oid_list *children, *c0;
7977 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7978 
7979 	/*
7980 	 * dev.t4nex.X.
7981 	 */
7982 	oid = device_get_sysctl_tree(sc->dev);
7983 	c0 = children = SYSCTL_CHILDREN(oid);
7984 
7985 	sc->sc_do_rxcopy = 1;
7986 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7987 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7988 
7989 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7990 	    sc->params.nports, "# of ports");
7991 
7992 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7993 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7994 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7995 	    "available doorbells");
7996 
7997 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7998 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7999 
8000 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
8001 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
8002 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
8003 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
8004 
8005 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
8006 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
8007 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
8008 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
8009 
8010 	t4_sge_sysctls(sc, ctx, children);
8011 
8012 	sc->lro_timeout = 100;
8013 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
8014 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
8015 
8016 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
8017 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
8018 
8019 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iflags", CTLFLAG_RW,
8020 	    &sc->intr_flags, 0, "flags for the slow interrupt handler");
8021 
8022 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
8023 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
8024 
8025 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
8026 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
8027 
8028 	if (sc->flags & IS_VF)
8029 		return;
8030 
8031 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
8032 	    NULL, chip_rev(sc), "chip hardware revision");
8033 
8034 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
8035 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
8036 
8037 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
8038 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
8039 
8040 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
8041 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
8042 
8043 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
8044 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
8045 
8046 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
8047 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
8048 
8049 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
8050 	    sc->er_version, 0, "expansion ROM version");
8051 
8052 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
8053 	    sc->bs_version, 0, "bootstrap firmware version");
8054 
8055 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
8056 	    NULL, sc->params.scfg_vers, "serial config version");
8057 
8058 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
8059 	    NULL, sc->params.vpd_vers, "VPD version");
8060 
8061 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
8062 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
8063 
8064 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
8065 	    sc->cfcsum, "config file checksum");
8066 
8067 #define SYSCTL_CAP(name, n, text) \
8068 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
8069 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
8070 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
8071 	    "available " text " capabilities")
8072 
8073 	SYSCTL_CAP(nbmcaps, 0, "NBM");
8074 	SYSCTL_CAP(linkcaps, 1, "link");
8075 	SYSCTL_CAP(switchcaps, 2, "switch");
8076 	SYSCTL_CAP(nvmecaps, 9, "NVMe");
8077 	SYSCTL_CAP(niccaps, 3, "NIC");
8078 	SYSCTL_CAP(toecaps, 4, "TCP offload");
8079 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
8080 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
8081 	SYSCTL_CAP(cryptocaps, 7, "crypto");
8082 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
8083 #undef SYSCTL_CAP
8084 
8085 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
8086 	    NULL, sc->tids.nftids, "number of filters");
8087 
8088 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_tunnel", CTLFLAG_RD,
8089 	    NULL, sc->params.nipsec_tunnel, "max hw IPsec tunnels");
8090 
8091 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nipsec_transport", CTLFLAG_RD,
8092 	    NULL, sc->params.nipsec_transport, "max hw IPsec transport pairs");
8093 
8094 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "nofld_ipsec_tunnel", CTLFLAG_RD,
8095 	    NULL, sc->params.nofld_ipsec_tunnel, "max hw IPsec tunnels (TOE)");
8096 
8097 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8098 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8099 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
8100 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
8101 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8102 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
8103 
8104 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
8105 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
8106 	    "I", "core Vdd (in mV)");
8107 
8108 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
8109 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
8110 	    sysctl_cpus, "A", "local CPUs");
8111 
8112 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
8113 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
8114 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
8115 
8116 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
8117 	    &sc->swintr, 0, "software triggered interrupts");
8118 
8119 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
8120 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
8121 	    "1 = reset adapter, 0 = zero reset counter");
8122 
8123 	/*
8124 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
8125 	 */
8126 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
8127 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
8128 	    "logs and miscellaneous information");
8129 	children = SYSCTL_CHILDREN(oid);
8130 
8131 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
8132 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8133 	    sysctl_cctrl, "A", "congestion control");
8134 
8135 	cim_sysctls(sc, ctx, children);
8136 
8137 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
8138 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8139 	    sysctl_cpl_stats, "A", "CPL statistics");
8140 
8141 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
8142 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8143 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
8144 
8145 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
8146 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8147 	    sysctl_tid_stats, "A", "tid stats");
8148 
8149 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
8150 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, -1,
8151 	    sysctl_devlog, "A", "firmware's device log (all cores)");
8152 
8153 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
8154 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8155 	    sysctl_fcoe_stats, "A", "FCoE statistics");
8156 
8157 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
8158 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8159 	    sysctl_hw_sched, "A", "hardware scheduler ");
8160 
8161 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
8162 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8163 	    sysctl_l2t, "A", "hardware L2 table");
8164 
8165 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
8166 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8167 	    sysctl_smt, "A", "hardware source MAC table");
8168 
8169 #ifdef INET6
8170 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
8171 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8172 	    sysctl_clip, "A", "active CLIP table entries");
8173 #endif
8174 
8175 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
8176 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8177 	    sysctl_lb_stats, "A", "loopback statistics");
8178 
8179 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
8180 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8181 	    sysctl_meminfo, "A", "memory regions");
8182 
8183 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
8184 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8185 	    chip_id(sc) >= CHELSIO_T7 ? sysctl_mps_tcam_t7 :
8186 	    (chip_id(sc) >= CHELSIO_T6 ? sysctl_mps_tcam_t6 : sysctl_mps_tcam),
8187 	    "A", "MPS TCAM entries");
8188 
8189 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
8190 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8191 	    sysctl_path_mtus, "A", "path MTUs");
8192 
8193 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
8194 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8195 	    sysctl_pm_stats, "A", "PM statistics");
8196 
8197 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
8198 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8199 	    sysctl_rdma_stats, "A", "RDMA statistics");
8200 
8201 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
8202 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8203 	    sysctl_tcp_stats, "A", "TCP statistics");
8204 
8205 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
8206 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8207 	    sysctl_tids, "A", "TID information");
8208 
8209 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
8210 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8211 	    sysctl_tp_err_stats, "A", "TP error statistics");
8212 
8213 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
8214 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8215 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
8216 
8217 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
8218 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
8219 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
8220 
8221 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
8222 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8223 	    sysctl_tp_la, "A", "TP logic analyzer");
8224 
8225 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
8226 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8227 	    sysctl_tx_rate, "A", "Tx rate");
8228 
8229 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
8230 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8231 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
8232 
8233 	if (chip_id(sc) >= CHELSIO_T5) {
8234 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
8235 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8236 		    sysctl_wcwr_stats, "A", "write combined work requests");
8237 	}
8238 
8239 	if (chip_id(sc) >= CHELSIO_T7) {
8240 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcb_cache",
8241 		    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tcb_cache, "I",
8242 		    "1 = enabled (default), 0 = disabled (for debug only)");
8243 	}
8244 
8245 #ifdef KERN_TLS
8246 	if (is_ktls(sc)) {
8247 		/*
8248 		 * dev.t4nex.0.tls.
8249 		 */
8250 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
8251 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
8252 		children = SYSCTL_CHILDREN(oid);
8253 
8254 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
8255 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
8256 		    "keys in work requests (1) or attempt to store TLS keys "
8257 		    "in card memory.");
8258 
8259 		if (is_t6(sc))
8260 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
8261 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
8262 			    "combine TCB field updates with TLS record work "
8263 			    "requests.");
8264 		else {
8265 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "short_records",
8266 			    CTLFLAG_RW, &sc->tlst.short_records, 0,
8267 			    "Use cipher-only mode for short records.");
8268 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "partial_ghash",
8269 			    CTLFLAG_RW, &sc->tlst.partial_ghash, 0,
8270 			    "Use partial GHASH for AES-GCM records.");
8271 		}
8272 	}
8273 #endif
8274 
8275 #ifdef TCP_OFFLOAD
8276 	if (is_offload(sc)) {
8277 		int i;
8278 		char s[4];
8279 
8280 		/*
8281 		 * dev.t4nex.X.toe.
8282 		 */
8283 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
8284 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
8285 		children = SYSCTL_CHILDREN(oid);
8286 
8287 		sc->tt.cong_algorithm = -1;
8288 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
8289 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
8290 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
8291 		    "3 = highspeed)");
8292 
8293 		sc->tt.sndbuf = -1;
8294 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
8295 		    &sc->tt.sndbuf, 0, "hardware send buffer");
8296 
8297 		sc->tt.ddp = 0;
8298 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
8299 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
8300 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
8301 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
8302 
8303 		sc->tt.rx_coalesce = -1;
8304 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
8305 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
8306 
8307 		sc->tt.tls = 1;
8308 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
8309 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
8310 		    "Inline TLS allowed");
8311 
8312 		sc->tt.tx_align = -1;
8313 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
8314 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
8315 
8316 		sc->tt.tx_zcopy = 0;
8317 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
8318 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
8319 		    "Enable zero-copy aio_write(2)");
8320 
8321 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
8322 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8323 		    "cop_managed_offloading", CTLFLAG_RW,
8324 		    &sc->tt.cop_managed_offloading, 0,
8325 		    "COP (Connection Offload Policy) controls all TOE offload");
8326 
8327 		sc->tt.autorcvbuf_inc = 16 * 1024;
8328 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
8329 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
8330 		    "autorcvbuf increment");
8331 
8332 		sc->tt.update_hc_on_pmtu_change = 1;
8333 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
8334 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
8335 		    &sc->tt.update_hc_on_pmtu_change, 0,
8336 		    "Update hostcache entry if the PMTU changes");
8337 
8338 		sc->tt.iso = 1;
8339 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
8340 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
8341 
8342 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
8343 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8344 		    sysctl_tp_tick, "A", "TP timer tick (us)");
8345 
8346 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
8347 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
8348 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
8349 
8350 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
8351 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
8352 		    sysctl_tp_tick, "A", "DACK tick (us)");
8353 
8354 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
8355 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
8356 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
8357 
8358 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
8359 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8360 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
8361 		    "Minimum retransmit interval (us)");
8362 
8363 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
8364 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8365 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
8366 		    "Maximum retransmit interval (us)");
8367 
8368 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
8369 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8370 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
8371 		    "Persist timer min (us)");
8372 
8373 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
8374 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8375 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
8376 		    "Persist timer max (us)");
8377 
8378 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
8379 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8380 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
8381 		    "Keepalive idle timer (us)");
8382 
8383 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
8384 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8385 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
8386 		    "Keepalive interval timer (us)");
8387 
8388 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
8389 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8390 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
8391 
8392 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
8393 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8394 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
8395 		    "FINWAIT2 timer (us)");
8396 
8397 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
8398 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8399 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
8400 		    "Number of SYN retransmissions before abort");
8401 
8402 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
8403 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8404 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
8405 		    "Number of retransmissions before abort");
8406 
8407 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
8408 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8409 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
8410 		    "Number of keepalive probes before abort");
8411 
8412 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
8413 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8414 		    "TOE retransmit backoffs");
8415 		children = SYSCTL_CHILDREN(oid);
8416 		for (i = 0; i < 16; i++) {
8417 			snprintf(s, sizeof(s), "%u", i);
8418 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
8419 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8420 			    i, sysctl_tp_backoff, "IU",
8421 			    "TOE retransmit backoff");
8422 		}
8423 	}
8424 #endif
8425 }
8426 
8427 void
8428 vi_sysctls(struct vi_info *vi)
8429 {
8430 	struct sysctl_ctx_list *ctx = &vi->ctx;
8431 	struct sysctl_oid *oid;
8432 	struct sysctl_oid_list *children;
8433 
8434 	/*
8435 	 * dev.v?(cxgbe|cxl).X.
8436 	 */
8437 	oid = device_get_sysctl_tree(vi->dev);
8438 	children = SYSCTL_CHILDREN(oid);
8439 
8440 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
8441 	    vi->viid, "VI identifer");
8442 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
8443 	    &vi->nrxq, 0, "# of rx queues");
8444 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
8445 	    &vi->ntxq, 0, "# of tx queues");
8446 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
8447 	    &vi->first_rxq, 0, "index of first rx queue");
8448 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
8449 	    &vi->first_txq, 0, "index of first tx queue");
8450 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
8451 	    vi->rss_base, "start of RSS indirection table");
8452 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
8453 	    vi->rss_size, "size of RSS indirection table");
8454 
8455 	if (IS_MAIN_VI(vi)) {
8456 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
8457 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8458 		    sysctl_noflowq, "IU",
8459 		    "Reserve queue 0 for non-flowid packets");
8460 	}
8461 
8462 	if (vi->adapter->flags & IS_VF) {
8463 		MPASS(vi->flags & TX_USES_VM_WR);
8464 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
8465 		    NULL, 1, "use VM work requests for transmit");
8466 	} else {
8467 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
8468 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8469 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
8470 	}
8471 
8472 #ifdef TCP_OFFLOAD
8473 	if (vi->nofldrxq != 0) {
8474 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
8475 		    &vi->nofldrxq, 0,
8476 		    "# of rx queues for offloaded TCP connections");
8477 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
8478 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
8479 		    "index of first TOE rx queue");
8480 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
8481 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8482 		    sysctl_holdoff_tmr_idx_ofld, "I",
8483 		    "holdoff timer index for TOE queues");
8484 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
8485 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8486 		    sysctl_holdoff_pktc_idx_ofld, "I",
8487 		    "holdoff packet counter index for TOE queues");
8488 	}
8489 #endif
8490 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
8491 	if (vi->nofldtxq != 0) {
8492 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
8493 		    &vi->nofldtxq, 0,
8494 		    "# of tx queues for TOE/ETHOFLD");
8495 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
8496 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
8497 		    "index of first TOE/ETHOFLD tx queue");
8498 	}
8499 #endif
8500 #ifdef DEV_NETMAP
8501 	if (vi->nnmrxq != 0) {
8502 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
8503 		    &vi->nnmrxq, 0, "# of netmap rx queues");
8504 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
8505 		    &vi->nnmtxq, 0, "# of netmap tx queues");
8506 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
8507 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
8508 		    "index of first netmap rx queue");
8509 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
8510 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
8511 		    "index of first netmap tx queue");
8512 	}
8513 #endif
8514 
8515 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8516 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8517 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8518 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8519 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8520 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8521 
8522 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8523 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8524 	    sysctl_qsize_rxq, "I", "rx queue size");
8525 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8526 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8527 	    sysctl_qsize_txq, "I", "tx queue size");
8528 }
8529 
8530 static void
8531 cxgbe_sysctls(struct port_info *pi)
8532 {
8533 	struct sysctl_ctx_list *ctx = &pi->ctx;
8534 	struct sysctl_oid *oid;
8535 	struct sysctl_oid_list *children, *children2;
8536 	struct adapter *sc = pi->adapter;
8537 	int i;
8538 	char name[16];
8539 	static char *tc_flags = {"\20\1USER"};
8540 
8541 	/*
8542 	 * dev.cxgbe.X.
8543 	 */
8544 	oid = device_get_sysctl_tree(pi->dev);
8545 	children = SYSCTL_CHILDREN(oid);
8546 
8547 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8548 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8549 	    sysctl_linkdnrc, "A", "reason why link is down");
8550 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8551 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8552 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8553 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8554 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8555 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8556 		    sysctl_btphy, "I", "PHY firmware version");
8557 	}
8558 
8559 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8560 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8561 	    sysctl_pause_settings, "A",
8562 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8563 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8564 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8565 	    "FEC in use on the link");
8566 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8567 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8568 	    sysctl_requested_fec, "A",
8569 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8571 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8572 	    "FEC recommended by the cable/transceiver");
8573 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8574 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8575 	    sysctl_autoneg, "I",
8576 	    "autonegotiation (-1 = not supported)");
8577 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8578 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8579 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8580 
8581 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8582 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8583 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8584 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8585 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8586 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8587 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8588 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8589 
8590 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8591 	    port_top_speed(pi), "max speed (in Gbps)");
8592 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8593 	    pi->mps_bg_map, "MPS buffer group map");
8594 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8595 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8596 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8597 	    pi->tx_chan, "TP tx c-channel");
8598 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8599 	    pi->rx_chan, "TP rx c-channel");
8600 
8601 	if (sc->flags & IS_VF)
8602 		return;
8603 
8604 	/*
8605 	 * dev.(cxgbe|cxl).X.tc.
8606 	 */
8607 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8608 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8609 	    "Tx scheduler traffic classes (cl_rl)");
8610 	children2 = SYSCTL_CHILDREN(oid);
8611 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8612 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8613 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8614 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8615 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8616 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8617 	for (i = 0; i < sc->params.nsched_cls; i++) {
8618 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8619 
8620 		snprintf(name, sizeof(name), "%d", i);
8621 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8622 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8623 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8624 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8625 		    CTLFLAG_RD, &tc->state, 0, "current state");
8626 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8627 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8628 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8629 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8630 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8631 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8632 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8633 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8634 		    "traffic class parameters");
8635 	}
8636 
8637 	/*
8638 	 * dev.cxgbe.X.stats.
8639 	 */
8640 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8641 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8642 	children = SYSCTL_CHILDREN(oid);
8643 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8644 	    &pi->tx_parse_error, 0,
8645 	    "# of tx packets with invalid length or # of segments");
8646 
8647 #define T4_LBSTAT(name, stat, desc) do { \
8648 	if (sc->params.tp.lb_mode) { \
8649 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8650 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, \
8651 		    A_MPS_PORT_STAT_##stat##_L, \
8652 		    sysctl_handle_t4_portstat64, "QU", desc); \
8653 	} else { \
8654 		SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8655 		    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8656 		    t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8657 		    sysctl_handle_t4_reg64, "QU", desc); \
8658 	} \
8659 } while (0)
8660 
8661 	T4_LBSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8662 	T4_LBSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8663 	T4_LBSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8664 	T4_LBSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8665 	T4_LBSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8666 	T4_LBSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8667 	T4_LBSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8668 	T4_LBSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8669 	T4_LBSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8670 	T4_LBSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8671 	T4_LBSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8672 	T4_LBSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8673 	T4_LBSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8674 	T4_LBSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8675 	T4_LBSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8676 	T4_LBSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8677 	T4_LBSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8678 	T4_LBSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8679 	T4_LBSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8680 	T4_LBSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8681 	T4_LBSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8682 	T4_LBSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8683 	T4_LBSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8684 
8685 	T4_LBSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8686 	T4_LBSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8687 	T4_LBSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8688 	T4_LBSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8689 	T4_LBSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8690 	T4_LBSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8691 	T4_LBSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8692 	if (is_t6(sc)) {
8693 		/* Read from port_stats and may be stale by up to 1s */
8694 		SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, "rx_fcs_err",
8695 		    CTLFLAG_RD, &pi->stats.rx_fcs_err,
8696 		    "# of frames received with bad FCS since last link up");
8697 	} else {
8698 		T4_LBSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8699 		    "# of frames received with bad FCS");
8700 	}
8701 	T4_LBSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8702 	T4_LBSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8703 	T4_LBSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8704 	T4_LBSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8705 	T4_LBSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8706 	T4_LBSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8707 	T4_LBSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8708 	T4_LBSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8709 	T4_LBSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8710 	T4_LBSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8711 	T4_LBSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8712 	T4_LBSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8713 	T4_LBSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8714 	T4_LBSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8715 	T4_LBSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8716 	T4_LBSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8717 	T4_LBSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8718 	T4_LBSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8719 	T4_LBSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8720 #undef T4_LBSTAT
8721 
8722 #define T4_REGSTAT(name, stat, desc) do { \
8723 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8724 	    CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8725 	    A_MPS_STAT_##stat##_L, sysctl_handle_t4_reg64, "QU", desc); \
8726 } while (0)
8727 
8728 	if (pi->mps_bg_map & 1) {
8729 		T4_REGSTAT(rx_ovflow0, RX_BG_0_MAC_DROP_FRAME,
8730 		    "# drops due to buffer-group 0 overflows");
8731 		T4_REGSTAT(rx_trunc0, RX_BG_0_MAC_TRUNC_FRAME,
8732 		    "# of buffer-group 0 truncated packets");
8733 	}
8734 	if (pi->mps_bg_map & 2) {
8735 		T4_REGSTAT(rx_ovflow1, RX_BG_1_MAC_DROP_FRAME,
8736 		    "# drops due to buffer-group 1 overflows");
8737 		T4_REGSTAT(rx_trunc1, RX_BG_1_MAC_TRUNC_FRAME,
8738 		    "# of buffer-group 1 truncated packets");
8739 	}
8740 	if (pi->mps_bg_map & 4) {
8741 		T4_REGSTAT(rx_ovflow2, RX_BG_2_MAC_DROP_FRAME,
8742 		    "# drops due to buffer-group 2 overflows");
8743 		T4_REGSTAT(rx_trunc2, RX_BG_2_MAC_TRUNC_FRAME,
8744 		    "# of buffer-group 2 truncated packets");
8745 	}
8746 	if (pi->mps_bg_map & 8) {
8747 		T4_REGSTAT(rx_ovflow3, RX_BG_3_MAC_DROP_FRAME,
8748 		    "# drops due to buffer-group 3 overflows");
8749 		T4_REGSTAT(rx_trunc3, RX_BG_3_MAC_TRUNC_FRAME,
8750 		    "# of buffer-group 3 truncated packets");
8751 	}
8752 #undef T4_REGSTAT
8753 }
8754 
8755 static int
8756 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8757 {
8758 	int rc, *i, space = 0;
8759 	struct sbuf sb;
8760 
8761 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8762 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8763 		if (space)
8764 			sbuf_printf(&sb, " ");
8765 		sbuf_printf(&sb, "%d", *i);
8766 		space = 1;
8767 	}
8768 	rc = sbuf_finish(&sb);
8769 	sbuf_delete(&sb);
8770 	return (rc);
8771 }
8772 
8773 static int
8774 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8775 {
8776 	int rc;
8777 	struct sbuf *sb;
8778 
8779 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8780 	if (sb == NULL)
8781 		return (ENOMEM);
8782 
8783 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8784 	rc = sbuf_finish(sb);
8785 	sbuf_delete(sb);
8786 
8787 	return (rc);
8788 }
8789 
8790 static int
8791 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8792 {
8793 	int rc;
8794 	struct sbuf *sb;
8795 
8796 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8797 	if (sb == NULL)
8798 		return (ENOMEM);
8799 
8800 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8801 	rc = sbuf_finish(sb);
8802 	sbuf_delete(sb);
8803 
8804 	return (rc);
8805 }
8806 
8807 static int
8808 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8809 {
8810 	struct port_info *pi = arg1;
8811 	int op = arg2;
8812 	struct adapter *sc = pi->adapter;
8813 	u_int v;
8814 	int rc;
8815 
8816 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8817 	if (rc)
8818 		return (rc);
8819 	if (!hw_all_ok(sc))
8820 		rc = ENXIO;
8821 	else {
8822 		/* XXX: magic numbers */
8823 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8824 		    op ? 0x20 : 0xc820, &v);
8825 	}
8826 	end_synchronized_op(sc, 0);
8827 	if (rc)
8828 		return (rc);
8829 	if (op == 0)
8830 		v /= 256;
8831 
8832 	rc = sysctl_handle_int(oidp, &v, 0, req);
8833 	return (rc);
8834 }
8835 
8836 static int
8837 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8838 {
8839 	struct vi_info *vi = arg1;
8840 	int rc, val;
8841 
8842 	val = vi->rsrv_noflowq;
8843 	rc = sysctl_handle_int(oidp, &val, 0, req);
8844 	if (rc != 0 || req->newptr == NULL)
8845 		return (rc);
8846 
8847 	if ((val >= 1) && (vi->ntxq > 1))
8848 		vi->rsrv_noflowq = 1;
8849 	else
8850 		vi->rsrv_noflowq = 0;
8851 
8852 	return (rc);
8853 }
8854 
8855 static int
8856 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8857 {
8858 	struct vi_info *vi = arg1;
8859 	struct adapter *sc = vi->adapter;
8860 	int rc, val, i;
8861 
8862 	MPASS(!(sc->flags & IS_VF));
8863 
8864 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8865 	rc = sysctl_handle_int(oidp, &val, 0, req);
8866 	if (rc != 0 || req->newptr == NULL)
8867 		return (rc);
8868 
8869 	if (val != 0 && val != 1)
8870 		return (EINVAL);
8871 
8872 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8873 	    "t4txvm");
8874 	if (rc)
8875 		return (rc);
8876 	if (!hw_all_ok(sc))
8877 		rc = ENXIO;
8878 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8879 		/*
8880 		 * We don't want parse_pkt to run with one setting (VF or PF)
8881 		 * and then eth_tx to see a different setting but still use
8882 		 * stale information calculated by parse_pkt.
8883 		 */
8884 		rc = EBUSY;
8885 	} else {
8886 		struct port_info *pi = vi->pi;
8887 		struct sge_txq *txq;
8888 		uint32_t ctrl0;
8889 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8890 
8891 		if (val) {
8892 			vi->flags |= TX_USES_VM_WR;
8893 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8894 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8895 			    V_TXPKT_INTF(pi->hw_port));
8896 			if (!(sc->flags & IS_VF))
8897 				npkt--;
8898 		} else {
8899 			vi->flags &= ~TX_USES_VM_WR;
8900 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8901 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8902 			    V_TXPKT_INTF(pi->hw_port) | V_TXPKT_PF(sc->pf) |
8903 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8904 		}
8905 		for_each_txq(vi, i, txq) {
8906 			txq->cpl_ctrl0 = ctrl0;
8907 			txq->txp.max_npkt = npkt;
8908 		}
8909 	}
8910 	end_synchronized_op(sc, LOCK_HELD);
8911 	return (rc);
8912 }
8913 
8914 static int
8915 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8916 {
8917 	struct vi_info *vi = arg1;
8918 	struct adapter *sc = vi->adapter;
8919 	int idx, rc, i;
8920 	struct sge_rxq *rxq;
8921 	uint8_t v;
8922 
8923 	idx = vi->tmr_idx;
8924 
8925 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8926 	if (rc != 0 || req->newptr == NULL)
8927 		return (rc);
8928 
8929 	if (idx < 0 || idx >= SGE_NTIMERS)
8930 		return (EINVAL);
8931 
8932 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8933 	    "t4tmr");
8934 	if (rc)
8935 		return (rc);
8936 
8937 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8938 	for_each_rxq(vi, i, rxq) {
8939 #ifdef atomic_store_rel_8
8940 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8941 #else
8942 		rxq->iq.intr_params = v;
8943 #endif
8944 	}
8945 	vi->tmr_idx = idx;
8946 
8947 	end_synchronized_op(sc, LOCK_HELD);
8948 	return (0);
8949 }
8950 
8951 static int
8952 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8953 {
8954 	struct vi_info *vi = arg1;
8955 	struct adapter *sc = vi->adapter;
8956 	int idx, rc;
8957 
8958 	idx = vi->pktc_idx;
8959 
8960 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8961 	if (rc != 0 || req->newptr == NULL)
8962 		return (rc);
8963 
8964 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8965 		return (EINVAL);
8966 
8967 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8968 	    "t4pktc");
8969 	if (rc)
8970 		return (rc);
8971 
8972 	if (vi->flags & VI_INIT_DONE)
8973 		rc = EBUSY; /* cannot be changed once the queues are created */
8974 	else
8975 		vi->pktc_idx = idx;
8976 
8977 	end_synchronized_op(sc, LOCK_HELD);
8978 	return (rc);
8979 }
8980 
8981 static int
8982 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8983 {
8984 	struct vi_info *vi = arg1;
8985 	struct adapter *sc = vi->adapter;
8986 	int qsize, rc;
8987 
8988 	qsize = vi->qsize_rxq;
8989 
8990 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8991 	if (rc != 0 || req->newptr == NULL)
8992 		return (rc);
8993 
8994 	if (qsize < 128 || (qsize & 7))
8995 		return (EINVAL);
8996 
8997 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8998 	    "t4rxqs");
8999 	if (rc)
9000 		return (rc);
9001 
9002 	if (vi->flags & VI_INIT_DONE)
9003 		rc = EBUSY; /* cannot be changed once the queues are created */
9004 	else
9005 		vi->qsize_rxq = qsize;
9006 
9007 	end_synchronized_op(sc, LOCK_HELD);
9008 	return (rc);
9009 }
9010 
9011 static int
9012 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
9013 {
9014 	struct vi_info *vi = arg1;
9015 	struct adapter *sc = vi->adapter;
9016 	int qsize, rc;
9017 
9018 	qsize = vi->qsize_txq;
9019 
9020 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
9021 	if (rc != 0 || req->newptr == NULL)
9022 		return (rc);
9023 
9024 	if (qsize < 128 || qsize > 65536)
9025 		return (EINVAL);
9026 
9027 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
9028 	    "t4txqs");
9029 	if (rc)
9030 		return (rc);
9031 
9032 	if (vi->flags & VI_INIT_DONE)
9033 		rc = EBUSY; /* cannot be changed once the queues are created */
9034 	else
9035 		vi->qsize_txq = qsize;
9036 
9037 	end_synchronized_op(sc, LOCK_HELD);
9038 	return (rc);
9039 }
9040 
9041 static int
9042 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
9043 {
9044 	struct port_info *pi = arg1;
9045 	struct adapter *sc = pi->adapter;
9046 	struct link_config *lc = &pi->link_cfg;
9047 	int rc;
9048 
9049 	if (req->newptr == NULL) {
9050 		struct sbuf *sb;
9051 		static char *bits = "\20\1RX\2TX\3AUTO";
9052 
9053 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9054 		if (sb == NULL)
9055 			return (ENOMEM);
9056 
9057 		if (lc->link_ok) {
9058 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
9059 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
9060 		} else {
9061 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
9062 			    PAUSE_RX | PAUSE_AUTONEG), bits);
9063 		}
9064 		rc = sbuf_finish(sb);
9065 		sbuf_delete(sb);
9066 	} else {
9067 		char s[2];
9068 		int n;
9069 
9070 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
9071 		    PAUSE_AUTONEG));
9072 		s[1] = 0;
9073 
9074 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9075 		if (rc != 0)
9076 			return(rc);
9077 
9078 		if (s[1] != 0)
9079 			return (EINVAL);
9080 		if (s[0] < '0' || s[0] > '9')
9081 			return (EINVAL);	/* not a number */
9082 		n = s[0] - '0';
9083 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
9084 			return (EINVAL);	/* some other bit is set too */
9085 
9086 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9087 		    "t4PAUSE");
9088 		if (rc)
9089 			return (rc);
9090 		if (hw_all_ok(sc)) {
9091 			PORT_LOCK(pi);
9092 			lc->requested_fc = n;
9093 			fixup_link_config(pi);
9094 			if (pi->up_vis > 0)
9095 				rc = apply_link_config(pi);
9096 			set_current_media(pi);
9097 			PORT_UNLOCK(pi);
9098 		}
9099 		end_synchronized_op(sc, 0);
9100 	}
9101 
9102 	return (rc);
9103 }
9104 
9105 static int
9106 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
9107 {
9108 	struct port_info *pi = arg1;
9109 	struct link_config *lc = &pi->link_cfg;
9110 	int rc;
9111 	struct sbuf *sb;
9112 
9113 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9114 	if (sb == NULL)
9115 		return (ENOMEM);
9116 	if (lc->link_ok)
9117 		sbuf_printf(sb, "%b", lc->fec, t4_fec_bits);
9118 	else
9119 		sbuf_printf(sb, "no link");
9120 	rc = sbuf_finish(sb);
9121 	sbuf_delete(sb);
9122 
9123 	return (rc);
9124 }
9125 
9126 static int
9127 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
9128 {
9129 	struct port_info *pi = arg1;
9130 	struct adapter *sc = pi->adapter;
9131 	struct link_config *lc = &pi->link_cfg;
9132 	int rc;
9133 	int8_t old = lc->requested_fec;
9134 
9135 	if (req->newptr == NULL) {
9136 		struct sbuf *sb;
9137 
9138 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9139 		if (sb == NULL)
9140 			return (ENOMEM);
9141 
9142 		sbuf_printf(sb, "%b", old, t4_fec_bits);
9143 		rc = sbuf_finish(sb);
9144 		sbuf_delete(sb);
9145 	} else {
9146 		char s[8];
9147 		int n;
9148 
9149 		snprintf(s, sizeof(s), "%d", old == FEC_AUTO ? -1 :
9150 		    old & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
9151 
9152 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
9153 		if (rc != 0)
9154 			return(rc);
9155 
9156 		n = strtol(&s[0], NULL, 0);
9157 		if (n < 0 || n & FEC_AUTO)
9158 			n = FEC_AUTO;
9159 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
9160 			return (EINVAL);/* some other bit is set too */
9161 
9162 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9163 		    "t4reqf");
9164 		if (rc)
9165 			return (rc);
9166 		PORT_LOCK(pi);
9167 		if (lc->requested_fec != old) {
9168 			rc = EBUSY;
9169 			goto done;
9170 		}
9171 		if (n == FEC_AUTO)
9172 			lc->requested_fec = FEC_AUTO;
9173 		else if (n == 0 || n == FEC_NONE)
9174 			lc->requested_fec = FEC_NONE;
9175 		else {
9176 			if ((lc->pcaps |
9177 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
9178 			    lc->pcaps) {
9179 				rc = ENOTSUP;
9180 				goto done;
9181 			}
9182 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
9183 			    FEC_MODULE);
9184 		}
9185 		if (hw_all_ok(sc)) {
9186 			fixup_link_config(pi);
9187 			if (pi->up_vis > 0) {
9188 				rc = apply_link_config(pi);
9189 				if (rc != 0) {
9190 					lc->requested_fec = old;
9191 					if (rc == FW_EPROTO)
9192 						rc = ENOTSUP;
9193 				}
9194 			}
9195 		}
9196 done:
9197 		PORT_UNLOCK(pi);
9198 		end_synchronized_op(sc, 0);
9199 	}
9200 
9201 	return (rc);
9202 }
9203 
9204 static int
9205 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
9206 {
9207 	struct port_info *pi = arg1;
9208 	struct adapter *sc = pi->adapter;
9209 	struct link_config *lc = &pi->link_cfg;
9210 	int rc;
9211 	int8_t fec;
9212 	struct sbuf *sb;
9213 
9214 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
9215 	if (sb == NULL)
9216 		return (ENOMEM);
9217 
9218 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
9219 		rc = EBUSY;
9220 		goto done;
9221 	}
9222 	if (!hw_all_ok(sc)) {
9223 		rc = ENXIO;
9224 		goto done;
9225 	}
9226 	PORT_LOCK(pi);
9227 	if (pi->up_vis == 0) {
9228 		/*
9229 		 * If all the interfaces are administratively down the firmware
9230 		 * does not report transceiver changes.  Refresh port info here.
9231 		 * This is the only reason we have a synchronized op in this
9232 		 * function.  Just PORT_LOCK would have been enough otherwise.
9233 		 */
9234 		t4_update_port_info(pi);
9235 	}
9236 
9237 	fec = lc->fec_hint;
9238 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
9239 	    !fec_supported(lc->pcaps)) {
9240 		PORT_UNLOCK(pi);
9241 		sbuf_printf(sb, "n/a");
9242 	} else {
9243 		if (fec == 0)
9244 			fec = FEC_NONE;
9245 		PORT_UNLOCK(pi);
9246 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, t4_fec_bits);
9247 	}
9248 	rc = sbuf_finish(sb);
9249 done:
9250 	sbuf_delete(sb);
9251 	end_synchronized_op(sc, 0);
9252 
9253 	return (rc);
9254 }
9255 
9256 static int
9257 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
9258 {
9259 	struct port_info *pi = arg1;
9260 	struct adapter *sc = pi->adapter;
9261 	struct link_config *lc = &pi->link_cfg;
9262 	int rc, val;
9263 
9264 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
9265 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
9266 	else
9267 		val = -1;
9268 	rc = sysctl_handle_int(oidp, &val, 0, req);
9269 	if (rc != 0 || req->newptr == NULL)
9270 		return (rc);
9271 	if (val == 0)
9272 		val = AUTONEG_DISABLE;
9273 	else if (val == 1)
9274 		val = AUTONEG_ENABLE;
9275 	else
9276 		val = AUTONEG_AUTO;
9277 
9278 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
9279 	    "t4aneg");
9280 	if (rc)
9281 		return (rc);
9282 	PORT_LOCK(pi);
9283 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
9284 		rc = ENOTSUP;
9285 		goto done;
9286 	}
9287 	lc->requested_aneg = val;
9288 	if (hw_all_ok(sc)) {
9289 		fixup_link_config(pi);
9290 		if (pi->up_vis > 0)
9291 			rc = apply_link_config(pi);
9292 		set_current_media(pi);
9293 	}
9294 done:
9295 	PORT_UNLOCK(pi);
9296 	end_synchronized_op(sc, 0);
9297 	return (rc);
9298 }
9299 
9300 static int
9301 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
9302 {
9303 	struct port_info *pi = arg1;
9304 	struct adapter *sc = pi->adapter;
9305 	struct link_config *lc = &pi->link_cfg;
9306 	int rc, val;
9307 
9308 	val = lc->force_fec;
9309 	MPASS(val >= -1 && val <= 1);
9310 	rc = sysctl_handle_int(oidp, &val, 0, req);
9311 	if (rc != 0 || req->newptr == NULL)
9312 		return (rc);
9313 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
9314 		return (ENOTSUP);
9315 	if (val < -1 || val > 1)
9316 		return (EINVAL);
9317 
9318 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
9319 	if (rc)
9320 		return (rc);
9321 	PORT_LOCK(pi);
9322 	lc->force_fec = val;
9323 	if (hw_all_ok(sc)) {
9324 		fixup_link_config(pi);
9325 		if (pi->up_vis > 0)
9326 			rc = apply_link_config(pi);
9327 	}
9328 	PORT_UNLOCK(pi);
9329 	end_synchronized_op(sc, 0);
9330 	return (rc);
9331 }
9332 
9333 static int
9334 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
9335 {
9336 	struct adapter *sc = arg1;
9337 	int rc, reg = arg2;
9338 	uint64_t val;
9339 
9340 	mtx_lock(&sc->reg_lock);
9341 	if (hw_off_limits(sc))
9342 		rc = ENXIO;
9343 	else {
9344 		rc = 0;
9345 		val = t4_read_reg64(sc, reg);
9346 	}
9347 	mtx_unlock(&sc->reg_lock);
9348 	if (rc == 0)
9349 		rc = sysctl_handle_64(oidp, &val, 0, req);
9350 	return (rc);
9351 }
9352 
9353 static int
9354 sysctl_handle_t4_portstat64(SYSCTL_HANDLER_ARGS)
9355 {
9356 	struct port_info *pi = arg1;
9357 	struct adapter *sc = pi->adapter;
9358 	int rc, i, reg = arg2;
9359 	uint64_t val;
9360 
9361 	mtx_lock(&sc->reg_lock);
9362 	if (hw_off_limits(sc))
9363 		rc = ENXIO;
9364 	else {
9365 		val = 0;
9366 		for (i = 0; i < sc->params.tp.lb_nchan; i++) {
9367 			val += t4_read_reg64(sc,
9368 			    t4_port_reg(sc, pi->tx_chan + i, reg));
9369 		}
9370 		rc = 0;
9371 	}
9372 	mtx_unlock(&sc->reg_lock);
9373 	if (rc == 0)
9374 		rc = sysctl_handle_64(oidp, &val, 0, req);
9375 	return (rc);
9376 }
9377 
9378 static int
9379 sysctl_temperature(SYSCTL_HANDLER_ARGS)
9380 {
9381 	struct adapter *sc = arg1;
9382 	int rc, t;
9383 	uint32_t param, val;
9384 
9385 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
9386 	if (rc)
9387 		return (rc);
9388 	if (!hw_all_ok(sc))
9389 		rc = ENXIO;
9390 	else {
9391 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9392 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9393 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
9394 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9395 	}
9396 	end_synchronized_op(sc, 0);
9397 	if (rc)
9398 		return (rc);
9399 
9400 	/* unknown is returned as 0 but we display -1 in that case */
9401 	t = val == 0 ? -1 : val;
9402 
9403 	rc = sysctl_handle_int(oidp, &t, 0, req);
9404 	return (rc);
9405 }
9406 
9407 static int
9408 sysctl_vdd(SYSCTL_HANDLER_ARGS)
9409 {
9410 	struct adapter *sc = arg1;
9411 	int rc;
9412 	uint32_t param, val;
9413 
9414 	if (sc->params.core_vdd == 0) {
9415 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
9416 		    "t4vdd");
9417 		if (rc)
9418 			return (rc);
9419 		if (!hw_all_ok(sc))
9420 			rc = ENXIO;
9421 		else {
9422 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9423 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9424 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
9425 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
9426 			    &param, &val);
9427 		}
9428 		end_synchronized_op(sc, 0);
9429 		if (rc)
9430 			return (rc);
9431 		sc->params.core_vdd = val;
9432 	}
9433 
9434 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
9435 }
9436 
9437 static int
9438 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
9439 {
9440 	struct adapter *sc = arg1;
9441 	int rc, v;
9442 	uint32_t param, val;
9443 
9444 	v = sc->sensor_resets;
9445 	rc = sysctl_handle_int(oidp, &v, 0, req);
9446 	if (rc != 0 || req->newptr == NULL || v <= 0)
9447 		return (rc);
9448 
9449 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
9450 	    chip_id(sc) < CHELSIO_T5)
9451 		return (ENOTSUP);
9452 
9453 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
9454 	if (rc)
9455 		return (rc);
9456 	if (!hw_all_ok(sc))
9457 		rc = ENXIO;
9458 	else {
9459 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9460 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
9461 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
9462 		val = 1;
9463 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9464 	}
9465 	end_synchronized_op(sc, 0);
9466 	if (rc == 0)
9467 		sc->sensor_resets++;
9468 	return (rc);
9469 }
9470 
9471 static int
9472 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
9473 {
9474 	struct adapter *sc = arg1;
9475 	struct sbuf *sb;
9476 	int rc;
9477 	uint32_t param, val;
9478 	uint8_t coreid = (uint8_t)arg2;
9479 
9480 	KASSERT(coreid < sc->params.ncores,
9481 	    ("%s: bad coreid %u\n", __func__, coreid));
9482 
9483 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
9484 	if (rc)
9485 		return (rc);
9486 	if (!hw_all_ok(sc))
9487 		rc = ENXIO;
9488 	else {
9489 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
9490 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD) |
9491 		    V_FW_PARAMS_PARAM_Y(coreid);
9492 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
9493 	}
9494 	end_synchronized_op(sc, 0);
9495 	if (rc)
9496 		return (rc);
9497 
9498 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9499 	if (sb == NULL)
9500 		return (ENOMEM);
9501 
9502 	if (val == 0xffffffff) {
9503 		/* Only debug and custom firmwares report load averages. */
9504 		sbuf_printf(sb, "not available");
9505 	} else {
9506 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
9507 		    (val >> 16) & 0xff);
9508 	}
9509 	rc = sbuf_finish(sb);
9510 	sbuf_delete(sb);
9511 
9512 	return (rc);
9513 }
9514 
9515 static int
9516 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
9517 {
9518 	struct adapter *sc = arg1;
9519 	struct sbuf *sb;
9520 	int rc, i;
9521 	uint16_t incr[NMTUS][NCCTRL_WIN];
9522 	static const char *dec_fac[] = {
9523 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
9524 		"0.9375"
9525 	};
9526 
9527 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9528 	if (sb == NULL)
9529 		return (ENOMEM);
9530 
9531 	rc = 0;
9532 	mtx_lock(&sc->reg_lock);
9533 	if (hw_off_limits(sc))
9534 		rc = ENXIO;
9535 	else
9536 		t4_read_cong_tbl(sc, incr);
9537 	mtx_unlock(&sc->reg_lock);
9538 	if (rc)
9539 		goto done;
9540 
9541 	for (i = 0; i < NCCTRL_WIN; ++i) {
9542 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
9543 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
9544 		    incr[5][i], incr[6][i], incr[7][i]);
9545 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
9546 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
9547 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
9548 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
9549 	}
9550 
9551 	rc = sbuf_finish(sb);
9552 done:
9553 	sbuf_delete(sb);
9554 	return (rc);
9555 }
9556 
9557 static int
9558 sysctl_cim_ibq(SYSCTL_HANDLER_ARGS)
9559 {
9560 	struct adapter *sc = arg1;
9561 	struct sbuf *sb;
9562 	int rc, i, n, qid, coreid;
9563 	uint32_t *buf, *p;
9564 
9565 	qid = arg2 & 0xffff;
9566 	coreid = arg2 >> 16;
9567 
9568 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_ibq,
9569 	    ("%s: bad ibq qid %d\n", __func__, qid));
9570 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9571 	    ("%s: bad coreid %d\n", __func__, coreid));
9572 
9573 	n = 4 * CIM_IBQ_SIZE;
9574 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9575 	mtx_lock(&sc->reg_lock);
9576 	if (hw_off_limits(sc))
9577 		rc = -ENXIO;
9578 	else
9579 		rc = t4_read_cim_ibq_core(sc, coreid, qid, buf, n);
9580 	mtx_unlock(&sc->reg_lock);
9581 	if (rc < 0) {
9582 		rc = -rc;
9583 		goto done;
9584 	}
9585 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9586 
9587 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9588 	if (sb == NULL) {
9589 		rc = ENOMEM;
9590 		goto done;
9591 	}
9592 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9593 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9594 		    p[2], p[3]);
9595 	rc = sbuf_finish(sb);
9596 	sbuf_delete(sb);
9597 done:
9598 	free(buf, M_CXGBE);
9599 	return (rc);
9600 }
9601 
9602 static int
9603 sysctl_cim_obq(SYSCTL_HANDLER_ARGS)
9604 {
9605 	struct adapter *sc = arg1;
9606 	struct sbuf *sb;
9607 	int rc, i, n, qid, coreid;
9608 	uint32_t *buf, *p;
9609 
9610 	qid = arg2 & 0xffff;
9611 	coreid = arg2 >> 16;
9612 
9613 	KASSERT(qid >= 0 && qid < sc->chip_params->cim_num_obq,
9614 	    ("%s: bad obq qid %d\n", __func__, qid));
9615 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
9616 	    ("%s: bad coreid %d\n", __func__, coreid));
9617 
9618 	n = 6 * CIM_OBQ_SIZE * 4;
9619 	buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9620 	mtx_lock(&sc->reg_lock);
9621 	if (hw_off_limits(sc))
9622 		rc = -ENXIO;
9623 	else
9624 		rc = t4_read_cim_obq_core(sc, coreid, qid, buf, n);
9625 	mtx_unlock(&sc->reg_lock);
9626 	if (rc < 0) {
9627 		rc = -rc;
9628 		goto done;
9629 	}
9630 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9631 
9632 	rc = sysctl_wire_old_buffer(req, 0);
9633 	if (rc != 0)
9634 		goto done;
9635 
9636 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9637 	if (sb == NULL) {
9638 		rc = ENOMEM;
9639 		goto done;
9640 	}
9641 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9642 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9643 		    p[2], p[3]);
9644 	rc = sbuf_finish(sb);
9645 	sbuf_delete(sb);
9646 done:
9647 	free(buf, M_CXGBE);
9648 	return (rc);
9649 }
9650 
9651 static void
9652 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9653 {
9654 	uint32_t *p;
9655 
9656 	sbuf_printf(sb, "Status   Data      PC%s",
9657 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9658 	    "     LS0Stat  LS0Addr             LS0Data");
9659 
9660 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9661 		if (cfg & F_UPDBGLACAPTPCONLY) {
9662 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9663 			    p[6], p[7]);
9664 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9665 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9666 			    p[4] & 0xff, p[5] >> 8);
9667 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9668 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9669 			    p[1] & 0xf, p[2] >> 4);
9670 		} else {
9671 			sbuf_printf(sb,
9672 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9673 			    "%08x%08x%08x%08x",
9674 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9675 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9676 			    p[6], p[7]);
9677 		}
9678 	}
9679 }
9680 
9681 static void
9682 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9683 {
9684 	uint32_t *p;
9685 
9686 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9687 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9688 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9689 
9690 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9691 		if (cfg & F_UPDBGLACAPTPCONLY) {
9692 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9693 			    p[3] & 0xff, p[2], p[1], p[0]);
9694 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9695 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9696 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9697 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9698 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9699 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9700 			    p[6] >> 16);
9701 		} else {
9702 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9703 			    "%08x %08x %08x %08x %08x %08x",
9704 			    (p[9] >> 16) & 0xff,
9705 			    p[9] & 0xffff, p[8] >> 16,
9706 			    p[8] & 0xffff, p[7] >> 16,
9707 			    p[7] & 0xffff, p[6] >> 16,
9708 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9709 		}
9710 	}
9711 }
9712 
9713 static int
9714 sbuf_cim_la(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
9715 {
9716 	uint32_t cfg, *buf;
9717 	int rc;
9718 
9719 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9720 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9721 	    M_ZERO | flags);
9722 	if (buf == NULL)
9723 		return (ENOMEM);
9724 
9725 	mtx_lock(&sc->reg_lock);
9726 	if (hw_off_limits(sc))
9727 		rc = ENXIO;
9728 	else {
9729 		rc = -t4_cim_read_core(sc, 1, coreid, A_UP_UP_DBG_LA_CFG, 1,
9730 		    &cfg);
9731 		if (rc == 0)
9732 			rc = -t4_cim_read_la_core(sc, coreid, buf, NULL);
9733 	}
9734 	mtx_unlock(&sc->reg_lock);
9735 	if (rc == 0) {
9736 		if (chip_id(sc) < CHELSIO_T6)
9737 			sbuf_cim_la4(sc, sb, buf, cfg);
9738 		else
9739 			sbuf_cim_la6(sc, sb, buf, cfg);
9740 	}
9741 	free(buf, M_CXGBE);
9742 	return (rc);
9743 }
9744 
9745 static int
9746 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9747 {
9748 	struct adapter *sc = arg1;
9749 	int coreid = arg2;
9750 	struct sbuf *sb;
9751 	int rc;
9752 
9753 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9754 	if (sb == NULL)
9755 		return (ENOMEM);
9756 
9757 	rc = sbuf_cim_la(sc, coreid, sb, M_WAITOK);
9758 	if (rc == 0)
9759 		rc = sbuf_finish(sb);
9760 	sbuf_delete(sb);
9761 	return (rc);
9762 }
9763 
9764 static void
9765 dump_cim_regs(struct adapter *sc)
9766 {
9767 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9768 	    device_get_nameunit(sc->dev),
9769 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9770 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9771 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9772 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9773 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9774 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9775 	    device_get_nameunit(sc->dev),
9776 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9777 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9778 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9779 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9780 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9781 }
9782 
9783 static void
9784 dump_cimla(struct adapter *sc)
9785 {
9786 	struct sbuf sb;
9787 	int rc;
9788 
9789 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9790 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9791 		    device_get_nameunit(sc->dev));
9792 		return;
9793 	}
9794 	rc = sbuf_cim_la(sc, 0, &sb, M_WAITOK);
9795 	if (rc == 0) {
9796 		rc = sbuf_finish(&sb);
9797 		if (rc == 0) {
9798 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9799 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9800 		}
9801 	}
9802 	sbuf_delete(&sb);
9803 }
9804 
9805 void
9806 t4_os_cim_err(struct adapter *sc)
9807 {
9808 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9809 }
9810 
9811 static int
9812 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9813 {
9814 	struct adapter *sc = arg1;
9815 	u_int i;
9816 	struct sbuf *sb;
9817 	uint32_t *buf, *p;
9818 	int rc;
9819 
9820 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9821 	if (sb == NULL)
9822 		return (ENOMEM);
9823 
9824 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9825 	    M_ZERO | M_WAITOK);
9826 
9827 	rc = 0;
9828 	mtx_lock(&sc->reg_lock);
9829 	if (hw_off_limits(sc))
9830 		rc = ENXIO;
9831 	else
9832 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9833 	mtx_unlock(&sc->reg_lock);
9834 	if (rc)
9835 		goto done;
9836 
9837 	p = buf;
9838 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9839 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9840 		    p[1], p[0]);
9841 	}
9842 
9843 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9844 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9845 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9846 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9847 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9848 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9849 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9850 		    p[0] & 1);
9851 	}
9852 	rc = sbuf_finish(sb);
9853 done:
9854 	sbuf_delete(sb);
9855 	free(buf, M_CXGBE);
9856 	return (rc);
9857 }
9858 
9859 static int
9860 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9861 {
9862 	struct adapter *sc = arg1;
9863 	u_int i;
9864 	struct sbuf *sb;
9865 	uint32_t *buf, *p;
9866 	int rc;
9867 
9868 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9869 	if (sb == NULL)
9870 		return (ENOMEM);
9871 
9872 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9873 	    M_ZERO | M_WAITOK);
9874 
9875 	rc = 0;
9876 	mtx_lock(&sc->reg_lock);
9877 	if (hw_off_limits(sc))
9878 		rc = ENXIO;
9879 	else
9880 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9881 	mtx_unlock(&sc->reg_lock);
9882 	if (rc)
9883 		goto done;
9884 
9885 	p = buf;
9886 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9887 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9888 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9889 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9890 		    p[4], p[3], p[2], p[1], p[0]);
9891 	}
9892 
9893 	sbuf_printf(sb, "\n\nCntl ID               Data");
9894 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9895 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9896 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9897 	}
9898 
9899 	rc = sbuf_finish(sb);
9900 done:
9901 	sbuf_delete(sb);
9902 	free(buf, M_CXGBE);
9903 	return (rc);
9904 }
9905 
9906 static int
9907 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9908 {
9909 	struct adapter *sc = arg1;
9910 	struct sbuf *sb;
9911 	int rc, i;
9912 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9913 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9914 	uint16_t thres[CIM_NUM_IBQ];
9915 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9916 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9917 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9918 	static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
9919 		"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
9920 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
9921 		"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
9922 	};
9923 
9924 	MPASS(chip_id(sc) < CHELSIO_T7);
9925 
9926 	cim_num_obq = sc->chip_params->cim_num_obq;
9927 	if (is_t4(sc)) {
9928 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9929 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9930 	} else {
9931 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9932 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9933 	}
9934 	nq = CIM_NUM_IBQ + cim_num_obq;
9935 
9936 	mtx_lock(&sc->reg_lock);
9937 	if (hw_off_limits(sc))
9938 		rc = ENXIO;
9939 	else {
9940 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9941 		if (rc == 0) {
9942 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9943 			    obq_wr);
9944 			if (rc == 0)
9945 				t4_read_cimq_cfg(sc, base, size, thres);
9946 		}
9947 	}
9948 	mtx_unlock(&sc->reg_lock);
9949 	if (rc)
9950 		return (rc);
9951 
9952 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9953 	if (sb == NULL)
9954 		return (ENOMEM);
9955 
9956 	sbuf_printf(sb,
9957 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9958 
9959 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9960 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9961 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9962 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9963 		    G_QUEREMFLITS(p[2]) * 16);
9964 	for ( ; i < nq; i++, p += 4, wr += 2)
9965 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9966 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9967 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9968 		    G_QUEREMFLITS(p[2]) * 16);
9969 
9970 	rc = sbuf_finish(sb);
9971 	sbuf_delete(sb);
9972 
9973 	return (rc);
9974 }
9975 
9976 static int
9977 sysctl_cim_qcfg_t7(SYSCTL_HANDLER_ARGS)
9978 {
9979 	struct adapter *sc = arg1;
9980 	u_int coreid = arg2;
9981 	struct sbuf *sb;
9982 	int rc, i;
9983 	u_int addr;
9984 	uint16_t base[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9985 	uint16_t size[CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7];
9986 	uint16_t thres[CIM_NUM_IBQ_T7];
9987 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T7], *wr = obq_wr;
9988 	uint32_t stat[4 * (CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7)], *p = stat;
9989 	static const char * const qname_ibq_t7[] = {
9990 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "SGE1", "NC-SI",
9991 		"RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5", "IPC6", "IPC7",
9992 	};
9993 	static const char * const qname_obq_t7[] = {
9994 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI", "SGE0-RX",
9995 		"RSVD", "RSVD", "IPC1", "IPC2", "IPC3", "IPC4", "IPC5",
9996 		"IPC6", "IPC7"
9997 	};
9998 	static const char * const qname_ibq_sec_t7[] = {
9999 		"TP0", "TP1", "TP2", "TP3", "ULP", "SGE0", "RSVD", "RSVD",
10000 		"RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",	"RSVD", "RSVD",
10001 	};
10002 	static const char * const qname_obq_sec_t7[] = {
10003 		"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "RSVD", "SGE0-RX",
10004 		"RSVD", "RSVD", "IPC0", "RSVD", "RSVD", "RSVD", "RSVD",
10005 		"RSVD", "RSVD",
10006 	};
10007 
10008 	MPASS(chip_id(sc) >= CHELSIO_T7);
10009 
10010 	mtx_lock(&sc->reg_lock);
10011 	if (hw_off_limits(sc))
10012 		rc = ENXIO;
10013 	else {
10014 		rc = -t4_cim_read_core(sc, 1, coreid,
10015 		    A_T7_UP_IBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_IBQ_T7, stat);
10016 		if (rc != 0)
10017 			goto unlock;
10018 
10019 		rc = -t4_cim_read_core(sc, 1, coreid,
10020 		    A_T7_UP_OBQ_0_SHADOW_RDADDR, 4 * CIM_NUM_OBQ_T7,
10021 		    &stat[4 * CIM_NUM_IBQ_T7]);
10022 		if (rc != 0)
10023 			goto unlock;
10024 
10025 		addr = A_T7_UP_OBQ_0_SHADOW_REALADDR;
10026 		for (i = 0; i < CIM_NUM_OBQ_T7 * 2; i++, addr += 8) {
10027 			rc = -t4_cim_read_core(sc, 1, coreid, addr, 1,
10028 			    &obq_wr[i]);
10029 			if (rc != 0)
10030 				goto unlock;
10031 		}
10032 		t4_read_cimq_cfg_core(sc, coreid, base, size, thres);
10033 	}
10034 unlock:
10035 	mtx_unlock(&sc->reg_lock);
10036 	if (rc)
10037 		return (rc);
10038 
10039 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
10040 	if (sb == NULL)
10041 		return (ENOMEM);
10042 
10043 	sbuf_printf(sb,
10044 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
10045 
10046 	for (i = 0; i < CIM_NUM_IBQ_T7; i++, p += 4) {
10047 		if (!size[i])
10048 			continue;
10049 
10050 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
10051 		    coreid == 0 ? qname_ibq_t7[i] : qname_ibq_sec_t7[i],
10052 		    base[i], size[i], thres[i], G_IBQRDADDR(p[0]) & 0xfff,
10053 		    G_IBQWRADDR(p[1]) & 0xfff, G_QUESOPCNT(p[3]),
10054 		    G_QUEEOPCNT(p[3]), G_T7_QUEREMFLITS(p[2]) * 16);
10055 	}
10056 
10057 	for ( ; i < CIM_NUM_IBQ_T7 + CIM_NUM_OBQ_T7; i++, p += 4, wr += 2) {
10058 		if (!size[i])
10059 			continue;
10060 
10061 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u",
10062 		    coreid == 0 ? qname_obq_t7[i - CIM_NUM_IBQ_T7] :
10063 		    qname_obq_sec_t7[i - CIM_NUM_IBQ_T7],
10064 		    base[i], size[i], G_QUERDADDR(p[0]) & 0xfff,
10065 		    wr[0] << 1, G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
10066 		    G_T7_QUEREMFLITS(p[2]) * 16);
10067 	}
10068 
10069 	rc = sbuf_finish(sb);
10070 	sbuf_delete(sb);
10071 	return (rc);
10072 }
10073 
10074 static int
10075 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
10076 {
10077 	struct adapter *sc = arg1;
10078 	struct sbuf *sb;
10079 	int rc;
10080 	struct tp_cpl_stats stats;
10081 
10082 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10083 	if (sb == NULL)
10084 		return (ENOMEM);
10085 
10086 	rc = 0;
10087 	mtx_lock(&sc->reg_lock);
10088 	if (hw_off_limits(sc))
10089 		rc = ENXIO;
10090 	else
10091 		t4_tp_get_cpl_stats(sc, &stats, 0);
10092 	mtx_unlock(&sc->reg_lock);
10093 	if (rc)
10094 		goto done;
10095 
10096 	if (sc->chip_params->nchan > 2) {
10097 		sbuf_printf(sb, "                 channel 0  channel 1"
10098 		    "  channel 2  channel 3");
10099 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
10100 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
10101 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
10102 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
10103 	} else {
10104 		sbuf_printf(sb, "                 channel 0  channel 1");
10105 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
10106 		    stats.req[0], stats.req[1]);
10107 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
10108 		    stats.rsp[0], stats.rsp[1]);
10109 	}
10110 
10111 	rc = sbuf_finish(sb);
10112 done:
10113 	sbuf_delete(sb);
10114 	return (rc);
10115 }
10116 
10117 static int
10118 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
10119 {
10120 	struct adapter *sc = arg1;
10121 	struct sbuf *sb;
10122 	int rc;
10123 	struct tp_usm_stats stats;
10124 
10125 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10126 	if (sb == NULL)
10127 		return (ENOMEM);
10128 
10129 	rc = 0;
10130 	mtx_lock(&sc->reg_lock);
10131 	if (hw_off_limits(sc))
10132 		rc = ENXIO;
10133 	else
10134 		t4_get_usm_stats(sc, &stats, 1);
10135 	mtx_unlock(&sc->reg_lock);
10136 	if (rc == 0) {
10137 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
10138 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
10139 		sbuf_printf(sb, "Drops:  %u", stats.drops);
10140 		rc = sbuf_finish(sb);
10141 	}
10142 	sbuf_delete(sb);
10143 
10144 	return (rc);
10145 }
10146 
10147 static int
10148 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
10149 {
10150 	struct adapter *sc = arg1;
10151 	struct sbuf *sb;
10152 	int rc;
10153 	struct tp_tid_stats stats;
10154 
10155 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10156 	if (sb == NULL)
10157 		return (ENOMEM);
10158 
10159 	rc = 0;
10160 	mtx_lock(&sc->reg_lock);
10161 	if (hw_off_limits(sc))
10162 		rc = ENXIO;
10163 	else
10164 		t4_tp_get_tid_stats(sc, &stats, 1);
10165 	mtx_unlock(&sc->reg_lock);
10166 	if (rc == 0) {
10167 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
10168 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
10169 		sbuf_printf(sb, "Active:     %u\n", stats.act);
10170 		sbuf_printf(sb, "Passive:    %u", stats.pas);
10171 		rc = sbuf_finish(sb);
10172 	}
10173 	sbuf_delete(sb);
10174 
10175 	return (rc);
10176 }
10177 
10178 static const char * const devlog_level_strings[] = {
10179 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
10180 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
10181 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
10182 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
10183 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
10184 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
10185 };
10186 
10187 static const char * const devlog_facility_strings[] = {
10188 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
10189 	[FW_DEVLOG_FACILITY_CF]		= "CF",
10190 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
10191 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
10192 	[FW_DEVLOG_FACILITY_RES]	= "RES",
10193 	[FW_DEVLOG_FACILITY_HW]		= "HW",
10194 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
10195 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
10196 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
10197 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
10198 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
10199 	[FW_DEVLOG_FACILITY_VI]		= "VI",
10200 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
10201 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
10202 	[FW_DEVLOG_FACILITY_TM]		= "TM",
10203 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
10204 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
10205 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
10206 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
10207 	[FW_DEVLOG_FACILITY_RI]		= "RI",
10208 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
10209 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
10210 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
10211 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
10212 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
10213 };
10214 
10215 static int
10216 sbuf_devlog(struct adapter *sc, int coreid, struct sbuf *sb, int flags)
10217 {
10218 	int i, j, rc, nentries, first = 0;
10219 	struct devlog_params *dparams = &sc->params.devlog;
10220 	struct fw_devlog_e *buf, *e;
10221 	uint32_t addr, size;
10222 	uint64_t ftstamp = UINT64_MAX;
10223 
10224 	KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10225 	    ("%s: bad coreid %d\n", __func__, coreid));
10226 
10227 	if (dparams->addr == 0)
10228 		return (ENXIO);
10229 
10230 	size = dparams->size / sc->params.ncores;
10231 	addr = dparams->addr + coreid * size;
10232 
10233 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
10234 	buf = malloc(size, M_CXGBE, M_ZERO | flags);
10235 	if (buf == NULL)
10236 		return (ENOMEM);
10237 
10238 	mtx_lock(&sc->reg_lock);
10239 	if (hw_off_limits(sc))
10240 		rc = ENXIO;
10241 	else
10242 		rc = read_via_memwin(sc, 1, addr, (void *)buf, size);
10243 	mtx_unlock(&sc->reg_lock);
10244 	if (rc != 0)
10245 		goto done;
10246 
10247 	nentries = size / sizeof(struct fw_devlog_e);
10248 	for (i = 0; i < nentries; i++) {
10249 		e = &buf[i];
10250 
10251 		if (e->timestamp == 0)
10252 			break;	/* end */
10253 
10254 		e->timestamp = be64toh(e->timestamp);
10255 		e->seqno = be32toh(e->seqno);
10256 		for (j = 0; j < 8; j++)
10257 			e->params[j] = be32toh(e->params[j]);
10258 
10259 		if (e->timestamp < ftstamp) {
10260 			ftstamp = e->timestamp;
10261 			first = i;
10262 		}
10263 	}
10264 
10265 	if (buf[first].timestamp == 0)
10266 		goto done;	/* nothing in the log */
10267 
10268 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
10269 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
10270 
10271 	i = first;
10272 	do {
10273 		e = &buf[i];
10274 		if (e->timestamp == 0)
10275 			break;	/* end */
10276 
10277 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
10278 		    e->seqno, e->timestamp,
10279 		    (e->level < nitems(devlog_level_strings) ?
10280 			devlog_level_strings[e->level] : "UNKNOWN"),
10281 		    (e->facility < nitems(devlog_facility_strings) ?
10282 			devlog_facility_strings[e->facility] : "UNKNOWN"));
10283 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
10284 		    e->params[2], e->params[3], e->params[4],
10285 		    e->params[5], e->params[6], e->params[7]);
10286 
10287 		if (++i == nentries)
10288 			i = 0;
10289 	} while (i != first);
10290 done:
10291 	free(buf, M_CXGBE);
10292 	return (rc);
10293 }
10294 
10295 static int
10296 sysctl_devlog(SYSCTL_HANDLER_ARGS)
10297 {
10298 	struct adapter *sc = arg1;
10299 	int rc, i, coreid = arg2;
10300 	struct sbuf *sb;
10301 
10302 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10303 	if (sb == NULL)
10304 		return (ENOMEM);
10305 	if (coreid == -1) {
10306 		/* -1 means all cores */
10307 		for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10308 			if (sc->params.ncores > 0)
10309 				sbuf_printf(sb, "=== CIM core %u ===\n", i);
10310 			rc = sbuf_devlog(sc, i, sb, M_WAITOK);
10311 		}
10312 	} else {
10313 		KASSERT(coreid >= 0 && coreid < sc->params.ncores,
10314 		    ("%s: bad coreid %d\n", __func__, coreid));
10315 		rc = sbuf_devlog(sc, coreid, sb, M_WAITOK);
10316 	}
10317 	if (rc == 0)
10318 		rc = sbuf_finish(sb);
10319 	sbuf_delete(sb);
10320 	return (rc);
10321 }
10322 
10323 static void
10324 dump_devlog(struct adapter *sc)
10325 {
10326 	int rc, i;
10327 	struct sbuf sb;
10328 
10329 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
10330 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
10331 		    device_get_nameunit(sc->dev));
10332 		return;
10333 	}
10334 	for (i = rc = 0; i < sc->params.ncores && rc == 0; i++) {
10335 		if (sc->params.ncores > 0)
10336 			sbuf_printf(&sb, "=== CIM core %u ===\n", i);
10337 		rc = sbuf_devlog(sc, i, &sb, M_WAITOK);
10338 	}
10339 	if (rc == 0) {
10340 		sbuf_finish(&sb);
10341 		log(LOG_DEBUG, "%s: device log follows.\n%s",
10342 		    device_get_nameunit(sc->dev), sbuf_data(&sb));
10343 	}
10344 	sbuf_delete(&sb);
10345 }
10346 
10347 static int
10348 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
10349 {
10350 	struct adapter *sc = arg1;
10351 	struct sbuf *sb;
10352 	int rc;
10353 	struct tp_fcoe_stats stats[MAX_NCHAN];
10354 	int i, nchan = sc->chip_params->nchan;
10355 
10356 	rc = 0;
10357 	mtx_lock(&sc->reg_lock);
10358 	if (hw_off_limits(sc))
10359 		rc = ENXIO;
10360 	else {
10361 		for (i = 0; i < nchan; i++)
10362 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
10363 	}
10364 	mtx_unlock(&sc->reg_lock);
10365 	if (rc != 0)
10366 		return (rc);
10367 
10368 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10369 	if (sb == NULL)
10370 		return (ENOMEM);
10371 
10372 	if (nchan > 2) {
10373 		sbuf_printf(sb, "                   channel 0        channel 1"
10374 		    "        channel 2        channel 3");
10375 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
10376 		    stats[0].octets_ddp, stats[1].octets_ddp,
10377 		    stats[2].octets_ddp, stats[3].octets_ddp);
10378 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
10379 		    stats[0].frames_ddp, stats[1].frames_ddp,
10380 		    stats[2].frames_ddp, stats[3].frames_ddp);
10381 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
10382 		    stats[0].frames_drop, stats[1].frames_drop,
10383 		    stats[2].frames_drop, stats[3].frames_drop);
10384 	} else {
10385 		sbuf_printf(sb, "                   channel 0        channel 1");
10386 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
10387 		    stats[0].octets_ddp, stats[1].octets_ddp);
10388 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
10389 		    stats[0].frames_ddp, stats[1].frames_ddp);
10390 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
10391 		    stats[0].frames_drop, stats[1].frames_drop);
10392 	}
10393 
10394 	rc = sbuf_finish(sb);
10395 	sbuf_delete(sb);
10396 
10397 	return (rc);
10398 }
10399 
10400 static int
10401 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
10402 {
10403 	struct adapter *sc = arg1;
10404 	struct sbuf *sb;
10405 	int rc, i;
10406 	unsigned int map, kbps, ipg, mode;
10407 	unsigned int pace_tab[NTX_SCHED];
10408 
10409 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
10410 	if (sb == NULL)
10411 		return (ENOMEM);
10412 
10413 	mtx_lock(&sc->reg_lock);
10414 	if (hw_off_limits(sc)) {
10415 		mtx_unlock(&sc->reg_lock);
10416 		rc = ENXIO;
10417 		goto done;
10418 	}
10419 
10420 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
10421 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
10422 	t4_read_pace_tbl(sc, pace_tab);
10423 	mtx_unlock(&sc->reg_lock);
10424 
10425 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
10426 	    "Class IPG (0.1 ns)   Flow IPG (us)");
10427 
10428 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
10429 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
10430 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
10431 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
10432 		if (kbps)
10433 			sbuf_printf(sb, "%9u     ", kbps);
10434 		else
10435 			sbuf_printf(sb, " disabled     ");
10436 
10437 		if (ipg)
10438 			sbuf_printf(sb, "%13u        ", ipg);
10439 		else
10440 			sbuf_printf(sb, "     disabled        ");
10441 
10442 		if (pace_tab[i])
10443 			sbuf_printf(sb, "%10u", pace_tab[i]);
10444 		else
10445 			sbuf_printf(sb, "  disabled");
10446 	}
10447 	rc = sbuf_finish(sb);
10448 done:
10449 	sbuf_delete(sb);
10450 	return (rc);
10451 }
10452 
10453 static int
10454 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
10455 {
10456 	struct adapter *sc = arg1;
10457 	struct sbuf *sb;
10458 	int rc, i, j;
10459 	uint64_t *p0, *p1;
10460 	struct lb_port_stats s[2];
10461 	static const char *stat_name[] = {
10462 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
10463 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
10464 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
10465 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
10466 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
10467 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
10468 		"BG2FramesTrunc:", "BG3FramesTrunc:"
10469 	};
10470 
10471 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10472 	if (sb == NULL)
10473 		return (ENOMEM);
10474 
10475 	memset(s, 0, sizeof(s));
10476 
10477 	rc = 0;
10478 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
10479 		mtx_lock(&sc->reg_lock);
10480 		if (hw_off_limits(sc))
10481 			rc = ENXIO;
10482 		else {
10483 			t4_get_lb_stats(sc, i, &s[0]);
10484 			t4_get_lb_stats(sc, i + 1, &s[1]);
10485 		}
10486 		mtx_unlock(&sc->reg_lock);
10487 		if (rc != 0)
10488 			break;
10489 
10490 		p0 = &s[0].octets;
10491 		p1 = &s[1].octets;
10492 		sbuf_printf(sb, "%s                       Loopback %u"
10493 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
10494 
10495 		for (j = 0; j < nitems(stat_name); j++)
10496 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
10497 				   *p0++, *p1++);
10498 	}
10499 
10500 	if (rc == 0)
10501 		rc = sbuf_finish(sb);
10502 	sbuf_delete(sb);
10503 
10504 	return (rc);
10505 }
10506 
10507 static int
10508 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
10509 {
10510 	int rc = 0;
10511 	struct port_info *pi = arg1;
10512 	struct link_config *lc = &pi->link_cfg;
10513 	struct sbuf *sb;
10514 
10515 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
10516 	if (sb == NULL)
10517 		return (ENOMEM);
10518 
10519 	if (lc->link_ok || lc->link_down_rc == 255)
10520 		sbuf_printf(sb, "n/a");
10521 	else
10522 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
10523 
10524 	rc = sbuf_finish(sb);
10525 	sbuf_delete(sb);
10526 
10527 	return (rc);
10528 }
10529 
10530 struct mem_desc {
10531 	uint64_t base;
10532 	uint64_t limit;
10533 	u_int idx;
10534 };
10535 
10536 static int
10537 mem_desc_cmp(const void *a, const void *b)
10538 {
10539 	const uint64_t v1 = ((const struct mem_desc *)a)->base;
10540 	const uint64_t v2 = ((const struct mem_desc *)b)->base;
10541 
10542 	if (v1 < v2)
10543 		return (-1);
10544 	else if (v1 > v2)
10545 		return (1);
10546 
10547 	return (0);
10548 }
10549 
10550 static void
10551 mem_region_show(struct sbuf *sb, const char *name, uint64_t from, uint64_t to)
10552 {
10553 	uintmax_t size;
10554 
10555 	if (from == to)
10556 		return;
10557 
10558 	size = to - from + 1;
10559 	if (size == 0)
10560 		return;
10561 
10562 	if (from > UINT32_MAX || to > UINT32_MAX)
10563 		sbuf_printf(sb, "%-18s 0x%012jx-0x%012jx [%ju]\n", name,
10564 		    (uintmax_t)from, (uintmax_t)to, size);
10565 	else
10566 		sbuf_printf(sb, "%-18s 0x%08jx-0x%08jx [%ju]\n", name,
10567 		    (uintmax_t)from, (uintmax_t)to, size);
10568 }
10569 
10570 static int
10571 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
10572 {
10573 	struct adapter *sc = arg1;
10574 	struct sbuf *sb;
10575 	int rc, i, n, nchan;
10576 	uint32_t lo, hi, used, free, alloc;
10577 	static const char *memory[] = {
10578 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
10579 	};
10580 	static const char *region[] = {
10581 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
10582 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
10583 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
10584 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
10585 		"RQUDP region:", "PBL region:", "TXPBL region:",
10586 		"TLSKey region:", "RRQ region:", "NVMe STAG region:",
10587 		"NVMe RQ region:", "NVMe RXPBL region:", "NVMe TPT region:",
10588 		"NVMe TXPBL region:", "DBVFIFO region:", "ULPRX state:",
10589 		"ULPTX state:", "RoCE RRQ region:", "On-chip queues:",
10590 	};
10591 	struct mem_desc avail[4];
10592 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
10593 	struct mem_desc *md;
10594 
10595 	rc = sysctl_wire_old_buffer(req, 0);
10596 	if (rc != 0)
10597 		return (rc);
10598 
10599 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10600 	if (sb == NULL)
10601 		return (ENOMEM);
10602 
10603 	for (i = 0; i < nitems(mem); i++) {
10604 		mem[i].limit = 0;
10605 		mem[i].idx = i;
10606 	}
10607 
10608 	mtx_lock(&sc->reg_lock);
10609 	if (hw_off_limits(sc)) {
10610 		rc = ENXIO;
10611 		goto done;
10612 	}
10613 
10614 	/* Find and sort the populated memory ranges */
10615 	i = 0;
10616 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
10617 	if (lo & F_EDRAM0_ENABLE) {
10618 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
10619 		if (chip_id(sc) >= CHELSIO_T7) {
10620 			avail[i].base = (uint64_t)G_T7_EDRAM0_BASE(hi) << 20;
10621 			avail[i].limit = avail[i].base +
10622 			    (G_T7_EDRAM0_SIZE(hi) << 20);
10623 		} else {
10624 			avail[i].base = (uint64_t)G_EDRAM0_BASE(hi) << 20;
10625 			avail[i].limit = avail[i].base +
10626 			    (G_EDRAM0_SIZE(hi) << 20);
10627 		}
10628 		avail[i].idx = 0;
10629 		i++;
10630 	}
10631 	if (lo & F_EDRAM1_ENABLE) {
10632 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
10633 		if (chip_id(sc) >= CHELSIO_T7) {
10634 			avail[i].base = (uint64_t)G_T7_EDRAM1_BASE(hi) << 20;
10635 			avail[i].limit = avail[i].base +
10636 			    (G_T7_EDRAM1_SIZE(hi) << 20);
10637 		} else {
10638 			avail[i].base = (uint64_t)G_EDRAM1_BASE(hi) << 20;
10639 			avail[i].limit = avail[i].base +
10640 			    (G_EDRAM1_SIZE(hi) << 20);
10641 		}
10642 		avail[i].idx = 1;
10643 		i++;
10644 	}
10645 	if (lo & F_EXT_MEM_ENABLE) {
10646 		switch (chip_id(sc)) {
10647 		case CHELSIO_T4:
10648 		case CHELSIO_T6:
10649 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
10650 			avail[i].base = (uint64_t)G_EXT_MEM_BASE(hi) << 20;
10651 			avail[i].limit = avail[i].base +
10652 			    (G_EXT_MEM_SIZE(hi) << 20);
10653 			avail[i].idx = 2;
10654 			break;
10655 		case CHELSIO_T5:
10656 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10657 			avail[i].base = (uint64_t)G_EXT_MEM0_BASE(hi) << 20;
10658 			avail[i].limit = avail[i].base +
10659 			    (G_EXT_MEM0_SIZE(hi) << 20);
10660 			avail[i].idx = 3;	/* Call it MC0 for T5 */
10661 			break;
10662 		default:
10663 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY0_BAR);
10664 			avail[i].base = (uint64_t)G_T7_EXT_MEM0_BASE(hi) << 20;
10665 			avail[i].limit = avail[i].base +
10666 			    (G_T7_EXT_MEM0_SIZE(hi) << 20);
10667 			avail[i].idx = 3;	/* Call it MC0 for T7+ */
10668 			break;
10669 		}
10670 		i++;
10671 	}
10672 	if (lo & F_EXT_MEM1_ENABLE && !(lo & F_MC_SPLIT)) {
10673 		/* Only T5 and T7+ have 2 MCs. */
10674 		MPASS(is_t5(sc) || chip_id(sc) >= CHELSIO_T7);
10675 
10676 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10677 		if (chip_id(sc) >= CHELSIO_T7) {
10678 			avail[i].base = (uint64_t)G_T7_EXT_MEM1_BASE(hi) << 20;
10679 			avail[i].limit = avail[i].base +
10680 			    (G_T7_EXT_MEM1_SIZE(hi) << 20);
10681 		} else {
10682 			avail[i].base = (uint64_t)G_EXT_MEM1_BASE(hi) << 20;
10683 			avail[i].limit = avail[i].base +
10684 			    (G_EXT_MEM1_SIZE(hi) << 20);
10685 		}
10686 		avail[i].idx = 4;
10687 		i++;
10688 	}
10689 	if (lo & F_HMA_MUX) {
10690 		/* Only T6+ have HMA. */
10691 		MPASS(chip_id(sc) >= CHELSIO_T6);
10692 
10693 		if (chip_id(sc) >= CHELSIO_T7) {
10694 			hi = t4_read_reg(sc, A_MA_HOST_MEMORY_BAR);
10695 			avail[i].base = (uint64_t)G_HMATARGETBASE(hi) << 20;
10696 			avail[i].limit = avail[i].base +
10697 			    (G_T7_HMA_SIZE(hi) << 20);
10698 		} else {
10699 			hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
10700 			avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
10701 			avail[i].limit = avail[i].base +
10702 			    (G_EXT_MEM1_SIZE(hi) << 20);
10703 		}
10704 		avail[i].idx = 5;
10705 		i++;
10706 	}
10707 	MPASS(i <= nitems(avail));
10708 	if (!i)                                    /* no memory available */
10709 		goto done;
10710 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
10711 
10712 	md = &mem[0];
10713 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
10714 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
10715 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
10716 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
10717 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
10718 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
10719 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
10720 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
10721 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
10722 
10723 	/* the next few have explicit upper bounds */
10724 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
10725 	md->limit = md->base - 1 +
10726 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
10727 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
10728 	md++;
10729 
10730 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
10731 	md->limit = md->base - 1 +
10732 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
10733 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
10734 	md++;
10735 
10736 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10737 		if (chip_id(sc) <= CHELSIO_T5)
10738 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
10739 		else
10740 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
10741 		md->limit = 0;
10742 	} else {
10743 		md->base = 0;
10744 		md->idx = nitems(region);  /* hide it */
10745 	}
10746 	md++;
10747 
10748 #define ulp_region(reg) do {\
10749 		const u_int shift = chip_id(sc) >= CHELSIO_T7 ? 4 : 0; \
10750 		md->base = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT) << shift; \
10751 		md->limit = (uint64_t)t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT) << shift; \
10752 		md->limit += (1 << shift) - 1; \
10753 		md++; \
10754 	} while (0)
10755 
10756 #define	hide_ulp_region() do { \
10757 		md->base = 0; \
10758 		md->idx = nitems(region); \
10759 		md++; \
10760 	} while (0)
10761 
10762 	ulp_region(RX_ISCSI);
10763 	ulp_region(RX_TDDP);
10764 	ulp_region(TX_TPT);
10765 	ulp_region(RX_STAG);
10766 	ulp_region(RX_RQ);
10767 	if (chip_id(sc) < CHELSIO_T7)
10768 		ulp_region(RX_RQUDP);
10769 	else
10770 		hide_ulp_region();
10771 	ulp_region(RX_PBL);
10772 	ulp_region(TX_PBL);
10773 	if (chip_id(sc) >= CHELSIO_T6)
10774 		ulp_region(RX_TLS_KEY);
10775 	else
10776 		hide_ulp_region();
10777 	if (chip_id(sc) >= CHELSIO_T7) {
10778 		ulp_region(RX_RRQ);
10779 		ulp_region(RX_NVME_TCP_STAG);
10780 		ulp_region(RX_NVME_TCP_RQ);
10781 		ulp_region(RX_NVME_TCP_PBL);
10782 		ulp_region(TX_NVME_TCP_TPT);
10783 		ulp_region(TX_NVME_TCP_PBL);
10784 	} else {
10785 		hide_ulp_region();
10786 		hide_ulp_region();
10787 		hide_ulp_region();
10788 		hide_ulp_region();
10789 		hide_ulp_region();
10790 		hide_ulp_region();
10791 	}
10792 #undef ulp_region
10793 #undef hide_ulp_region
10794 
10795 	md->base = 0;
10796 	if (is_t4(sc))
10797 		md->idx = nitems(region);
10798 	else {
10799 		uint32_t size = 0;
10800 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
10801 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
10802 
10803 		if (is_t5(sc)) {
10804 			if (sge_ctrl & F_VFIFO_ENABLE)
10805 				size = fifo_size << 2;
10806 		} else
10807 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
10808 
10809 		if (size) {
10810 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10811 			md->limit = md->base + size - 1;
10812 		} else
10813 			md->idx = nitems(region);
10814 	}
10815 	md++;
10816 
10817 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10818 	md->limit = 0;
10819 	md++;
10820 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10821 	md->limit = 0;
10822 	md++;
10823 
10824 	if (chip_id(sc) >= CHELSIO_T7) {
10825 		t4_tp_pio_read(sc, &lo, 1, A_TP_ROCE_RRQ_BASE, false);
10826 		md->base = lo;
10827 	} else {
10828 		md->base = 0;
10829 		md->idx = nitems(region);
10830 	}
10831 	md++;
10832 
10833 	md->base = sc->vres.ocq.start;
10834 	if (sc->vres.ocq.size)
10835 		md->limit = md->base + sc->vres.ocq.size - 1;
10836 	else
10837 		md->idx = nitems(region);  /* hide it */
10838 	md++;
10839 
10840 	/* add any address-space holes, there can be up to 3 */
10841 	for (n = 0; n < i - 1; n++)
10842 		if (avail[n].limit < avail[n + 1].base)
10843 			(md++)->base = avail[n].limit;
10844 	if (avail[n].limit)
10845 		(md++)->base = avail[n].limit;
10846 
10847 	n = md - mem;
10848 	MPASS(n <= nitems(mem));
10849 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10850 
10851 	for (lo = 0; lo < i; lo++)
10852 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10853 				avail[lo].limit - 1);
10854 
10855 	sbuf_printf(sb, "\n");
10856 	for (i = 0; i < n; i++) {
10857 		if (mem[i].idx >= nitems(region))
10858 			continue;                        /* skip holes */
10859 		if (!mem[i].limit)
10860 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10861 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10862 				mem[i].limit);
10863 	}
10864 
10865 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10866 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10867 	if (hi != lo  - 1) {
10868 		sbuf_printf(sb, "\n");
10869 		mem_region_show(sb, "uP RAM:", lo, hi);
10870 	}
10871 
10872 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10873 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10874 	if (hi != lo  - 1)
10875 		mem_region_show(sb, "uP Extmem2:", lo, hi);
10876 
10877 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10878 	if (chip_id(sc) >= CHELSIO_T7)
10879 		nchan = 1 << G_T7_PMRXNUMCHN(lo);
10880 	else
10881 		nchan = lo & F_PMRXNUMCHN ? 2 : 1;
10882 	for (i = 0, free = 0; i < nchan; i++)
10883 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10884 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10885 		   G_PMRXMAXPAGE(lo), free,
10886 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10, nchan);
10887 
10888 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10889 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10890 	if (chip_id(sc) >= CHELSIO_T7)
10891 		nchan = 1 << G_T7_PMTXNUMCHN(lo);
10892 	else
10893 		nchan = 1 << G_PMTXNUMCHN(lo);
10894 	for (i = 0, free = 0; i < nchan; i++)
10895 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10896 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10897 		   G_PMTXMAXPAGE(lo), free,
10898 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10899 		   hi >= (1 << 20) ? 'M' : 'K', nchan);
10900 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10901 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10902 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10903 
10904 	for (i = 0; i < 4; i++) {
10905 		if (chip_id(sc) > CHELSIO_T5)
10906 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10907 		else
10908 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10909 		if (is_t5(sc)) {
10910 			used = G_T5_USED(lo);
10911 			alloc = G_T5_ALLOC(lo);
10912 		} else {
10913 			used = G_USED(lo);
10914 			alloc = G_ALLOC(lo);
10915 		}
10916 		/* For T6+ these are MAC buffer groups */
10917 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10918 		    i, used, alloc);
10919 	}
10920 	for (i = 0; i < sc->chip_params->nchan; i++) {
10921 		if (chip_id(sc) > CHELSIO_T5)
10922 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10923 		else
10924 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10925 		if (is_t5(sc)) {
10926 			used = G_T5_USED(lo);
10927 			alloc = G_T5_ALLOC(lo);
10928 		} else {
10929 			used = G_USED(lo);
10930 			alloc = G_ALLOC(lo);
10931 		}
10932 		/* For T6+ these are MAC buffer groups */
10933 		sbuf_printf(sb,
10934 		    "\nLoopback %d using %u pages out of %u allocated",
10935 		    i, used, alloc);
10936 	}
10937 done:
10938 	mtx_unlock(&sc->reg_lock);
10939 	if (rc == 0)
10940 		rc = sbuf_finish(sb);
10941 	sbuf_delete(sb);
10942 	return (rc);
10943 }
10944 
10945 static inline void
10946 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10947 {
10948 	*mask = x | y;
10949 	y = htobe64(y);
10950 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10951 }
10952 
10953 static int
10954 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10955 {
10956 	struct adapter *sc = arg1;
10957 	struct sbuf *sb;
10958 	int rc, i;
10959 
10960 	MPASS(chip_id(sc) <= CHELSIO_T5);
10961 
10962 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10963 	if (sb == NULL)
10964 		return (ENOMEM);
10965 
10966 	sbuf_printf(sb,
10967 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10968 	    "  VF              Replication             P0 P1 P2 P3  ML");
10969 	rc = 0;
10970 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10971 		uint64_t tcamx, tcamy, mask;
10972 		uint32_t cls_lo, cls_hi;
10973 		uint8_t addr[ETHER_ADDR_LEN];
10974 
10975 		mtx_lock(&sc->reg_lock);
10976 		if (hw_off_limits(sc))
10977 			rc = ENXIO;
10978 		else {
10979 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10980 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10981 		}
10982 		mtx_unlock(&sc->reg_lock);
10983 		if (rc != 0)
10984 			break;
10985 		if (tcamx & tcamy)
10986 			continue;
10987 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10988 		mtx_lock(&sc->reg_lock);
10989 		if (hw_off_limits(sc))
10990 			rc = ENXIO;
10991 		else {
10992 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10993 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10994 		}
10995 		mtx_unlock(&sc->reg_lock);
10996 		if (rc != 0)
10997 			break;
10998 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10999 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
11000 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
11001 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
11002 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
11003 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
11004 
11005 		if (cls_lo & F_REPLICATE) {
11006 			struct fw_ldst_cmd ldst_cmd;
11007 
11008 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11009 			ldst_cmd.op_to_addrspace =
11010 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11011 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11012 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11013 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11014 			ldst_cmd.u.mps.rplc.fid_idx =
11015 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11016 				V_FW_LDST_CMD_IDX(i));
11017 
11018 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11019 			    "t4mps");
11020 			if (rc)
11021 				break;
11022 			if (hw_off_limits(sc))
11023 				rc = ENXIO;
11024 			else
11025 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11026 				    sizeof(ldst_cmd), &ldst_cmd);
11027 			end_synchronized_op(sc, 0);
11028 			if (rc != 0)
11029 				break;
11030 			else {
11031 				sbuf_printf(sb, " %08x %08x %08x %08x",
11032 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11033 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11034 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11035 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11036 			}
11037 		} else
11038 			sbuf_printf(sb, "%36s", "");
11039 
11040 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
11041 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
11042 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
11043 	}
11044 
11045 	if (rc)
11046 		(void) sbuf_finish(sb);
11047 	else
11048 		rc = sbuf_finish(sb);
11049 	sbuf_delete(sb);
11050 
11051 	return (rc);
11052 }
11053 
11054 static int
11055 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
11056 {
11057 	struct adapter *sc = arg1;
11058 	struct sbuf *sb;
11059 	int rc, i;
11060 
11061 	MPASS(chip_id(sc) == CHELSIO_T6);
11062 
11063 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11064 	if (sb == NULL)
11065 		return (ENOMEM);
11066 
11067 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11068 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11069 	    "                           Replication"
11070 	    "                                    P0 P1 P2 P3  ML");
11071 
11072 	rc = 0;
11073 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11074 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11075 		uint16_t ivlan;
11076 		uint64_t tcamx, tcamy, val, mask;
11077 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11078 		uint8_t addr[ETHER_ADDR_LEN];
11079 
11080 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
11081 		if (i < 256)
11082 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
11083 		else
11084 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
11085 		mtx_lock(&sc->reg_lock);
11086 		if (hw_off_limits(sc))
11087 			rc = ENXIO;
11088 		else {
11089 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11090 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11091 			tcamy = G_DMACH(val) << 32;
11092 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11093 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11094 		}
11095 		mtx_unlock(&sc->reg_lock);
11096 		if (rc != 0)
11097 			break;
11098 
11099 		lookup_type = G_DATALKPTYPE(data2);
11100 		port_num = G_DATAPORTNUM(data2);
11101 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11102 			/* Inner header VNI */
11103 			vniy = ((data2 & F_DATAVIDH2) << 23) |
11104 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11105 			dip_hit = data2 & F_DATADIPHIT;
11106 			vlan_vld = 0;
11107 		} else {
11108 			vniy = 0;
11109 			dip_hit = 0;
11110 			vlan_vld = data2 & F_DATAVIDH2;
11111 			ivlan = G_VIDL(val);
11112 		}
11113 
11114 		ctl |= V_CTLXYBITSEL(1);
11115 		mtx_lock(&sc->reg_lock);
11116 		if (hw_off_limits(sc))
11117 			rc = ENXIO;
11118 		else {
11119 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11120 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
11121 			tcamx = G_DMACH(val) << 32;
11122 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
11123 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
11124 		}
11125 		mtx_unlock(&sc->reg_lock);
11126 		if (rc != 0)
11127 			break;
11128 
11129 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11130 			/* Inner header VNI mask */
11131 			vnix = ((data2 & F_DATAVIDH2) << 23) |
11132 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
11133 		} else
11134 			vnix = 0;
11135 
11136 		if (tcamx & tcamy)
11137 			continue;
11138 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11139 
11140 		mtx_lock(&sc->reg_lock);
11141 		if (hw_off_limits(sc))
11142 			rc = ENXIO;
11143 		else {
11144 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11145 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11146 		}
11147 		mtx_unlock(&sc->reg_lock);
11148 		if (rc != 0)
11149 			break;
11150 
11151 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11152 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11153 			    "%012jx %06x %06x    -    -   %3c"
11154 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11155 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11156 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11157 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11158 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11159 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11160 		} else {
11161 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11162 			    "%012jx    -       -   ", i, addr[0], addr[1],
11163 			    addr[2], addr[3], addr[4], addr[5],
11164 			    (uintmax_t)mask);
11165 
11166 			if (vlan_vld)
11167 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11168 			else
11169 				sbuf_printf(sb, "  -    N     ");
11170 
11171 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11172 			    lookup_type ? 'I' : 'O', port_num,
11173 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11174 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11175 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11176 		}
11177 
11178 
11179 		if (cls_lo & F_T6_REPLICATE) {
11180 			struct fw_ldst_cmd ldst_cmd;
11181 
11182 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11183 			ldst_cmd.op_to_addrspace =
11184 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11185 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11186 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11187 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11188 			ldst_cmd.u.mps.rplc.fid_idx =
11189 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11190 				V_FW_LDST_CMD_IDX(i));
11191 
11192 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11193 			    "t6mps");
11194 			if (rc)
11195 				break;
11196 			if (hw_off_limits(sc))
11197 				rc = ENXIO;
11198 			else
11199 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11200 				    sizeof(ldst_cmd), &ldst_cmd);
11201 			end_synchronized_op(sc, 0);
11202 			if (rc != 0)
11203 				break;
11204 			else {
11205 				sbuf_printf(sb, " %08x %08x %08x %08x"
11206 				    " %08x %08x %08x %08x",
11207 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11208 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11209 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11210 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11211 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11212 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11213 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11214 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11215 			}
11216 		} else
11217 			sbuf_printf(sb, "%72s", "");
11218 
11219 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11220 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11221 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11222 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11223 	}
11224 
11225 	if (rc)
11226 		(void) sbuf_finish(sb);
11227 	else
11228 		rc = sbuf_finish(sb);
11229 	sbuf_delete(sb);
11230 
11231 	return (rc);
11232 }
11233 
11234 static int
11235 sysctl_mps_tcam_t7(SYSCTL_HANDLER_ARGS)
11236 {
11237 	struct adapter *sc = arg1;
11238 	struct sbuf *sb;
11239 	int rc, i;
11240 
11241 	MPASS(chip_id(sc) >= CHELSIO_T7);
11242 
11243 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11244 	if (sb == NULL)
11245 		return (ENOMEM);
11246 
11247 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
11248 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
11249 	    "                           Replication"
11250 	    "                                    P0 P1 P2 P3  ML");
11251 
11252 	rc = 0;
11253 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
11254 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
11255 		uint16_t ivlan;
11256 		uint64_t tcamx, tcamy, val, mask;
11257 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
11258 		uint8_t addr[ETHER_ADDR_LEN];
11259 
11260 		/* Read tcamy */
11261 		ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11262 		if (chip_rev(sc) == 0) {
11263 			if (i < 256)
11264 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11265 			else
11266 				ctl |= V_CTLTCAMINDEX(i - 256) | V_T7_CTLTCAMSEL(1);
11267 		} else {
11268 #if 0
11269 			ctl = (V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0));
11270 #endif
11271 			if (i < 512)
11272 				ctl |= V_CTLTCAMINDEX(i) | V_T7_CTLTCAMSEL(0);
11273 			else if (i < 1024)
11274 				ctl |= V_CTLTCAMINDEX(i - 512) | V_T7_CTLTCAMSEL(1);
11275 			else
11276 				ctl |= V_CTLTCAMINDEX(i - 1024) | V_T7_CTLTCAMSEL(2);
11277 		}
11278 
11279 		mtx_lock(&sc->reg_lock);
11280 		if (hw_off_limits(sc))
11281 			rc = ENXIO;
11282 		else {
11283 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11284 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11285 			tcamy = G_DMACH(val) << 32;
11286 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11287 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11288 		}
11289 		mtx_unlock(&sc->reg_lock);
11290 		if (rc != 0)
11291 			break;
11292 
11293 		lookup_type = G_DATALKPTYPE(data2);
11294 		port_num = G_DATAPORTNUM(data2);
11295 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11296 			/* Inner header VNI */
11297 			vniy = (((data2 & F_DATAVIDH2) |
11298 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11299 			dip_hit = data2 & F_DATADIPHIT;
11300 			vlan_vld = 0;
11301 		} else {
11302 			vniy = 0;
11303 			dip_hit = 0;
11304 			vlan_vld = data2 & F_DATAVIDH2;
11305 			ivlan = G_VIDL(val);
11306 		}
11307 
11308 		ctl |= V_CTLXYBITSEL(1);
11309 		mtx_lock(&sc->reg_lock);
11310 		if (hw_off_limits(sc))
11311 			rc = ENXIO;
11312 		else {
11313 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
11314 			val = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA1_REQ_ID1);
11315 			tcamx = G_DMACH(val) << 32;
11316 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA0_REQ_ID1);
11317 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM0_RDATA2_REQ_ID1);
11318 		}
11319 		mtx_unlock(&sc->reg_lock);
11320 		if (rc != 0)
11321 			break;
11322 
11323 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11324 			/* Inner header VNI mask */
11325 			vnix = (((data2 & F_DATAVIDH2) |
11326 			    G_DATAVIDH1(data2)) << 16) | G_VIDL(val);
11327 		} else
11328 			vnix = 0;
11329 
11330 		if (tcamx & tcamy)
11331 			continue;
11332 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
11333 
11334 		mtx_lock(&sc->reg_lock);
11335 		if (hw_off_limits(sc))
11336 			rc = ENXIO;
11337 		else {
11338 			if (chip_rev(sc) == 0) {
11339 				cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
11340 				cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
11341 			} else {
11342 				t4_write_reg(sc, A_MPS_CLS_SRAM_H,
11343 				    V_SRAMWRN(0) | V_SRAMINDEX(i));
11344 				cls_lo = t4_read_reg(sc, A_MPS_CLS_SRAM_L);
11345 				cls_hi = t4_read_reg(sc, A_MPS_CLS_SRAM_H);
11346 			}
11347 		}
11348 		mtx_unlock(&sc->reg_lock);
11349 		if (rc != 0)
11350 			break;
11351 
11352 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
11353 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11354 			    "%012jx %06x %06x    -    -   %3c"
11355 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
11356 			    addr[1], addr[2], addr[3], addr[4], addr[5],
11357 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
11358 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11359 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11360 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11361 		} else {
11362 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
11363 			    "%012jx    -       -   ", i, addr[0], addr[1],
11364 			    addr[2], addr[3], addr[4], addr[5],
11365 			    (uintmax_t)mask);
11366 
11367 			if (vlan_vld)
11368 				sbuf_printf(sb, "%4u   Y     ", ivlan);
11369 			else
11370 				sbuf_printf(sb, "  -    N     ");
11371 
11372 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
11373 			    lookup_type ? 'I' : 'O', port_num,
11374 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
11375 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
11376 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
11377 		}
11378 
11379 		if (cls_lo & F_T6_REPLICATE) {
11380 			struct fw_ldst_cmd ldst_cmd;
11381 
11382 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
11383 			ldst_cmd.op_to_addrspace =
11384 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
11385 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
11386 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
11387 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
11388 			ldst_cmd.u.mps.rplc.fid_idx =
11389 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
11390 				V_FW_LDST_CMD_IDX(i));
11391 
11392 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
11393 			    "t6mps");
11394 			if (rc)
11395 				break;
11396 			if (hw_off_limits(sc))
11397 				rc = ENXIO;
11398 			else
11399 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
11400 				    sizeof(ldst_cmd), &ldst_cmd);
11401 			end_synchronized_op(sc, 0);
11402 			if (rc != 0)
11403 				break;
11404 			else {
11405 				sbuf_printf(sb, " %08x %08x %08x %08x"
11406 				    " %08x %08x %08x %08x",
11407 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
11408 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
11409 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
11410 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
11411 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
11412 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
11413 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
11414 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
11415 			}
11416 		} else
11417 			sbuf_printf(sb, "%72s", "");
11418 
11419 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
11420 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
11421 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
11422 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
11423 	}
11424 
11425 	if (rc)
11426 		(void) sbuf_finish(sb);
11427 	else
11428 		rc = sbuf_finish(sb);
11429 	sbuf_delete(sb);
11430 
11431 	return (rc);
11432 }
11433 
11434 static int
11435 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
11436 {
11437 	struct adapter *sc = arg1;
11438 	struct sbuf *sb;
11439 	int rc;
11440 	uint16_t mtus[NMTUS];
11441 
11442 	rc = 0;
11443 	mtx_lock(&sc->reg_lock);
11444 	if (hw_off_limits(sc))
11445 		rc = ENXIO;
11446 	else
11447 		t4_read_mtu_tbl(sc, mtus, NULL);
11448 	mtx_unlock(&sc->reg_lock);
11449 	if (rc != 0)
11450 		return (rc);
11451 
11452 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11453 	if (sb == NULL)
11454 		return (ENOMEM);
11455 
11456 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
11457 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
11458 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
11459 	    mtus[14], mtus[15]);
11460 
11461 	rc = sbuf_finish(sb);
11462 	sbuf_delete(sb);
11463 
11464 	return (rc);
11465 }
11466 
11467 static int
11468 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
11469 {
11470 	struct adapter *sc = arg1;
11471 	struct sbuf *sb;
11472 	int rc, i;
11473 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
11474 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
11475 	uint32_t stats[T7_PM_RX_CACHE_NSTATS];
11476 	static const char *tx_stats[MAX_PM_NSTATS] = {
11477 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
11478 		"Tx FIFO wait", NULL, "Tx latency"
11479 	};
11480 	static const char *rx_stats[MAX_PM_NSTATS] = {
11481 		"Read:", "Write bypass:", "Write mem:", "Flush:",
11482 		"Rx FIFO wait", NULL, "Rx latency"
11483 	};
11484 
11485 	rc = 0;
11486 	mtx_lock(&sc->reg_lock);
11487 	if (hw_off_limits(sc))
11488 		rc = ENXIO;
11489 	else {
11490 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
11491 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
11492 		if (chip_id(sc) >= CHELSIO_T7)
11493 			t4_pmrx_cache_get_stats(sc, stats);
11494 	}
11495 	mtx_unlock(&sc->reg_lock);
11496 	if (rc != 0)
11497 		return (rc);
11498 
11499 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11500 	if (sb == NULL)
11501 		return (ENOMEM);
11502 
11503 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
11504 	for (i = 0; i < 4; i++) {
11505 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11506 		    tx_cyc[i]);
11507 	}
11508 
11509 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
11510 	for (i = 0; i < 4; i++) {
11511 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11512 		    rx_cyc[i]);
11513 	}
11514 
11515 	if (chip_id(sc) > CHELSIO_T5) {
11516 		sbuf_printf(sb,
11517 		    "\n              Total wait      Total occupancy");
11518 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11519 		    tx_cyc[i]);
11520 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11521 		    rx_cyc[i]);
11522 
11523 		i += 2;
11524 		MPASS(i < nitems(tx_stats));
11525 
11526 		sbuf_printf(sb,
11527 		    "\n                   Reads           Total wait");
11528 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
11529 		    tx_cyc[i]);
11530 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
11531 		    rx_cyc[i]);
11532 	}
11533 
11534 	if (chip_id(sc) >= CHELSIO_T7) {
11535 		i = 0;
11536 		sbuf_printf(sb, "\n\nPM RX Cache Stats\n");
11537 		sbuf_printf(sb, "%-40s    %u\n", "ReqWrite", stats[i++]);
11538 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadInv", stats[i++]);
11539 		sbuf_printf(sb, "%-40s    %u\n", "ReqReadNoInv", stats[i++]);
11540 		sbuf_printf(sb, "%-40s    %u\n", "Write Split Request",
11541 			   stats[i++]);
11542 		sbuf_printf(sb, "%-40s    %u\n",
11543 			   "Normal Read Split (Read Invalidate)", stats[i++]);
11544 		sbuf_printf(sb, "%-40s    %u\n",
11545 			   "Feedback Read Split (Read NoInvalidate)",
11546 			   stats[i++]);
11547 		sbuf_printf(sb, "%-40s    %u\n", "Write Hit", stats[i++]);
11548 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit",
11549 			   stats[i++]);
11550 		sbuf_printf(sb, "%-40s    %u\n", "Feedback Read Hit",
11551 			   stats[i++]);
11552 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full Avail",
11553 			   stats[i++]);
11554 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Hit Full UnAvail",
11555 			   stats[i++]);
11556 		sbuf_printf(sb, "%-40s    %u\n",
11557 			   "Normal Read Hit Partial Avail",
11558 			   stats[i++]);
11559 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full Avail",
11560 			   stats[i++]);
11561 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Full UnAvail",
11562 			   stats[i++]);
11563 		sbuf_printf(sb, "%-40s    %u\n", "FB Read Hit Partial Avail",
11564 			   stats[i++]);
11565 		sbuf_printf(sb, "%-40s    %u\n", "Normal Read Full Free",
11566 			   stats[i++]);
11567 		sbuf_printf(sb, "%-40s    %u\n",
11568 			   "Normal Read Part-avail Mul-Regions",
11569 			   stats[i++]);
11570 		sbuf_printf(sb, "%-40s    %u\n",
11571 			   "FB Read Part-avail Mul-Regions",
11572 			   stats[i++]);
11573 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss FL Used",
11574 			   stats[i++]);
11575 		sbuf_printf(sb, "%-40s    %u\n", "Write Miss LRU Used",
11576 			   stats[i++]);
11577 		sbuf_printf(sb, "%-40s    %u\n",
11578 			   "Write Miss LRU-Multiple Evict", stats[i++]);
11579 		sbuf_printf(sb, "%-40s    %u\n",
11580 			   "Write Hit Increasing Islands", stats[i++]);
11581 		sbuf_printf(sb, "%-40s    %u\n",
11582 			   "Normal Read Island Read split", stats[i++]);
11583 		sbuf_printf(sb, "%-40s    %u\n", "Write Overflow Eviction",
11584 			   stats[i++]);
11585 		sbuf_printf(sb, "%-40s    %u", "Read Overflow Eviction",
11586 			   stats[i++]);
11587 	}
11588 
11589 	rc = sbuf_finish(sb);
11590 	sbuf_delete(sb);
11591 
11592 	return (rc);
11593 }
11594 
11595 static int
11596 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
11597 {
11598 	struct adapter *sc = arg1;
11599 	struct sbuf *sb;
11600 	int rc;
11601 	struct tp_rdma_stats stats;
11602 
11603 	rc = 0;
11604 	mtx_lock(&sc->reg_lock);
11605 	if (hw_off_limits(sc))
11606 		rc = ENXIO;
11607 	else
11608 		t4_tp_get_rdma_stats(sc, &stats, 0);
11609 	mtx_unlock(&sc->reg_lock);
11610 	if (rc != 0)
11611 		return (rc);
11612 
11613 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11614 	if (sb == NULL)
11615 		return (ENOMEM);
11616 
11617 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
11618 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
11619 
11620 	rc = sbuf_finish(sb);
11621 	sbuf_delete(sb);
11622 
11623 	return (rc);
11624 }
11625 
11626 static int
11627 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
11628 {
11629 	struct adapter *sc = arg1;
11630 	struct sbuf *sb;
11631 	int rc;
11632 	struct tp_tcp_stats v4, v6;
11633 
11634 	rc = 0;
11635 	mtx_lock(&sc->reg_lock);
11636 	if (hw_off_limits(sc))
11637 		rc = ENXIO;
11638 	else
11639 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
11640 	mtx_unlock(&sc->reg_lock);
11641 	if (rc != 0)
11642 		return (rc);
11643 
11644 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11645 	if (sb == NULL)
11646 		return (ENOMEM);
11647 
11648 	sbuf_printf(sb,
11649 	    "                                IP                 IPv6\n");
11650 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
11651 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
11652 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
11653 	    v4.tcp_in_segs, v6.tcp_in_segs);
11654 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
11655 	    v4.tcp_out_segs, v6.tcp_out_segs);
11656 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
11657 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
11658 
11659 	rc = sbuf_finish(sb);
11660 	sbuf_delete(sb);
11661 
11662 	return (rc);
11663 }
11664 
11665 static int
11666 sysctl_tids(SYSCTL_HANDLER_ARGS)
11667 {
11668 	struct adapter *sc = arg1;
11669 	struct sbuf *sb;
11670 	int rc;
11671 	uint32_t x, y;
11672 	struct tid_info *t = &sc->tids;
11673 
11674 	rc = 0;
11675 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11676 	if (sb == NULL)
11677 		return (ENOMEM);
11678 
11679 	if (t->natids) {
11680 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
11681 		    t->atids_in_use);
11682 	}
11683 
11684 	if (t->nhpftids) {
11685 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
11686 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
11687 	}
11688 
11689 	if (t->ntids) {
11690 		bool hashen = false;
11691 
11692 		mtx_lock(&sc->reg_lock);
11693 		if (hw_off_limits(sc))
11694 			rc = ENXIO;
11695 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
11696 			hashen = true;
11697 			if (chip_id(sc) <= CHELSIO_T5) {
11698 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
11699 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
11700 			} else {
11701 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
11702 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
11703 			}
11704 		}
11705 		mtx_unlock(&sc->reg_lock);
11706 		if (rc != 0)
11707 			goto done;
11708 
11709 		sbuf_printf(sb, "TID range: ");
11710 		if (hashen) {
11711 			if (x)
11712 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
11713 			sbuf_printf(sb, "%u-%u", y, t->tid_base + t->ntids - 1);
11714 		} else {
11715 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
11716 			    t->ntids - 1);
11717 		}
11718 		sbuf_printf(sb, ", in use: %u\n",
11719 		    atomic_load_acq_int(&t->tids_in_use));
11720 	}
11721 
11722 	if (t->nstids) {
11723 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
11724 		    t->stid_base + t->nstids - 1, t->stids_in_use);
11725 	}
11726 
11727 	if (t->nftids) {
11728 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
11729 		    t->ftid_end, t->ftids_in_use);
11730 	}
11731 
11732 	if (t->netids) {
11733 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
11734 		    t->etid_base + t->netids - 1, t->etids_in_use);
11735 	}
11736 
11737 	mtx_lock(&sc->reg_lock);
11738 	if (hw_off_limits(sc))
11739 		rc = ENXIO;
11740 	else {
11741 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
11742 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
11743 	}
11744 	mtx_unlock(&sc->reg_lock);
11745 	if (rc != 0)
11746 		goto done;
11747 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
11748 done:
11749 	if (rc == 0)
11750 		rc = sbuf_finish(sb);
11751 	else
11752 		(void)sbuf_finish(sb);
11753 	sbuf_delete(sb);
11754 
11755 	return (rc);
11756 }
11757 
11758 static int
11759 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
11760 {
11761 	struct adapter *sc = arg1;
11762 	struct sbuf *sb;
11763 	int rc;
11764 	struct tp_err_stats stats;
11765 
11766 	rc = 0;
11767 	mtx_lock(&sc->reg_lock);
11768 	if (hw_off_limits(sc))
11769 		rc = ENXIO;
11770 	else
11771 		t4_tp_get_err_stats(sc, &stats, 0);
11772 	mtx_unlock(&sc->reg_lock);
11773 	if (rc != 0)
11774 		return (rc);
11775 
11776 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11777 	if (sb == NULL)
11778 		return (ENOMEM);
11779 
11780 	if (sc->chip_params->nchan > 2) {
11781 		sbuf_printf(sb, "                 channel 0  channel 1"
11782 		    "  channel 2  channel 3\n");
11783 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
11784 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
11785 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
11786 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
11787 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
11788 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
11789 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
11790 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
11791 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
11792 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
11793 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
11794 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
11795 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
11796 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
11797 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
11798 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
11799 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
11800 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
11801 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
11802 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
11803 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
11804 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
11805 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
11806 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
11807 	} else {
11808 		sbuf_printf(sb, "                 channel 0  channel 1\n");
11809 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
11810 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
11811 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
11812 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
11813 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
11814 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
11815 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
11816 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
11817 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
11818 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
11819 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
11820 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
11821 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
11822 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
11823 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
11824 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
11825 	}
11826 
11827 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
11828 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
11829 
11830 	rc = sbuf_finish(sb);
11831 	sbuf_delete(sb);
11832 
11833 	return (rc);
11834 }
11835 
11836 static int
11837 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
11838 {
11839 	struct adapter *sc = arg1;
11840 	struct sbuf *sb;
11841 	int rc;
11842 	struct tp_tnl_stats stats;
11843 
11844 	rc = 0;
11845 	mtx_lock(&sc->reg_lock);
11846 	if (hw_off_limits(sc))
11847 		rc = ENXIO;
11848 	else
11849 		t4_tp_get_tnl_stats(sc, &stats, 1);
11850 	mtx_unlock(&sc->reg_lock);
11851 	if (rc != 0)
11852 		return (rc);
11853 
11854 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11855 	if (sb == NULL)
11856 		return (ENOMEM);
11857 
11858 	if (sc->chip_params->nchan > 2) {
11859 		sbuf_printf(sb, "           channel 0  channel 1"
11860 		    "  channel 2  channel 3\n");
11861 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
11862 		    stats.out_pkt[0], stats.out_pkt[1],
11863 		    stats.out_pkt[2], stats.out_pkt[3]);
11864 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
11865 		    stats.in_pkt[0], stats.in_pkt[1],
11866 		    stats.in_pkt[2], stats.in_pkt[3]);
11867 	} else {
11868 		sbuf_printf(sb, "           channel 0  channel 1\n");
11869 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
11870 		    stats.out_pkt[0], stats.out_pkt[1]);
11871 		sbuf_printf(sb, "InPkts:   %10u %10u",
11872 		    stats.in_pkt[0], stats.in_pkt[1]);
11873 	}
11874 
11875 	rc = sbuf_finish(sb);
11876 	sbuf_delete(sb);
11877 
11878 	return (rc);
11879 }
11880 
11881 static int
11882 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
11883 {
11884 	struct adapter *sc = arg1;
11885 	struct tp_params *tpp = &sc->params.tp;
11886 	u_int mask;
11887 	int rc;
11888 
11889 	mask = tpp->la_mask >> 16;
11890 	rc = sysctl_handle_int(oidp, &mask, 0, req);
11891 	if (rc != 0 || req->newptr == NULL)
11892 		return (rc);
11893 	if (mask > 0xffff)
11894 		return (EINVAL);
11895 	mtx_lock(&sc->reg_lock);
11896 	if (hw_off_limits(sc))
11897 		rc = ENXIO;
11898 	else {
11899 		tpp->la_mask = mask << 16;
11900 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
11901 		    tpp->la_mask);
11902 	}
11903 	mtx_unlock(&sc->reg_lock);
11904 
11905 	return (rc);
11906 }
11907 
11908 struct field_desc {
11909 	const char *name;
11910 	u_int start;
11911 	u_int width;
11912 };
11913 
11914 static void
11915 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
11916 {
11917 	char buf[32];
11918 	int line_size = 0;
11919 
11920 	while (f->name) {
11921 		uint64_t mask = (1ULL << f->width) - 1;
11922 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
11923 		    ((uintmax_t)v >> f->start) & mask);
11924 
11925 		if (line_size + len >= 79) {
11926 			line_size = 8;
11927 			sbuf_printf(sb, "\n        ");
11928 		}
11929 		sbuf_printf(sb, "%s ", buf);
11930 		line_size += len + 1;
11931 		f++;
11932 	}
11933 	sbuf_printf(sb, "\n");
11934 }
11935 
11936 static const struct field_desc tp_la0[] = {
11937 	{ "RcfOpCodeOut", 60, 4 },
11938 	{ "State", 56, 4 },
11939 	{ "WcfState", 52, 4 },
11940 	{ "RcfOpcSrcOut", 50, 2 },
11941 	{ "CRxError", 49, 1 },
11942 	{ "ERxError", 48, 1 },
11943 	{ "SanityFailed", 47, 1 },
11944 	{ "SpuriousMsg", 46, 1 },
11945 	{ "FlushInputMsg", 45, 1 },
11946 	{ "FlushInputCpl", 44, 1 },
11947 	{ "RssUpBit", 43, 1 },
11948 	{ "RssFilterHit", 42, 1 },
11949 	{ "Tid", 32, 10 },
11950 	{ "InitTcb", 31, 1 },
11951 	{ "LineNumber", 24, 7 },
11952 	{ "Emsg", 23, 1 },
11953 	{ "EdataOut", 22, 1 },
11954 	{ "Cmsg", 21, 1 },
11955 	{ "CdataOut", 20, 1 },
11956 	{ "EreadPdu", 19, 1 },
11957 	{ "CreadPdu", 18, 1 },
11958 	{ "TunnelPkt", 17, 1 },
11959 	{ "RcfPeerFin", 16, 1 },
11960 	{ "RcfReasonOut", 12, 4 },
11961 	{ "TxCchannel", 10, 2 },
11962 	{ "RcfTxChannel", 8, 2 },
11963 	{ "RxEchannel", 6, 2 },
11964 	{ "RcfRxChannel", 5, 1 },
11965 	{ "RcfDataOutSrdy", 4, 1 },
11966 	{ "RxDvld", 3, 1 },
11967 	{ "RxOoDvld", 2, 1 },
11968 	{ "RxCongestion", 1, 1 },
11969 	{ "TxCongestion", 0, 1 },
11970 	{ NULL }
11971 };
11972 
11973 static const struct field_desc tp_la1[] = {
11974 	{ "CplCmdIn", 56, 8 },
11975 	{ "CplCmdOut", 48, 8 },
11976 	{ "ESynOut", 47, 1 },
11977 	{ "EAckOut", 46, 1 },
11978 	{ "EFinOut", 45, 1 },
11979 	{ "ERstOut", 44, 1 },
11980 	{ "SynIn", 43, 1 },
11981 	{ "AckIn", 42, 1 },
11982 	{ "FinIn", 41, 1 },
11983 	{ "RstIn", 40, 1 },
11984 	{ "DataIn", 39, 1 },
11985 	{ "DataInVld", 38, 1 },
11986 	{ "PadIn", 37, 1 },
11987 	{ "RxBufEmpty", 36, 1 },
11988 	{ "RxDdp", 35, 1 },
11989 	{ "RxFbCongestion", 34, 1 },
11990 	{ "TxFbCongestion", 33, 1 },
11991 	{ "TxPktSumSrdy", 32, 1 },
11992 	{ "RcfUlpType", 28, 4 },
11993 	{ "Eread", 27, 1 },
11994 	{ "Ebypass", 26, 1 },
11995 	{ "Esave", 25, 1 },
11996 	{ "Static0", 24, 1 },
11997 	{ "Cread", 23, 1 },
11998 	{ "Cbypass", 22, 1 },
11999 	{ "Csave", 21, 1 },
12000 	{ "CPktOut", 20, 1 },
12001 	{ "RxPagePoolFull", 18, 2 },
12002 	{ "RxLpbkPkt", 17, 1 },
12003 	{ "TxLpbkPkt", 16, 1 },
12004 	{ "RxVfValid", 15, 1 },
12005 	{ "SynLearned", 14, 1 },
12006 	{ "SetDelEntry", 13, 1 },
12007 	{ "SetInvEntry", 12, 1 },
12008 	{ "CpcmdDvld", 11, 1 },
12009 	{ "CpcmdSave", 10, 1 },
12010 	{ "RxPstructsFull", 8, 2 },
12011 	{ "EpcmdDvld", 7, 1 },
12012 	{ "EpcmdFlush", 6, 1 },
12013 	{ "EpcmdTrimPrefix", 5, 1 },
12014 	{ "EpcmdTrimPostfix", 4, 1 },
12015 	{ "ERssIp4Pkt", 3, 1 },
12016 	{ "ERssIp6Pkt", 2, 1 },
12017 	{ "ERssTcpUdpPkt", 1, 1 },
12018 	{ "ERssFceFipPkt", 0, 1 },
12019 	{ NULL }
12020 };
12021 
12022 static const struct field_desc tp_la2[] = {
12023 	{ "CplCmdIn", 56, 8 },
12024 	{ "MpsVfVld", 55, 1 },
12025 	{ "MpsPf", 52, 3 },
12026 	{ "MpsVf", 44, 8 },
12027 	{ "SynIn", 43, 1 },
12028 	{ "AckIn", 42, 1 },
12029 	{ "FinIn", 41, 1 },
12030 	{ "RstIn", 40, 1 },
12031 	{ "DataIn", 39, 1 },
12032 	{ "DataInVld", 38, 1 },
12033 	{ "PadIn", 37, 1 },
12034 	{ "RxBufEmpty", 36, 1 },
12035 	{ "RxDdp", 35, 1 },
12036 	{ "RxFbCongestion", 34, 1 },
12037 	{ "TxFbCongestion", 33, 1 },
12038 	{ "TxPktSumSrdy", 32, 1 },
12039 	{ "RcfUlpType", 28, 4 },
12040 	{ "Eread", 27, 1 },
12041 	{ "Ebypass", 26, 1 },
12042 	{ "Esave", 25, 1 },
12043 	{ "Static0", 24, 1 },
12044 	{ "Cread", 23, 1 },
12045 	{ "Cbypass", 22, 1 },
12046 	{ "Csave", 21, 1 },
12047 	{ "CPktOut", 20, 1 },
12048 	{ "RxPagePoolFull", 18, 2 },
12049 	{ "RxLpbkPkt", 17, 1 },
12050 	{ "TxLpbkPkt", 16, 1 },
12051 	{ "RxVfValid", 15, 1 },
12052 	{ "SynLearned", 14, 1 },
12053 	{ "SetDelEntry", 13, 1 },
12054 	{ "SetInvEntry", 12, 1 },
12055 	{ "CpcmdDvld", 11, 1 },
12056 	{ "CpcmdSave", 10, 1 },
12057 	{ "RxPstructsFull", 8, 2 },
12058 	{ "EpcmdDvld", 7, 1 },
12059 	{ "EpcmdFlush", 6, 1 },
12060 	{ "EpcmdTrimPrefix", 5, 1 },
12061 	{ "EpcmdTrimPostfix", 4, 1 },
12062 	{ "ERssIp4Pkt", 3, 1 },
12063 	{ "ERssIp6Pkt", 2, 1 },
12064 	{ "ERssTcpUdpPkt", 1, 1 },
12065 	{ "ERssFceFipPkt", 0, 1 },
12066 	{ NULL }
12067 };
12068 
12069 static void
12070 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
12071 {
12072 
12073 	field_desc_show(sb, *p, tp_la0);
12074 }
12075 
12076 static void
12077 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
12078 {
12079 
12080 	if (idx)
12081 		sbuf_printf(sb, "\n");
12082 	field_desc_show(sb, p[0], tp_la0);
12083 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12084 		field_desc_show(sb, p[1], tp_la0);
12085 }
12086 
12087 static void
12088 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
12089 {
12090 
12091 	if (idx)
12092 		sbuf_printf(sb, "\n");
12093 	field_desc_show(sb, p[0], tp_la0);
12094 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
12095 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
12096 }
12097 
12098 static int
12099 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
12100 {
12101 	struct adapter *sc = arg1;
12102 	struct sbuf *sb;
12103 	uint64_t *buf, *p;
12104 	int rc;
12105 	u_int i, inc;
12106 	void (*show_func)(struct sbuf *, uint64_t *, int);
12107 
12108 	rc = 0;
12109 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12110 	if (sb == NULL)
12111 		return (ENOMEM);
12112 
12113 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
12114 
12115 	mtx_lock(&sc->reg_lock);
12116 	if (hw_off_limits(sc))
12117 		rc = ENXIO;
12118 	else {
12119 		t4_tp_read_la(sc, buf, NULL);
12120 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
12121 		case 2:
12122 			inc = 2;
12123 			show_func = tp_la_show2;
12124 			break;
12125 		case 3:
12126 			inc = 2;
12127 			show_func = tp_la_show3;
12128 			break;
12129 		default:
12130 			inc = 1;
12131 			show_func = tp_la_show;
12132 		}
12133 	}
12134 	mtx_unlock(&sc->reg_lock);
12135 	if (rc != 0)
12136 		goto done;
12137 
12138 	p = buf;
12139 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
12140 		(*show_func)(sb, p, i);
12141 	rc = sbuf_finish(sb);
12142 done:
12143 	sbuf_delete(sb);
12144 	free(buf, M_CXGBE);
12145 	return (rc);
12146 }
12147 
12148 static int
12149 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
12150 {
12151 	struct adapter *sc = arg1;
12152 	struct sbuf *sb;
12153 	int rc;
12154 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
12155 
12156 	rc = 0;
12157 	mtx_lock(&sc->reg_lock);
12158 	if (hw_off_limits(sc))
12159 		rc = ENXIO;
12160 	else
12161 		t4_get_chan_txrate(sc, nrate, orate);
12162 	mtx_unlock(&sc->reg_lock);
12163 	if (rc != 0)
12164 		return (rc);
12165 
12166 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
12167 	if (sb == NULL)
12168 		return (ENOMEM);
12169 
12170 	if (sc->chip_params->nchan > 2) {
12171 		sbuf_printf(sb, "              channel 0   channel 1"
12172 		    "   channel 2   channel 3\n");
12173 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
12174 		    nrate[0], nrate[1], nrate[2], nrate[3]);
12175 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
12176 		    orate[0], orate[1], orate[2], orate[3]);
12177 	} else {
12178 		sbuf_printf(sb, "              channel 0   channel 1\n");
12179 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
12180 		    nrate[0], nrate[1]);
12181 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
12182 		    orate[0], orate[1]);
12183 	}
12184 
12185 	rc = sbuf_finish(sb);
12186 	sbuf_delete(sb);
12187 
12188 	return (rc);
12189 }
12190 
12191 static int
12192 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
12193 {
12194 	struct adapter *sc = arg1;
12195 	struct sbuf *sb;
12196 	uint32_t *buf, *p;
12197 	int rc, i;
12198 
12199 	rc = 0;
12200 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12201 	if (sb == NULL)
12202 		return (ENOMEM);
12203 
12204 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
12205 	    M_ZERO | M_WAITOK);
12206 
12207 	mtx_lock(&sc->reg_lock);
12208 	if (hw_off_limits(sc))
12209 		rc = ENXIO;
12210 	else
12211 		t4_ulprx_read_la(sc, buf);
12212 	mtx_unlock(&sc->reg_lock);
12213 	if (rc != 0)
12214 		goto done;
12215 
12216 	p = buf;
12217 	sbuf_printf(sb, "      Pcmd        Type   Message"
12218 	    "                Data");
12219 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
12220 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
12221 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
12222 	}
12223 	rc = sbuf_finish(sb);
12224 done:
12225 	sbuf_delete(sb);
12226 	free(buf, M_CXGBE);
12227 	return (rc);
12228 }
12229 
12230 static int
12231 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
12232 {
12233 	struct adapter *sc = arg1;
12234 	struct sbuf *sb;
12235 	int rc;
12236 	uint32_t cfg, s1, s2;
12237 
12238 	MPASS(chip_id(sc) >= CHELSIO_T5);
12239 
12240 	rc = 0;
12241 	mtx_lock(&sc->reg_lock);
12242 	if (hw_off_limits(sc))
12243 		rc = ENXIO;
12244 	else {
12245 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
12246 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
12247 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
12248 	}
12249 	mtx_unlock(&sc->reg_lock);
12250 	if (rc != 0)
12251 		return (rc);
12252 
12253 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12254 	if (sb == NULL)
12255 		return (ENOMEM);
12256 
12257 	if (G_STATSOURCE_T5(cfg) == 7) {
12258 		int mode;
12259 
12260 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
12261 		if (mode == 0)
12262 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
12263 		else if (mode == 1)
12264 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
12265 		else
12266 			sbuf_printf(sb, "unknown mode %d", mode);
12267 	}
12268 	rc = sbuf_finish(sb);
12269 	sbuf_delete(sb);
12270 
12271 	return (rc);
12272 }
12273 
12274 static int
12275 sysctl_cpus(SYSCTL_HANDLER_ARGS)
12276 {
12277 	struct adapter *sc = arg1;
12278 	enum cpu_sets op = arg2;
12279 	cpuset_t cpuset;
12280 	struct sbuf *sb;
12281 	int i, rc;
12282 
12283 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
12284 
12285 	CPU_ZERO(&cpuset);
12286 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
12287 	if (rc != 0)
12288 		return (rc);
12289 
12290 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
12291 	if (sb == NULL)
12292 		return (ENOMEM);
12293 
12294 	CPU_FOREACH(i)
12295 		sbuf_printf(sb, "%d ", i);
12296 	rc = sbuf_finish(sb);
12297 	sbuf_delete(sb);
12298 
12299 	return (rc);
12300 }
12301 
12302 static int
12303 sysctl_reset(SYSCTL_HANDLER_ARGS)
12304 {
12305 	struct adapter *sc = arg1;
12306 	u_int val;
12307 	int rc;
12308 
12309 	val = atomic_load_int(&sc->num_resets);
12310 	rc = sysctl_handle_int(oidp, &val, 0, req);
12311 	if (rc != 0 || req->newptr == NULL)
12312 		return (rc);
12313 
12314 	if (val == 0) {
12315 		/* Zero out the counter that tracks reset. */
12316 		atomic_store_int(&sc->num_resets, 0);
12317 		return (0);
12318 	}
12319 
12320 	if (val != 1)
12321 		return (EINVAL);	/* 0 or 1 are the only legal values */
12322 
12323 	if (hw_off_limits(sc))		/* harmless race */
12324 		return (EALREADY);
12325 
12326 	taskqueue_enqueue(reset_tq, &sc->reset_task);
12327 	return (0);
12328 }
12329 
12330 static int
12331 sysctl_tcb_cache(SYSCTL_HANDLER_ARGS)
12332 {
12333 	struct adapter *sc = arg1;
12334 	u_int val, v;
12335 	int rc;
12336 
12337 	mtx_lock(&sc->reg_lock);
12338 	if (hw_off_limits(sc)) {
12339 		rc = ENXIO;
12340 		goto done;
12341 	}
12342 	t4_tp_pio_read(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12343 	mtx_unlock(&sc->reg_lock);
12344 
12345 	val = v & F_GLFL ? 0 : 1;
12346 	rc = sysctl_handle_int(oidp, &val, 0, req);
12347 	if (rc != 0 || req->newptr == NULL)
12348 		return (rc);
12349 	if (val == 0)
12350 		v |= F_GLFL;
12351 	else
12352 		v &= ~F_GLFL;
12353 
12354 	mtx_lock(&sc->reg_lock);
12355 	if (hw_off_limits(sc))
12356 		rc = ENXIO;
12357 	else
12358 		t4_tp_pio_write(sc, &v, 1, A_TP_CMM_CONFIG, 1);
12359 done:
12360 	mtx_unlock(&sc->reg_lock);
12361 	return (rc);
12362 }
12363 
12364 #ifdef TCP_OFFLOAD
12365 static int
12366 sysctl_tls(SYSCTL_HANDLER_ARGS)
12367 {
12368 	struct adapter *sc = arg1;
12369 	int i, j, v, rc;
12370 	struct vi_info *vi;
12371 
12372 	v = sc->tt.tls;
12373 	rc = sysctl_handle_int(oidp, &v, 0, req);
12374 	if (rc != 0 || req->newptr == NULL)
12375 		return (rc);
12376 
12377 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
12378 		return (ENOTSUP);
12379 
12380 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
12381 	if (rc)
12382 		return (rc);
12383 	if (hw_off_limits(sc))
12384 		rc = ENXIO;
12385 	else {
12386 		sc->tt.tls = !!v;
12387 		for_each_port(sc, i) {
12388 			for_each_vi(sc->port[i], j, vi) {
12389 				if (vi->flags & VI_INIT_DONE)
12390 					t4_update_fl_bufsize(vi->ifp);
12391 			}
12392 		}
12393 	}
12394 	end_synchronized_op(sc, 0);
12395 
12396 	return (rc);
12397 
12398 }
12399 
12400 static void
12401 unit_conv(char *buf, size_t len, u_int val, u_int factor)
12402 {
12403 	u_int rem = val % factor;
12404 
12405 	if (rem == 0)
12406 		snprintf(buf, len, "%u", val / factor);
12407 	else {
12408 		while (rem % 10 == 0)
12409 			rem /= 10;
12410 		snprintf(buf, len, "%u.%u", val / factor, rem);
12411 	}
12412 }
12413 
12414 static int
12415 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
12416 {
12417 	struct adapter *sc = arg1;
12418 	char buf[16];
12419 	u_int res, re;
12420 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12421 
12422 	mtx_lock(&sc->reg_lock);
12423 	if (hw_off_limits(sc))
12424 		res = (u_int)-1;
12425 	else
12426 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
12427 	mtx_unlock(&sc->reg_lock);
12428 	if (res == (u_int)-1)
12429 		return (ENXIO);
12430 
12431 	switch (arg2) {
12432 	case 0:
12433 		/* timer_tick */
12434 		re = G_TIMERRESOLUTION(res);
12435 		break;
12436 	case 1:
12437 		/* TCP timestamp tick */
12438 		re = G_TIMESTAMPRESOLUTION(res);
12439 		break;
12440 	case 2:
12441 		/* DACK tick */
12442 		re = G_DELAYEDACKRESOLUTION(res);
12443 		break;
12444 	default:
12445 		return (EDOOFUS);
12446 	}
12447 
12448 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
12449 
12450 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
12451 }
12452 
12453 static int
12454 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
12455 {
12456 	struct adapter *sc = arg1;
12457 	int rc;
12458 	u_int dack_tmr, dack_re, v;
12459 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12460 
12461 	mtx_lock(&sc->reg_lock);
12462 	if (hw_off_limits(sc))
12463 		rc = ENXIO;
12464 	else {
12465 		rc = 0;
12466 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
12467 		    A_TP_TIMER_RESOLUTION));
12468 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
12469 	}
12470 	mtx_unlock(&sc->reg_lock);
12471 	if (rc != 0)
12472 		return (rc);
12473 
12474 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
12475 
12476 	return (sysctl_handle_int(oidp, &v, 0, req));
12477 }
12478 
12479 static int
12480 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
12481 {
12482 	struct adapter *sc = arg1;
12483 	int rc, reg = arg2;
12484 	u_int tre;
12485 	u_long tp_tick_us, v;
12486 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
12487 
12488 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
12489 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
12490 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
12491 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
12492 
12493 	mtx_lock(&sc->reg_lock);
12494 	if (hw_off_limits(sc))
12495 		rc = ENXIO;
12496 	else {
12497 		rc = 0;
12498 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
12499 		tp_tick_us = (cclk_ps << tre) / 1000000;
12500 		if (reg == A_TP_INIT_SRTT)
12501 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
12502 		else
12503 			v = tp_tick_us * t4_read_reg(sc, reg);
12504 	}
12505 	mtx_unlock(&sc->reg_lock);
12506 	if (rc != 0)
12507 		return (rc);
12508 	else
12509 		return (sysctl_handle_long(oidp, &v, 0, req));
12510 }
12511 
12512 /*
12513  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
12514  * passed to this function.
12515  */
12516 static int
12517 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
12518 {
12519 	struct adapter *sc = arg1;
12520 	int rc, idx = arg2;
12521 	u_int v;
12522 
12523 	MPASS(idx >= 0 && idx <= 24);
12524 
12525 	mtx_lock(&sc->reg_lock);
12526 	if (hw_off_limits(sc))
12527 		rc = ENXIO;
12528 	else {
12529 		rc = 0;
12530 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
12531 	}
12532 	mtx_unlock(&sc->reg_lock);
12533 	if (rc != 0)
12534 		return (rc);
12535 	else
12536 		return (sysctl_handle_int(oidp, &v, 0, req));
12537 }
12538 
12539 static int
12540 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
12541 {
12542 	struct adapter *sc = arg1;
12543 	int rc, idx = arg2;
12544 	u_int shift, v, r;
12545 
12546 	MPASS(idx >= 0 && idx < 16);
12547 
12548 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
12549 	shift = (idx & 3) << 3;
12550 	mtx_lock(&sc->reg_lock);
12551 	if (hw_off_limits(sc))
12552 		rc = ENXIO;
12553 	else {
12554 		rc = 0;
12555 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
12556 	}
12557 	mtx_unlock(&sc->reg_lock);
12558 	if (rc != 0)
12559 		return (rc);
12560 	else
12561 		return (sysctl_handle_int(oidp, &v, 0, req));
12562 }
12563 
12564 static int
12565 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
12566 {
12567 	struct vi_info *vi = arg1;
12568 	struct adapter *sc = vi->adapter;
12569 	int idx, rc, i;
12570 	struct sge_ofld_rxq *ofld_rxq;
12571 	uint8_t v;
12572 
12573 	idx = vi->ofld_tmr_idx;
12574 
12575 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12576 	if (rc != 0 || req->newptr == NULL)
12577 		return (rc);
12578 
12579 	if (idx < 0 || idx >= SGE_NTIMERS)
12580 		return (EINVAL);
12581 
12582 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12583 	    "t4otmr");
12584 	if (rc)
12585 		return (rc);
12586 
12587 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
12588 	for_each_ofld_rxq(vi, i, ofld_rxq) {
12589 #ifdef atomic_store_rel_8
12590 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
12591 #else
12592 		ofld_rxq->iq.intr_params = v;
12593 #endif
12594 	}
12595 	vi->ofld_tmr_idx = idx;
12596 
12597 	end_synchronized_op(sc, LOCK_HELD);
12598 	return (0);
12599 }
12600 
12601 static int
12602 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
12603 {
12604 	struct vi_info *vi = arg1;
12605 	struct adapter *sc = vi->adapter;
12606 	int idx, rc;
12607 
12608 	idx = vi->ofld_pktc_idx;
12609 
12610 	rc = sysctl_handle_int(oidp, &idx, 0, req);
12611 	if (rc != 0 || req->newptr == NULL)
12612 		return (rc);
12613 
12614 	if (idx < -1 || idx >= SGE_NCOUNTERS)
12615 		return (EINVAL);
12616 
12617 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
12618 	    "t4opktc");
12619 	if (rc)
12620 		return (rc);
12621 
12622 	if (vi->flags & VI_INIT_DONE)
12623 		rc = EBUSY; /* cannot be changed once the queues are created */
12624 	else
12625 		vi->ofld_pktc_idx = idx;
12626 
12627 	end_synchronized_op(sc, LOCK_HELD);
12628 	return (rc);
12629 }
12630 #endif
12631 
12632 static int
12633 get_sge_context(struct adapter *sc, int mem_id, uint32_t cid, int len,
12634     uint32_t *data)
12635 {
12636 	int rc;
12637 
12638 	if (len < sc->chip_params->sge_ctxt_size)
12639 		return (ENOBUFS);
12640 	if (cid > M_CTXTQID)
12641 		return (EINVAL);
12642 	if (mem_id != CTXT_EGRESS && mem_id != CTXT_INGRESS &&
12643 	    mem_id != CTXT_FLM && mem_id != CTXT_CNM)
12644 		return (EINVAL);
12645 
12646 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
12647 	if (rc)
12648 		return (rc);
12649 
12650 	if (hw_off_limits(sc)) {
12651 		rc = ENXIO;
12652 		goto done;
12653 	}
12654 
12655 	if (sc->flags & FW_OK && !is_t7(sc)) {
12656 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cid, mem_id, data);
12657 		if (rc == 0)
12658 			goto done;
12659 	}
12660 
12661 	/*
12662 	 * Read via firmware failed or wasn't even attempted.  Read directly via
12663 	 * the backdoor.
12664 	 */
12665 	rc = -t4_sge_ctxt_rd_bd(sc, cid, mem_id, data);
12666 done:
12667 	end_synchronized_op(sc, 0);
12668 	return (rc);
12669 }
12670 
12671 static int
12672 load_fw(struct adapter *sc, struct t4_data *fw)
12673 {
12674 	int rc;
12675 	uint8_t *fw_data;
12676 
12677 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
12678 	if (rc)
12679 		return (rc);
12680 
12681 	if (hw_off_limits(sc)) {
12682 		rc = ENXIO;
12683 		goto done;
12684 	}
12685 
12686 	/*
12687 	 * The firmware, with the sole exception of the memory parity error
12688 	 * handler, runs from memory and not flash.  It is almost always safe to
12689 	 * install a new firmware on a running system.  Just set bit 1 in
12690 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
12691 	 */
12692 	if (sc->flags & FULL_INIT_DONE &&
12693 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
12694 		rc = EBUSY;
12695 		goto done;
12696 	}
12697 
12698 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
12699 
12700 	rc = copyin(fw->data, fw_data, fw->len);
12701 	if (rc == 0)
12702 		rc = -t4_load_fw(sc, fw_data, fw->len);
12703 
12704 	free(fw_data, M_CXGBE);
12705 done:
12706 	end_synchronized_op(sc, 0);
12707 	return (rc);
12708 }
12709 
12710 static int
12711 load_cfg(struct adapter *sc, struct t4_data *cfg)
12712 {
12713 	int rc;
12714 	uint8_t *cfg_data = NULL;
12715 
12716 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12717 	if (rc)
12718 		return (rc);
12719 
12720 	if (hw_off_limits(sc)) {
12721 		rc = ENXIO;
12722 		goto done;
12723 	}
12724 
12725 	if (cfg->len == 0) {
12726 		/* clear */
12727 		rc = -t4_load_cfg(sc, NULL, 0);
12728 		goto done;
12729 	}
12730 
12731 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
12732 
12733 	rc = copyin(cfg->data, cfg_data, cfg->len);
12734 	if (rc == 0)
12735 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
12736 
12737 	free(cfg_data, M_CXGBE);
12738 done:
12739 	end_synchronized_op(sc, 0);
12740 	return (rc);
12741 }
12742 
12743 static int
12744 load_boot(struct adapter *sc, struct t4_bootrom *br)
12745 {
12746 	int rc;
12747 	uint8_t *br_data = NULL;
12748 	u_int offset;
12749 
12750 	if (br->len > 1024 * 1024)
12751 		return (EFBIG);
12752 
12753 	if (br->pf_offset == 0) {
12754 		/* pfidx */
12755 		if (br->pfidx_addr > 7)
12756 			return (EINVAL);
12757 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
12758 		    A_PCIE_PF_EXPROM_OFST)));
12759 	} else if (br->pf_offset == 1) {
12760 		/* offset */
12761 		offset = G_OFFSET(br->pfidx_addr);
12762 	} else {
12763 		return (EINVAL);
12764 	}
12765 
12766 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
12767 	if (rc)
12768 		return (rc);
12769 
12770 	if (hw_off_limits(sc)) {
12771 		rc = ENXIO;
12772 		goto done;
12773 	}
12774 
12775 	if (br->len == 0) {
12776 		/* clear */
12777 		rc = -t4_load_boot(sc, NULL, offset, 0);
12778 		goto done;
12779 	}
12780 
12781 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
12782 
12783 	rc = copyin(br->data, br_data, br->len);
12784 	if (rc == 0)
12785 		rc = -t4_load_boot(sc, br_data, offset, br->len);
12786 
12787 	free(br_data, M_CXGBE);
12788 done:
12789 	end_synchronized_op(sc, 0);
12790 	return (rc);
12791 }
12792 
12793 static int
12794 load_bootcfg(struct adapter *sc, struct t4_data *bc)
12795 {
12796 	int rc;
12797 	uint8_t *bc_data = NULL;
12798 
12799 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
12800 	if (rc)
12801 		return (rc);
12802 
12803 	if (hw_off_limits(sc)) {
12804 		rc = ENXIO;
12805 		goto done;
12806 	}
12807 
12808 	if (bc->len == 0) {
12809 		/* clear */
12810 		rc = -t4_load_bootcfg(sc, NULL, 0);
12811 		goto done;
12812 	}
12813 
12814 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
12815 
12816 	rc = copyin(bc->data, bc_data, bc->len);
12817 	if (rc == 0)
12818 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
12819 
12820 	free(bc_data, M_CXGBE);
12821 done:
12822 	end_synchronized_op(sc, 0);
12823 	return (rc);
12824 }
12825 
12826 static int
12827 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
12828 {
12829 	int rc;
12830 	struct cudbg_init *cudbg;
12831 	void *handle, *buf;
12832 
12833 	/* buf is large, don't block if no memory is available */
12834 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
12835 	if (buf == NULL)
12836 		return (ENOMEM);
12837 
12838 	handle = cudbg_alloc_handle();
12839 	if (handle == NULL) {
12840 		rc = ENOMEM;
12841 		goto done;
12842 	}
12843 
12844 	cudbg = cudbg_get_init(handle);
12845 	cudbg->adap = sc;
12846 	cudbg->print = (cudbg_print_cb)printf;
12847 
12848 #ifndef notyet
12849 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
12850 	    __func__, dump->wr_flash, dump->len, dump->data);
12851 #endif
12852 
12853 	if (dump->wr_flash)
12854 		cudbg->use_flash = 1;
12855 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
12856 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
12857 
12858 	rc = cudbg_collect(handle, buf, &dump->len);
12859 	if (rc != 0)
12860 		goto done;
12861 
12862 	rc = copyout(buf, dump->data, dump->len);
12863 done:
12864 	cudbg_free_handle(handle);
12865 	free(buf, M_CXGBE);
12866 	return (rc);
12867 }
12868 
12869 static void
12870 free_offload_policy(struct t4_offload_policy *op)
12871 {
12872 	struct offload_rule *r;
12873 	int i;
12874 
12875 	if (op == NULL)
12876 		return;
12877 
12878 	r = &op->rule[0];
12879 	for (i = 0; i < op->nrules; i++, r++) {
12880 		free(r->bpf_prog.bf_insns, M_CXGBE);
12881 	}
12882 	free(op->rule, M_CXGBE);
12883 	free(op, M_CXGBE);
12884 }
12885 
12886 static int
12887 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
12888 {
12889 	int i, rc, len;
12890 	struct t4_offload_policy *op, *old;
12891 	struct bpf_program *bf;
12892 	const struct offload_settings *s;
12893 	struct offload_rule *r;
12894 	void *u;
12895 
12896 	if (!is_offload(sc))
12897 		return (ENODEV);
12898 
12899 	if (uop->nrules == 0) {
12900 		/* Delete installed policies. */
12901 		op = NULL;
12902 		goto set_policy;
12903 	} else if (uop->nrules > 256) { /* arbitrary */
12904 		return (E2BIG);
12905 	}
12906 
12907 	/* Copy userspace offload policy to kernel */
12908 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
12909 	op->nrules = uop->nrules;
12910 	len = op->nrules * sizeof(struct offload_rule);
12911 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12912 	rc = copyin(uop->rule, op->rule, len);
12913 	if (rc) {
12914 		free(op->rule, M_CXGBE);
12915 		free(op, M_CXGBE);
12916 		return (rc);
12917 	}
12918 
12919 	r = &op->rule[0];
12920 	for (i = 0; i < op->nrules; i++, r++) {
12921 
12922 		/* Validate open_type */
12923 		if (r->open_type != OPEN_TYPE_LISTEN &&
12924 		    r->open_type != OPEN_TYPE_ACTIVE &&
12925 		    r->open_type != OPEN_TYPE_PASSIVE &&
12926 		    r->open_type != OPEN_TYPE_DONTCARE) {
12927 error:
12928 			/*
12929 			 * Rules 0 to i have malloc'd filters that need to be
12930 			 * freed.  Rules i+1 to nrules have userspace pointers
12931 			 * and should be left alone.
12932 			 */
12933 			op->nrules = i;
12934 			free_offload_policy(op);
12935 			return (rc);
12936 		}
12937 
12938 		/* Validate settings */
12939 		s = &r->settings;
12940 		if ((s->offload != 0 && s->offload != 1) ||
12941 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
12942 		    s->sched_class < -1 ||
12943 		    s->sched_class >= sc->params.nsched_cls) {
12944 			rc = EINVAL;
12945 			goto error;
12946 		}
12947 
12948 		bf = &r->bpf_prog;
12949 		u = bf->bf_insns;	/* userspace ptr */
12950 		bf->bf_insns = NULL;
12951 		if (bf->bf_len == 0) {
12952 			/* legal, matches everything */
12953 			continue;
12954 		}
12955 		len = bf->bf_len * sizeof(*bf->bf_insns);
12956 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
12957 		rc = copyin(u, bf->bf_insns, len);
12958 		if (rc != 0)
12959 			goto error;
12960 
12961 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
12962 			rc = EINVAL;
12963 			goto error;
12964 		}
12965 	}
12966 set_policy:
12967 	rw_wlock(&sc->policy_lock);
12968 	old = sc->policy;
12969 	sc->policy = op;
12970 	rw_wunlock(&sc->policy_lock);
12971 	free_offload_policy(old);
12972 
12973 	return (0);
12974 }
12975 
12976 #define MAX_READ_BUF_SIZE (128 * 1024)
12977 static int
12978 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
12979 {
12980 	uint32_t addr, remaining, n;
12981 	uint32_t *buf;
12982 	int rc;
12983 	uint8_t *dst;
12984 
12985 	mtx_lock(&sc->reg_lock);
12986 	if (hw_off_limits(sc))
12987 		rc = ENXIO;
12988 	else
12989 		rc = validate_mem_range(sc, mr->addr, mr->len);
12990 	mtx_unlock(&sc->reg_lock);
12991 	if (rc != 0)
12992 		return (rc);
12993 
12994 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
12995 	addr = mr->addr;
12996 	remaining = mr->len;
12997 	dst = (void *)mr->data;
12998 
12999 	while (remaining) {
13000 		n = min(remaining, MAX_READ_BUF_SIZE);
13001 		mtx_lock(&sc->reg_lock);
13002 		if (hw_off_limits(sc))
13003 			rc = ENXIO;
13004 		else
13005 			read_via_memwin(sc, 2, addr, buf, n);
13006 		mtx_unlock(&sc->reg_lock);
13007 		if (rc != 0)
13008 			break;
13009 
13010 		rc = copyout(buf, dst, n);
13011 		if (rc != 0)
13012 			break;
13013 
13014 		dst += n;
13015 		remaining -= n;
13016 		addr += n;
13017 	}
13018 
13019 	free(buf, M_CXGBE);
13020 	return (rc);
13021 }
13022 #undef MAX_READ_BUF_SIZE
13023 
13024 static int
13025 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
13026 {
13027 	int rc;
13028 
13029 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
13030 		return (EINVAL);
13031 
13032 	if (i2cd->len > sizeof(i2cd->data))
13033 		return (EFBIG);
13034 
13035 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
13036 	if (rc)
13037 		return (rc);
13038 	if (hw_off_limits(sc))
13039 		rc = ENXIO;
13040 	else
13041 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
13042 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
13043 	end_synchronized_op(sc, 0);
13044 
13045 	return (rc);
13046 }
13047 
13048 static int
13049 clear_stats(struct adapter *sc, u_int port_id)
13050 {
13051 	int i, v, chan_map;
13052 	struct port_info *pi;
13053 	struct vi_info *vi;
13054 	struct sge_rxq *rxq;
13055 	struct sge_txq *txq;
13056 	struct sge_wrq *wrq;
13057 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13058 	struct sge_ofld_txq *ofld_txq;
13059 #endif
13060 #ifdef TCP_OFFLOAD
13061 	struct sge_ofld_rxq *ofld_rxq;
13062 #endif
13063 
13064 	if (port_id >= sc->params.nports)
13065 		return (EINVAL);
13066 	pi = sc->port[port_id];
13067 	if (pi == NULL)
13068 		return (EIO);
13069 
13070 	mtx_lock(&sc->reg_lock);
13071 	if (!hw_off_limits(sc)) {
13072 		/* MAC stats */
13073 		t4_clr_port_stats(sc, pi->hw_port);
13074 		if (is_t6(sc)) {
13075 			if (pi->fcs_reg != -1)
13076 				pi->fcs_base = t4_read_reg64(sc,
13077 				    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13078 			else
13079 				pi->stats.rx_fcs_err = 0;
13080 		}
13081 		for_each_vi(pi, v, vi) {
13082 			if (vi->flags & VI_INIT_DONE)
13083 				t4_clr_vi_stats(sc, vi->vin);
13084 		}
13085 		chan_map = pi->rx_e_chan_map;
13086 		v = 0;	/* reuse */
13087 		while (chan_map) {
13088 			i = ffs(chan_map) - 1;
13089 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
13090 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
13091 			chan_map &= ~(1 << i);
13092 		}
13093 	}
13094 	mtx_unlock(&sc->reg_lock);
13095 	pi->tx_parse_error = 0;
13096 	pi->tnl_cong_drops = 0;
13097 
13098 	/*
13099 	 * Since this command accepts a port, clear stats for
13100 	 * all VIs on this port.
13101 	 */
13102 	for_each_vi(pi, v, vi) {
13103 		if (vi->flags & VI_INIT_DONE) {
13104 
13105 			for_each_rxq(vi, i, rxq) {
13106 #if defined(INET) || defined(INET6)
13107 				rxq->lro.lro_queued = 0;
13108 				rxq->lro.lro_flushed = 0;
13109 #endif
13110 				rxq->rxcsum = 0;
13111 				rxq->vlan_extraction = 0;
13112 				rxq->vxlan_rxcsum = 0;
13113 
13114 				rxq->fl.cl_allocated = 0;
13115 				rxq->fl.cl_recycled = 0;
13116 				rxq->fl.cl_fast_recycled = 0;
13117 			}
13118 
13119 			for_each_txq(vi, i, txq) {
13120 				txq->txcsum = 0;
13121 				txq->tso_wrs = 0;
13122 				txq->vlan_insertion = 0;
13123 				txq->imm_wrs = 0;
13124 				txq->sgl_wrs = 0;
13125 				txq->txpkt_wrs = 0;
13126 				txq->txpkts0_wrs = 0;
13127 				txq->txpkts1_wrs = 0;
13128 				txq->txpkts0_pkts = 0;
13129 				txq->txpkts1_pkts = 0;
13130 				txq->txpkts_flush = 0;
13131 				txq->raw_wrs = 0;
13132 				txq->vxlan_tso_wrs = 0;
13133 				txq->vxlan_txcsum = 0;
13134 				txq->kern_tls_records = 0;
13135 				txq->kern_tls_short = 0;
13136 				txq->kern_tls_partial = 0;
13137 				txq->kern_tls_full = 0;
13138 				txq->kern_tls_octets = 0;
13139 				txq->kern_tls_waste = 0;
13140 				txq->kern_tls_header = 0;
13141 				txq->kern_tls_fin_short = 0;
13142 				txq->kern_tls_cbc = 0;
13143 				txq->kern_tls_gcm = 0;
13144 				if (is_t6(sc)) {
13145 					txq->kern_tls_options = 0;
13146 					txq->kern_tls_fin = 0;
13147 				} else {
13148 					txq->kern_tls_ghash_received = 0;
13149 					txq->kern_tls_ghash_requested = 0;
13150 					txq->kern_tls_lso = 0;
13151 					txq->kern_tls_partial_ghash = 0;
13152 					txq->kern_tls_splitmode = 0;
13153 					txq->kern_tls_trailer = 0;
13154 				}
13155 				mp_ring_reset_stats(txq->r);
13156 			}
13157 
13158 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13159 			for_each_ofld_txq(vi, i, ofld_txq) {
13160 				ofld_txq->wrq.tx_wrs_direct = 0;
13161 				ofld_txq->wrq.tx_wrs_copied = 0;
13162 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
13163 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
13164 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
13165 				counter_u64_zero(ofld_txq->tx_nvme_pdus);
13166 				counter_u64_zero(ofld_txq->tx_nvme_octets);
13167 				counter_u64_zero(ofld_txq->tx_nvme_iso_wrs);
13168 				counter_u64_zero(ofld_txq->tx_aio_jobs);
13169 				counter_u64_zero(ofld_txq->tx_aio_octets);
13170 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
13171 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
13172 			}
13173 #endif
13174 #ifdef TCP_OFFLOAD
13175 			for_each_ofld_rxq(vi, i, ofld_rxq) {
13176 				ofld_rxq->fl.cl_allocated = 0;
13177 				ofld_rxq->fl.cl_recycled = 0;
13178 				ofld_rxq->fl.cl_fast_recycled = 0;
13179 				counter_u64_zero(
13180 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
13181 				counter_u64_zero(
13182 				    ofld_rxq->rx_iscsi_ddp_setup_error);
13183 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
13184 				ofld_rxq->rx_iscsi_ddp_octets = 0;
13185 				ofld_rxq->rx_iscsi_fl_pdus = 0;
13186 				ofld_rxq->rx_iscsi_fl_octets = 0;
13187 				counter_u64_zero(
13188 				    ofld_rxq->rx_nvme_ddp_setup_ok);
13189 				counter_u64_zero(
13190 				    ofld_rxq->rx_nvme_ddp_setup_no_stag);
13191 				counter_u64_zero(
13192 				    ofld_rxq->rx_nvme_ddp_setup_error);
13193 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_pdus);
13194 				counter_u64_zero(ofld_rxq->rx_nvme_ddp_octets);
13195 				counter_u64_zero(ofld_rxq->rx_nvme_fl_pdus);
13196 				counter_u64_zero(ofld_rxq->rx_nvme_fl_octets);
13197 				counter_u64_zero(
13198 				    ofld_rxq->rx_nvme_invalid_headers);
13199 				counter_u64_zero(
13200 				    ofld_rxq->rx_nvme_header_digest_errors);
13201 				counter_u64_zero(
13202 				    ofld_rxq->rx_nvme_data_digest_errors);
13203 				ofld_rxq->rx_aio_ddp_jobs = 0;
13204 				ofld_rxq->rx_aio_ddp_octets = 0;
13205 				ofld_rxq->rx_toe_tls_records = 0;
13206 				ofld_rxq->rx_toe_tls_octets = 0;
13207 				ofld_rxq->rx_toe_ddp_octets = 0;
13208 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
13209 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
13210 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
13211 			}
13212 #endif
13213 
13214 			if (IS_MAIN_VI(vi)) {
13215 				wrq = &sc->sge.ctrlq[pi->port_id];
13216 				wrq->tx_wrs_direct = 0;
13217 				wrq->tx_wrs_copied = 0;
13218 			}
13219 		}
13220 	}
13221 
13222 	return (0);
13223 }
13224 
13225 static int
13226 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13227 {
13228 #ifdef INET6
13229 	struct in6_addr in6;
13230 
13231 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13232 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
13233 		return (0);
13234 	else
13235 		return (EIO);
13236 #else
13237 	return (ENOTSUP);
13238 #endif
13239 }
13240 
13241 static int
13242 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
13243 {
13244 #ifdef INET6
13245 	struct in6_addr in6;
13246 
13247 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
13248 	return (t4_release_clip_addr(sc, &in6));
13249 #else
13250 	return (ENOTSUP);
13251 #endif
13252 }
13253 
13254 int
13255 t4_os_find_pci_capability(struct adapter *sc, int cap)
13256 {
13257 	int i;
13258 
13259 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
13260 }
13261 
13262 void
13263 t4_os_portmod_changed(struct port_info *pi)
13264 {
13265 	struct adapter *sc = pi->adapter;
13266 	struct vi_info *vi;
13267 	if_t ifp;
13268 	static const char *mod_str[] = {
13269 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM",
13270 		"LR_SIMPLEX", "DR"
13271 	};
13272 
13273 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
13274 	    ("%s: port_type %u", __func__, pi->port_type));
13275 
13276 	vi = &pi->vi[0];
13277 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
13278 		PORT_LOCK(pi);
13279 		build_medialist(pi);
13280 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
13281 			fixup_link_config(pi);
13282 			apply_link_config(pi);
13283 		}
13284 		PORT_UNLOCK(pi);
13285 		end_synchronized_op(sc, LOCK_HELD);
13286 	}
13287 
13288 	ifp = vi->ifp;
13289 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
13290 		if_printf(ifp, "transceiver unplugged.\n");
13291 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
13292 		if_printf(ifp, "unknown transceiver inserted.\n");
13293 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
13294 		if_printf(ifp, "unsupported transceiver inserted.\n");
13295 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
13296 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
13297 		    port_top_speed(pi), mod_str[pi->mod_type]);
13298 	} else {
13299 		if_printf(ifp, "transceiver (type %d) inserted.\n",
13300 		    pi->mod_type);
13301 	}
13302 }
13303 
13304 void
13305 t4_os_link_changed(struct port_info *pi)
13306 {
13307 	struct vi_info *vi;
13308 	if_t ifp;
13309 	struct link_config *lc = &pi->link_cfg;
13310 	struct adapter *sc = pi->adapter;
13311 	int v;
13312 
13313 	PORT_LOCK_ASSERT_OWNED(pi);
13314 
13315 	if (is_t6(sc)) {
13316 		if (lc->link_ok) {
13317 			if (lc->speed > 25000 ||
13318 			    (lc->speed == 25000 && lc->fec == FEC_RS))
13319 				pi->fcs_reg = A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS;
13320 			else
13321 				pi->fcs_reg = A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS;
13322 			pi->fcs_base = t4_read_reg64(sc,
13323 			    t4_port_reg(sc, pi->tx_chan, pi->fcs_reg));
13324 			pi->stats.rx_fcs_err = 0;
13325 		} else {
13326 			pi->fcs_reg = -1;
13327 		}
13328 	} else {
13329 		MPASS(pi->fcs_reg != -1);
13330 		MPASS(pi->fcs_base == 0);
13331 	}
13332 
13333 	for_each_vi(pi, v, vi) {
13334 		ifp = vi->ifp;
13335 		if (ifp == NULL || IS_DETACHING(vi))
13336 			continue;
13337 
13338 		if (lc->link_ok) {
13339 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
13340 			if_link_state_change(ifp, LINK_STATE_UP);
13341 		} else {
13342 			if_link_state_change(ifp, LINK_STATE_DOWN);
13343 		}
13344 	}
13345 }
13346 
13347 void
13348 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
13349 {
13350 	struct adapter *sc;
13351 
13352 	sx_slock(&t4_list_lock);
13353 	SLIST_FOREACH(sc, &t4_list, link) {
13354 		/*
13355 		 * func should not make any assumptions about what state sc is
13356 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
13357 		 */
13358 		func(sc, arg);
13359 	}
13360 	sx_sunlock(&t4_list_lock);
13361 }
13362 
13363 static int
13364 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
13365     struct thread *td)
13366 {
13367 	int rc;
13368 	struct adapter *sc = dev->si_drv1;
13369 
13370 	rc = priv_check(td, PRIV_DRIVER);
13371 	if (rc != 0)
13372 		return (rc);
13373 
13374 	switch (cmd) {
13375 	case CHELSIO_T4_GETREG: {
13376 		struct t4_reg *edata = (struct t4_reg *)data;
13377 
13378 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13379 			return (EFAULT);
13380 
13381 		mtx_lock(&sc->reg_lock);
13382 		if (hw_off_limits(sc))
13383 			rc = ENXIO;
13384 		else if (edata->size == 4)
13385 			edata->val = t4_read_reg(sc, edata->addr);
13386 		else if (edata->size == 8)
13387 			edata->val = t4_read_reg64(sc, edata->addr);
13388 		else
13389 			rc = EINVAL;
13390 		mtx_unlock(&sc->reg_lock);
13391 
13392 		break;
13393 	}
13394 	case CHELSIO_T4_SETREG: {
13395 		struct t4_reg *edata = (struct t4_reg *)data;
13396 
13397 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
13398 			return (EFAULT);
13399 
13400 		mtx_lock(&sc->reg_lock);
13401 		if (hw_off_limits(sc))
13402 			rc = ENXIO;
13403 		else if (edata->size == 4) {
13404 			if (edata->val & 0xffffffff00000000)
13405 				rc = EINVAL;
13406 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
13407 		} else if (edata->size == 8)
13408 			t4_write_reg64(sc, edata->addr, edata->val);
13409 		else
13410 			rc = EINVAL;
13411 		mtx_unlock(&sc->reg_lock);
13412 
13413 		break;
13414 	}
13415 	case CHELSIO_T4_REGDUMP: {
13416 		struct t4_regdump *regs = (struct t4_regdump *)data;
13417 		int reglen = t4_get_regs_len(sc);
13418 		uint8_t *buf;
13419 
13420 		if (regs->len < reglen) {
13421 			regs->len = reglen; /* hint to the caller */
13422 			return (ENOBUFS);
13423 		}
13424 
13425 		regs->len = reglen;
13426 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
13427 		mtx_lock(&sc->reg_lock);
13428 		if (hw_off_limits(sc))
13429 			rc = ENXIO;
13430 		else
13431 			get_regs(sc, regs, buf);
13432 		mtx_unlock(&sc->reg_lock);
13433 		if (rc == 0)
13434 			rc = copyout(buf, regs->data, reglen);
13435 		free(buf, M_CXGBE);
13436 		break;
13437 	}
13438 	case CHELSIO_T4_GET_FILTER_MODE:
13439 		rc = get_filter_mode(sc, (uint32_t *)data);
13440 		break;
13441 	case CHELSIO_T4_SET_FILTER_MODE:
13442 		rc = set_filter_mode(sc, *(uint32_t *)data);
13443 		break;
13444 	case CHELSIO_T4_SET_FILTER_MASK:
13445 		rc = set_filter_mask(sc, *(uint32_t *)data);
13446 		break;
13447 	case CHELSIO_T4_GET_FILTER:
13448 		rc = get_filter(sc, (struct t4_filter *)data);
13449 		break;
13450 	case CHELSIO_T4_SET_FILTER:
13451 		rc = set_filter(sc, (struct t4_filter *)data);
13452 		break;
13453 	case CHELSIO_T4_DEL_FILTER:
13454 		rc = del_filter(sc, (struct t4_filter *)data);
13455 		break;
13456 	case CHELSIO_T4_GET_SGE_CONTEXT: {
13457 		struct t4_sge_context *ctxt = (struct t4_sge_context *)data;
13458 
13459 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13460 		    sizeof(ctxt->data), &ctxt->data[0]);
13461 		break;
13462 	}
13463 	case CHELSIO_T4_LOAD_FW:
13464 		rc = load_fw(sc, (struct t4_data *)data);
13465 		break;
13466 	case CHELSIO_T4_GET_MEM:
13467 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
13468 		break;
13469 	case CHELSIO_T4_GET_I2C:
13470 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
13471 		break;
13472 	case CHELSIO_T4_CLEAR_STATS:
13473 		rc = clear_stats(sc, *(uint32_t *)data);
13474 		break;
13475 	case CHELSIO_T4_SCHED_CLASS:
13476 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
13477 		break;
13478 	case CHELSIO_T4_SCHED_QUEUE:
13479 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
13480 		break;
13481 	case CHELSIO_T4_GET_TRACER:
13482 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
13483 		break;
13484 	case CHELSIO_T4_SET_TRACER:
13485 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
13486 		break;
13487 	case CHELSIO_T4_LOAD_CFG:
13488 		rc = load_cfg(sc, (struct t4_data *)data);
13489 		break;
13490 	case CHELSIO_T4_LOAD_BOOT:
13491 		rc = load_boot(sc, (struct t4_bootrom *)data);
13492 		break;
13493 	case CHELSIO_T4_LOAD_BOOTCFG:
13494 		rc = load_bootcfg(sc, (struct t4_data *)data);
13495 		break;
13496 	case CHELSIO_T4_CUDBG_DUMP:
13497 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
13498 		break;
13499 	case CHELSIO_T4_SET_OFLD_POLICY:
13500 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
13501 		break;
13502 	case CHELSIO_T4_HOLD_CLIP_ADDR:
13503 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
13504 		break;
13505 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
13506 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
13507 		break;
13508 	case CHELSIO_T4_GET_SGE_CTXT: {
13509 		struct t4_sge_ctxt *ctxt = (struct t4_sge_ctxt *)data;
13510 
13511 		rc = get_sge_context(sc, ctxt->mem_id, ctxt->cid,
13512 		    sizeof(ctxt->data), &ctxt->data[0]);
13513 		break;
13514 	}
13515 	default:
13516 		rc = ENOTTY;
13517 	}
13518 
13519 	return (rc);
13520 }
13521 
13522 #ifdef TCP_OFFLOAD
13523 int
13524 toe_capability(struct vi_info *vi, bool enable)
13525 {
13526 	int rc;
13527 	struct port_info *pi = vi->pi;
13528 	struct adapter *sc = pi->adapter;
13529 
13530 	ASSERT_SYNCHRONIZED_OP(sc);
13531 
13532 	if (!is_offload(sc))
13533 		return (ENODEV);
13534 	if (!hw_all_ok(sc))
13535 		return (ENXIO);
13536 
13537 	if (enable) {
13538 #ifdef KERN_TLS
13539 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
13540 			int i, j, n;
13541 			struct port_info *p;
13542 			struct vi_info *v;
13543 
13544 			/*
13545 			 * Reconfigure hardware for TOE if TXTLS is not enabled
13546 			 * on any ifnet.
13547 			 */
13548 			n = 0;
13549 			for_each_port(sc, i) {
13550 				p = sc->port[i];
13551 				for_each_vi(p, j, v) {
13552 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
13553 						CH_WARN(sc,
13554 						    "%s has NIC TLS enabled.\n",
13555 						    device_get_nameunit(v->dev));
13556 						n++;
13557 					}
13558 				}
13559 			}
13560 			if (n > 0) {
13561 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
13562 				    "associated with this adapter before "
13563 				    "trying to enable TOE.\n");
13564 				return (EAGAIN);
13565 			}
13566 			rc = t6_config_kern_tls(sc, false);
13567 			if (rc)
13568 				return (rc);
13569 		}
13570 #endif
13571 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
13572 			/* TOE is already enabled. */
13573 			return (0);
13574 		}
13575 
13576 		/*
13577 		 * We need the port's queues around so that we're able to send
13578 		 * and receive CPLs to/from the TOE even if the ifnet for this
13579 		 * port has never been UP'd administratively.
13580 		 */
13581 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
13582 			return (rc);
13583 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
13584 		    ((rc = vi_init(&pi->vi[0])) != 0))
13585 			return (rc);
13586 
13587 		if (isset(&sc->offload_map, pi->port_id)) {
13588 			/* TOE is enabled on another VI of this port. */
13589 			MPASS(pi->uld_vis > 0);
13590 			pi->uld_vis++;
13591 			return (0);
13592 		}
13593 
13594 		if (!uld_active(sc, ULD_TOM)) {
13595 			rc = t4_activate_uld(sc, ULD_TOM);
13596 			if (rc == EAGAIN) {
13597 				log(LOG_WARNING,
13598 				    "You must kldload t4_tom.ko before trying "
13599 				    "to enable TOE on a cxgbe interface.\n");
13600 			}
13601 			if (rc != 0)
13602 				return (rc);
13603 			KASSERT(sc->tom_softc != NULL,
13604 			    ("%s: TOM activated but softc NULL", __func__));
13605 			KASSERT(uld_active(sc, ULD_TOM),
13606 			    ("%s: TOM activated but flag not set", __func__));
13607 		}
13608 
13609 		/*
13610 		 * Activate iWARP, iSCSI, and NVMe too, if the modules
13611 		 * are loaded.
13612 		 */
13613 		if (!uld_active(sc, ULD_IWARP))
13614 			(void) t4_activate_uld(sc, ULD_IWARP);
13615 		if (!uld_active(sc, ULD_ISCSI))
13616 			(void) t4_activate_uld(sc, ULD_ISCSI);
13617 		if (!uld_active(sc, ULD_NVME))
13618 			(void) t4_activate_uld(sc, ULD_NVME);
13619 
13620 		if (pi->uld_vis++ == 0)
13621 			setbit(&sc->offload_map, pi->port_id);
13622 	} else {
13623 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
13624 			/* TOE is already disabled. */
13625 			return (0);
13626 		}
13627 		MPASS(isset(&sc->offload_map, pi->port_id));
13628 		MPASS(pi->uld_vis > 0);
13629 		if (--pi->uld_vis == 0)
13630 			clrbit(&sc->offload_map, pi->port_id);
13631 	}
13632 
13633 	return (0);
13634 }
13635 
13636 /*
13637  * Add an upper layer driver to the global list.
13638  */
13639 int
13640 t4_register_uld(struct uld_info *ui, int id)
13641 {
13642 	int rc;
13643 
13644 	if (id < 0 || id > ULD_MAX)
13645 		return (EINVAL);
13646 	sx_xlock(&t4_uld_list_lock);
13647 	if (t4_uld_list[id] != NULL)
13648 		rc = EEXIST;
13649 	else {
13650 		t4_uld_list[id] = ui;
13651 		rc = 0;
13652 	}
13653 	sx_xunlock(&t4_uld_list_lock);
13654 	return (rc);
13655 }
13656 
13657 int
13658 t4_unregister_uld(struct uld_info *ui, int id)
13659 {
13660 
13661 	if (id < 0 || id > ULD_MAX)
13662 		return (EINVAL);
13663 	sx_xlock(&t4_uld_list_lock);
13664 	MPASS(t4_uld_list[id] == ui);
13665 	t4_uld_list[id] = NULL;
13666 	sx_xunlock(&t4_uld_list_lock);
13667 	return (0);
13668 }
13669 
13670 int
13671 t4_activate_uld(struct adapter *sc, int id)
13672 {
13673 	int rc;
13674 
13675 	ASSERT_SYNCHRONIZED_OP(sc);
13676 
13677 	if (id < 0 || id > ULD_MAX)
13678 		return (EINVAL);
13679 
13680 	/* Adapter needs to be initialized before any ULD can be activated. */
13681 	if (!(sc->flags & FULL_INIT_DONE)) {
13682 		rc = adapter_init(sc);
13683 		if (rc != 0)
13684 			return (rc);
13685 	}
13686 
13687 	sx_slock(&t4_uld_list_lock);
13688 	if (t4_uld_list[id] == NULL)
13689 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
13690 	else {
13691 		rc = t4_uld_list[id]->uld_activate(sc);
13692 		if (rc == 0)
13693 			setbit(&sc->active_ulds, id);
13694 	}
13695 	sx_sunlock(&t4_uld_list_lock);
13696 
13697 	return (rc);
13698 }
13699 
13700 int
13701 t4_deactivate_uld(struct adapter *sc, int id)
13702 {
13703 	int rc;
13704 
13705 	ASSERT_SYNCHRONIZED_OP(sc);
13706 
13707 	if (id < 0 || id > ULD_MAX)
13708 		return (EINVAL);
13709 
13710 	sx_slock(&t4_uld_list_lock);
13711 	if (t4_uld_list[id] == NULL)
13712 		rc = ENXIO;
13713 	else {
13714 		rc = t4_uld_list[id]->uld_deactivate(sc);
13715 		if (rc == 0)
13716 			clrbit(&sc->active_ulds, id);
13717 	}
13718 	sx_sunlock(&t4_uld_list_lock);
13719 
13720 	return (rc);
13721 }
13722 
13723 static int
13724 deactivate_all_uld(struct adapter *sc)
13725 {
13726 	int i, rc;
13727 
13728 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
13729 	if (rc != 0)
13730 		return (ENXIO);
13731 	sx_slock(&t4_uld_list_lock);
13732 	for (i = 0; i <= ULD_MAX; i++) {
13733 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
13734 			continue;
13735 		rc = t4_uld_list[i]->uld_deactivate(sc);
13736 		if (rc != 0)
13737 			break;
13738 		clrbit(&sc->active_ulds, i);
13739 	}
13740 	sx_sunlock(&t4_uld_list_lock);
13741 	end_synchronized_op(sc, 0);
13742 
13743 	return (rc);
13744 }
13745 
13746 static void
13747 stop_all_uld(struct adapter *sc)
13748 {
13749 	int i;
13750 
13751 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
13752 		return;
13753 	sx_slock(&t4_uld_list_lock);
13754 	for (i = 0; i <= ULD_MAX; i++) {
13755 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13756 		    t4_uld_list[i]->uld_stop == NULL)
13757 			continue;
13758 		(void) t4_uld_list[i]->uld_stop(sc);
13759 	}
13760 	sx_sunlock(&t4_uld_list_lock);
13761 	end_synchronized_op(sc, 0);
13762 }
13763 
13764 static void
13765 restart_all_uld(struct adapter *sc)
13766 {
13767 	int i;
13768 
13769 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
13770 		return;
13771 	sx_slock(&t4_uld_list_lock);
13772 	for (i = 0; i <= ULD_MAX; i++) {
13773 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
13774 		    t4_uld_list[i]->uld_restart == NULL)
13775 			continue;
13776 		(void) t4_uld_list[i]->uld_restart(sc);
13777 	}
13778 	sx_sunlock(&t4_uld_list_lock);
13779 	end_synchronized_op(sc, 0);
13780 }
13781 
13782 int
13783 uld_active(struct adapter *sc, int id)
13784 {
13785 
13786 	MPASS(id >= 0 && id <= ULD_MAX);
13787 
13788 	return (isset(&sc->active_ulds, id));
13789 }
13790 #endif
13791 
13792 #ifdef KERN_TLS
13793 static int
13794 ktls_capability(struct adapter *sc, bool enable)
13795 {
13796 	ASSERT_SYNCHRONIZED_OP(sc);
13797 
13798 	if (!is_ktls(sc))
13799 		return (ENODEV);
13800 	if (!is_t6(sc))
13801 		return (0);
13802 	if (!hw_all_ok(sc))
13803 		return (ENXIO);
13804 
13805 	if (enable) {
13806 		if (sc->flags & KERN_TLS_ON)
13807 			return (0);	/* already on */
13808 		if (sc->offload_map != 0) {
13809 			CH_WARN(sc,
13810 			    "Disable TOE on all interfaces associated with "
13811 			    "this adapter before trying to enable NIC TLS.\n");
13812 			return (EAGAIN);
13813 		}
13814 		return (t6_config_kern_tls(sc, true));
13815 	} else {
13816 		/*
13817 		 * Nothing to do for disable.  If TOE is enabled sometime later
13818 		 * then toe_capability will reconfigure the hardware.
13819 		 */
13820 		return (0);
13821 	}
13822 }
13823 #endif
13824 
13825 /*
13826  * t  = ptr to tunable.
13827  * nc = number of CPUs.
13828  * c  = compiled in default for that tunable.
13829  */
13830 static void
13831 calculate_nqueues(int *t, int nc, const int c)
13832 {
13833 	int nq;
13834 
13835 	if (*t > 0)
13836 		return;
13837 	nq = *t < 0 ? -*t : c;
13838 	*t = min(nc, nq);
13839 }
13840 
13841 /*
13842  * Come up with reasonable defaults for some of the tunables, provided they're
13843  * not set by the user (in which case we'll use the values as is).
13844  */
13845 static void
13846 tweak_tunables(void)
13847 {
13848 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
13849 
13850 	if (t4_ntxq < 1) {
13851 #ifdef RSS
13852 		t4_ntxq = rss_getnumbuckets();
13853 #else
13854 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
13855 #endif
13856 	}
13857 
13858 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
13859 
13860 	if (t4_nrxq < 1) {
13861 #ifdef RSS
13862 		t4_nrxq = rss_getnumbuckets();
13863 #else
13864 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
13865 #endif
13866 	}
13867 
13868 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
13869 
13870 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
13871 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
13872 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
13873 #endif
13874 #ifdef TCP_OFFLOAD
13875 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
13876 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
13877 #endif
13878 
13879 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
13880 	if (t4_toecaps_allowed == -1)
13881 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
13882 #else
13883 	if (t4_toecaps_allowed == -1)
13884 		t4_toecaps_allowed = 0;
13885 #endif
13886 
13887 #ifdef TCP_OFFLOAD
13888 	if (t4_rdmacaps_allowed == -1) {
13889 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
13890 		    FW_CAPS_CONFIG_RDMA_RDMAC;
13891 	}
13892 
13893 	if (t4_iscsicaps_allowed == -1) {
13894 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
13895 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
13896 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
13897 	}
13898 
13899 	if (t4_nvmecaps_allowed == -1)
13900 		t4_nvmecaps_allowed = FW_CAPS_CONFIG_NVME_TCP;
13901 
13902 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
13903 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
13904 
13905 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
13906 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
13907 #else
13908 	if (t4_rdmacaps_allowed == -1)
13909 		t4_rdmacaps_allowed = 0;
13910 
13911 	if (t4_iscsicaps_allowed == -1)
13912 		t4_iscsicaps_allowed = 0;
13913 
13914 	if (t4_nvmecaps_allowed == -1)
13915 		t4_nvmecaps_allowed = 0;
13916 #endif
13917 
13918 #ifdef DEV_NETMAP
13919 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
13920 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
13921 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
13922 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
13923 #endif
13924 
13925 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
13926 		t4_tmr_idx = TMR_IDX;
13927 
13928 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
13929 		t4_pktc_idx = PKTC_IDX;
13930 
13931 	if (t4_qsize_txq < 128)
13932 		t4_qsize_txq = 128;
13933 
13934 	if (t4_qsize_rxq < 128)
13935 		t4_qsize_rxq = 128;
13936 	while (t4_qsize_rxq & 7)
13937 		t4_qsize_rxq++;
13938 
13939 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
13940 
13941 	/*
13942 	 * Number of VIs to create per-port.  The first VI is the "main" regular
13943 	 * VI for the port.  The rest are additional virtual interfaces on the
13944 	 * same physical port.  Note that the main VI does not have native
13945 	 * netmap support but the extra VIs do.
13946 	 *
13947 	 * Limit the number of VIs per port to the number of available
13948 	 * MAC addresses per port.
13949 	 */
13950 	if (t4_num_vis < 1)
13951 		t4_num_vis = 1;
13952 	if (t4_num_vis > nitems(vi_mac_funcs)) {
13953 		t4_num_vis = nitems(vi_mac_funcs);
13954 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
13955 	}
13956 
13957 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
13958 		pcie_relaxed_ordering = 1;
13959 #if defined(__i386__) || defined(__amd64__)
13960 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
13961 			pcie_relaxed_ordering = 0;
13962 #endif
13963 	}
13964 }
13965 
13966 #ifdef DDB
13967 static void
13968 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
13969 {
13970 	uint32_t base, j, off, pf, reg, save, win_pos;
13971 
13972 	reg = chip_id(sc) > CHELSIO_T6 ?
13973 	    PCIE_MEM_ACCESS_T7_REG(A_PCIE_MEM_ACCESS_OFFSET0, 2) :
13974 	    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
13975 	save = t4_read_reg(sc, reg);
13976 	base = sc->memwin[2].mw_base;
13977 
13978 	if (is_t4(sc)) {
13979 		pf = 0;
13980 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
13981 	} else {
13982 		pf = V_PFNUM(sc->pf);
13983 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
13984 	}
13985 	off = addr - win_pos;
13986 	if (chip_id(sc) > CHELSIO_T6)
13987 		win_pos >>= X_T7_MEMOFST_SHIFT;
13988 	t4_write_reg(sc, reg, win_pos | pf);
13989 	t4_read_reg(sc, reg);
13990 
13991 	while (len > 0 && !db_pager_quit) {
13992 		uint32_t buf[8];
13993 		for (j = 0; j < 8; j++, off += 4)
13994 			buf[j] = htonl(t4_read_reg(sc, base + off));
13995 
13996 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
13997 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
13998 		    buf[7]);
13999 		if (len <= sizeof(buf))
14000 			len = 0;
14001 		else
14002 			len -= sizeof(buf);
14003 	}
14004 
14005 	t4_write_reg(sc, reg, save);
14006 	t4_read_reg(sc, reg);
14007 }
14008 
14009 static void
14010 t4_dump_tcb(struct adapter *sc, int tid)
14011 {
14012 	uint32_t tcb_addr;
14013 
14014 	/* Dump TCB for the tid */
14015 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
14016 	tcb_addr += tid * TCB_SIZE;
14017 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
14018 }
14019 
14020 static void
14021 t4_dump_devlog(struct adapter *sc)
14022 {
14023 	struct devlog_params *dparams = &sc->params.devlog;
14024 	struct fw_devlog_e e;
14025 	int i, first, j, m, nentries, rc;
14026 	uint64_t ftstamp = UINT64_MAX;
14027 
14028 	if (dparams->start == 0) {
14029 		db_printf("devlog params not valid\n");
14030 		return;
14031 	}
14032 
14033 	nentries = dparams->size / sizeof(struct fw_devlog_e);
14034 	m = fwmtype_to_hwmtype(dparams->memtype);
14035 
14036 	/* Find the first entry. */
14037 	first = -1;
14038 	for (i = 0; i < nentries && !db_pager_quit; i++) {
14039 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
14040 		    sizeof(e), (void *)&e);
14041 		if (rc != 0)
14042 			break;
14043 
14044 		if (e.timestamp == 0)
14045 			break;
14046 
14047 		e.timestamp = be64toh(e.timestamp);
14048 		if (e.timestamp < ftstamp) {
14049 			ftstamp = e.timestamp;
14050 			first = i;
14051 		}
14052 	}
14053 
14054 	if (first == -1)
14055 		return;
14056 
14057 	i = first;
14058 	do {
14059 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
14060 		    sizeof(e), (void *)&e);
14061 		if (rc != 0)
14062 			return;
14063 
14064 		if (e.timestamp == 0)
14065 			return;
14066 
14067 		e.timestamp = be64toh(e.timestamp);
14068 		e.seqno = be32toh(e.seqno);
14069 		for (j = 0; j < 8; j++)
14070 			e.params[j] = be32toh(e.params[j]);
14071 
14072 		db_printf("%10d  %15ju  %8s  %8s  ",
14073 		    e.seqno, e.timestamp,
14074 		    (e.level < nitems(devlog_level_strings) ?
14075 			devlog_level_strings[e.level] : "UNKNOWN"),
14076 		    (e.facility < nitems(devlog_facility_strings) ?
14077 			devlog_facility_strings[e.facility] : "UNKNOWN"));
14078 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
14079 		    e.params[3], e.params[4], e.params[5], e.params[6],
14080 		    e.params[7]);
14081 
14082 		if (++i == nentries)
14083 			i = 0;
14084 	} while (i != first && !db_pager_quit);
14085 }
14086 
14087 static DB_DEFINE_TABLE(show, t4, show_t4);
14088 
14089 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
14090 {
14091 	device_t dev;
14092 	int t;
14093 	bool valid;
14094 
14095 	valid = false;
14096 	t = db_read_token();
14097 	if (t == tIDENT) {
14098 		dev = device_lookup_by_name(db_tok_string);
14099 		valid = true;
14100 	}
14101 	db_skip_to_eol();
14102 	if (!valid) {
14103 		db_printf("usage: show t4 devlog <nexus>\n");
14104 		return;
14105 	}
14106 
14107 	if (dev == NULL) {
14108 		db_printf("device not found\n");
14109 		return;
14110 	}
14111 
14112 	t4_dump_devlog(device_get_softc(dev));
14113 }
14114 
14115 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
14116 {
14117 	device_t dev;
14118 	int radix, tid, t;
14119 	bool valid;
14120 
14121 	valid = false;
14122 	radix = db_radix;
14123 	db_radix = 10;
14124 	t = db_read_token();
14125 	if (t == tIDENT) {
14126 		dev = device_lookup_by_name(db_tok_string);
14127 		t = db_read_token();
14128 		if (t == tNUMBER) {
14129 			tid = db_tok_number;
14130 			valid = true;
14131 		}
14132 	}
14133 	db_radix = radix;
14134 	db_skip_to_eol();
14135 	if (!valid) {
14136 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
14137 		return;
14138 	}
14139 
14140 	if (dev == NULL) {
14141 		db_printf("device not found\n");
14142 		return;
14143 	}
14144 	if (tid < 0) {
14145 		db_printf("invalid tid\n");
14146 		return;
14147 	}
14148 
14149 	t4_dump_tcb(device_get_softc(dev), tid);
14150 }
14151 
14152 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
14153 {
14154 	device_t dev;
14155 	int radix, t;
14156 	bool valid;
14157 
14158 	valid = false;
14159 	radix = db_radix;
14160 	db_radix = 10;
14161 	t = db_read_token();
14162 	if (t == tIDENT) {
14163 		dev = device_lookup_by_name(db_tok_string);
14164 		t = db_read_token();
14165 		if (t == tNUMBER) {
14166 			addr = db_tok_number;
14167 			t = db_read_token();
14168 			if (t == tNUMBER) {
14169 				count = db_tok_number;
14170 				valid = true;
14171 			}
14172 		}
14173 	}
14174 	db_radix = radix;
14175 	db_skip_to_eol();
14176 	if (!valid) {
14177 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
14178 		return;
14179 	}
14180 
14181 	if (dev == NULL) {
14182 		db_printf("device not found\n");
14183 		return;
14184 	}
14185 	if (addr < 0) {
14186 		db_printf("invalid address\n");
14187 		return;
14188 	}
14189 	if (count <= 0) {
14190 		db_printf("invalid length\n");
14191 		return;
14192 	}
14193 
14194 	t4_dump_mem(device_get_softc(dev), addr, count);
14195 }
14196 #endif
14197 
14198 static eventhandler_tag vxlan_start_evtag;
14199 static eventhandler_tag vxlan_stop_evtag;
14200 
14201 struct vxlan_evargs {
14202 	if_t ifp;
14203 	uint16_t port;
14204 };
14205 
14206 static void
14207 enable_vxlan_rx(struct adapter *sc)
14208 {
14209 	int i, rc;
14210 	struct port_info *pi;
14211 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
14212 
14213 	ASSERT_SYNCHRONIZED_OP(sc);
14214 
14215 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
14216 	    F_VXLAN_EN);
14217 	for_each_port(sc, i) {
14218 		pi = sc->port[i];
14219 		if (pi->vxlan_tcam_entry == true)
14220 			continue;
14221 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
14222 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
14223 		    true);
14224 		if (rc < 0) {
14225 			rc = -rc;
14226 			CH_ERR(&pi->vi[0],
14227 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
14228 		} else {
14229 			MPASS(rc == sc->rawf_base + pi->port_id);
14230 			pi->vxlan_tcam_entry = true;
14231 		}
14232 	}
14233 }
14234 
14235 static void
14236 t4_vxlan_start(struct adapter *sc, void *arg)
14237 {
14238 	struct vxlan_evargs *v = arg;
14239 
14240 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14241 		return;
14242 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
14243 		return;
14244 
14245 	if (sc->vxlan_refcount == 0) {
14246 		sc->vxlan_port = v->port;
14247 		sc->vxlan_refcount = 1;
14248 		if (!hw_off_limits(sc))
14249 			enable_vxlan_rx(sc);
14250 	} else if (sc->vxlan_port == v->port) {
14251 		sc->vxlan_refcount++;
14252 	} else {
14253 		CH_ERR(sc, "VXLAN already configured on port  %d; "
14254 		    "ignoring attempt to configure it on port %d\n",
14255 		    sc->vxlan_port, v->port);
14256 	}
14257 	end_synchronized_op(sc, 0);
14258 }
14259 
14260 static void
14261 t4_vxlan_stop(struct adapter *sc, void *arg)
14262 {
14263 	struct vxlan_evargs *v = arg;
14264 
14265 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
14266 		return;
14267 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
14268 		return;
14269 
14270 	/*
14271 	 * VXLANs may have been configured before the driver was loaded so we
14272 	 * may see more stops than starts.  This is not handled cleanly but at
14273 	 * least we keep the refcount sane.
14274 	 */
14275 	if (sc->vxlan_port != v->port)
14276 		goto done;
14277 	if (sc->vxlan_refcount == 0) {
14278 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
14279 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
14280 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
14281 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
14282 done:
14283 	end_synchronized_op(sc, 0);
14284 }
14285 
14286 static void
14287 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
14288     sa_family_t family, u_int port)
14289 {
14290 	struct vxlan_evargs v;
14291 
14292 	MPASS(family == AF_INET || family == AF_INET6);
14293 	v.ifp = ifp;
14294 	v.port = port;
14295 
14296 	t4_iterate(t4_vxlan_start, &v);
14297 }
14298 
14299 static void
14300 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
14301     u_int port)
14302 {
14303 	struct vxlan_evargs v;
14304 
14305 	MPASS(family == AF_INET || family == AF_INET6);
14306 	v.ifp = ifp;
14307 	v.port = port;
14308 
14309 	t4_iterate(t4_vxlan_stop, &v);
14310 }
14311 
14312 
14313 static struct sx mlu;	/* mod load unload */
14314 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
14315 
14316 static int
14317 mod_event(module_t mod, int cmd, void *arg)
14318 {
14319 	int rc = 0;
14320 	static int loaded = 0;
14321 
14322 	switch (cmd) {
14323 	case MOD_LOAD:
14324 		sx_xlock(&mlu);
14325 		if (loaded++ == 0) {
14326 			t4_sge_modload();
14327 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14328 			    t4_filter_rpl, CPL_COOKIE_FILTER);
14329 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
14330 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
14331 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
14332 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
14333 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
14334 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
14335 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
14336 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
14337 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
14338 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
14339 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
14340 			    do_smt_write_rpl);
14341 			sx_init(&t4_list_lock, "T4/T5 adapters");
14342 			SLIST_INIT(&t4_list);
14343 			callout_init(&fatal_callout, 1);
14344 #ifdef TCP_OFFLOAD
14345 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
14346 #endif
14347 #ifdef INET6
14348 			t4_clip_modload();
14349 #endif
14350 #ifdef KERN_TLS
14351 			t6_ktls_modload();
14352 			t7_ktls_modload();
14353 #endif
14354 			t4_tracer_modload();
14355 			tweak_tunables();
14356 			vxlan_start_evtag =
14357 			    EVENTHANDLER_REGISTER(vxlan_start,
14358 				t4_vxlan_start_handler, NULL,
14359 				EVENTHANDLER_PRI_ANY);
14360 			vxlan_stop_evtag =
14361 			    EVENTHANDLER_REGISTER(vxlan_stop,
14362 				t4_vxlan_stop_handler, NULL,
14363 				EVENTHANDLER_PRI_ANY);
14364 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
14365 			    taskqueue_thread_enqueue, &reset_tq);
14366 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
14367 			    "t4_rst_thr");
14368 		}
14369 		sx_xunlock(&mlu);
14370 		break;
14371 
14372 	case MOD_UNLOAD:
14373 		sx_xlock(&mlu);
14374 		if (--loaded == 0) {
14375 #ifdef TCP_OFFLOAD
14376 			int i;
14377 #endif
14378 			int tries;
14379 
14380 			taskqueue_free(reset_tq);
14381 
14382 			tries = 0;
14383 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
14384 				uprintf("%ju clusters with custom free routine "
14385 				    "still is use.\n", t4_sge_extfree_refs());
14386 				pause("t4unload", 2 * hz);
14387 			}
14388 
14389 			sx_slock(&t4_list_lock);
14390 			if (!SLIST_EMPTY(&t4_list)) {
14391 				rc = EBUSY;
14392 				sx_sunlock(&t4_list_lock);
14393 				goto done_unload;
14394 			}
14395 #ifdef TCP_OFFLOAD
14396 			sx_slock(&t4_uld_list_lock);
14397 			for (i = 0; i <= ULD_MAX; i++) {
14398 				if (t4_uld_list[i] != NULL) {
14399 					rc = EBUSY;
14400 					sx_sunlock(&t4_uld_list_lock);
14401 					sx_sunlock(&t4_list_lock);
14402 					goto done_unload;
14403 				}
14404 			}
14405 			sx_sunlock(&t4_uld_list_lock);
14406 #endif
14407 			sx_sunlock(&t4_list_lock);
14408 
14409 			if (t4_sge_extfree_refs() == 0) {
14410 				EVENTHANDLER_DEREGISTER(vxlan_start,
14411 				    vxlan_start_evtag);
14412 				EVENTHANDLER_DEREGISTER(vxlan_stop,
14413 				    vxlan_stop_evtag);
14414 				t4_tracer_modunload();
14415 #ifdef KERN_TLS
14416 				t7_ktls_modunload();
14417 				t6_ktls_modunload();
14418 #endif
14419 #ifdef INET6
14420 				t4_clip_modunload();
14421 #endif
14422 #ifdef TCP_OFFLOAD
14423 				sx_destroy(&t4_uld_list_lock);
14424 #endif
14425 				sx_destroy(&t4_list_lock);
14426 				t4_sge_modunload();
14427 				loaded = 0;
14428 			} else {
14429 				rc = EBUSY;
14430 				loaded++;	/* undo earlier decrement */
14431 			}
14432 		}
14433 done_unload:
14434 		sx_xunlock(&mlu);
14435 		break;
14436 	}
14437 
14438 	return (rc);
14439 }
14440 
14441 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
14442 MODULE_VERSION(t4nex, 1);
14443 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
14444 #ifdef DEV_NETMAP
14445 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
14446 #endif /* DEV_NETMAP */
14447 
14448 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
14449 MODULE_VERSION(t5nex, 1);
14450 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
14451 #ifdef DEV_NETMAP
14452 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
14453 #endif /* DEV_NETMAP */
14454 
14455 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
14456 MODULE_VERSION(t6nex, 1);
14457 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
14458 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
14459 #ifdef DEV_NETMAP
14460 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
14461 #endif /* DEV_NETMAP */
14462 
14463 DRIVER_MODULE(chnex, pci, ch_driver, mod_event, 0);
14464 MODULE_VERSION(chnex, 1);
14465 MODULE_DEPEND(chnex, crypto, 1, 1, 1);
14466 MODULE_DEPEND(chnex, firmware, 1, 1, 1);
14467 #ifdef DEV_NETMAP
14468 MODULE_DEPEND(chnex, netmap, 1, 1, 1);
14469 #endif /* DEV_NETMAP */
14470 
14471 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
14472 MODULE_VERSION(cxgbe, 1);
14473 
14474 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
14475 MODULE_VERSION(cxl, 1);
14476 
14477 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
14478 MODULE_VERSION(cc, 1);
14479 
14480 DRIVER_MODULE(che, chnex, che_driver, 0, 0);
14481 MODULE_VERSION(che, 1);
14482 
14483 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
14484 MODULE_VERSION(vcxgbe, 1);
14485 
14486 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
14487 MODULE_VERSION(vcxl, 1);
14488 
14489 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
14490 MODULE_VERSION(vcc, 1);
14491 
14492 DRIVER_MODULE(vche, che, vche_driver, 0, 0);
14493 MODULE_VERSION(vche, 1);
14494