xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 59f5f100b774de8824fb2fc1a8a11a93bbc2dafd)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_kern_tls.h"
35 #include "opt_ratelimit.h"
36 #include "opt_rss.h"
37 
38 #include <sys/param.h>
39 #include <sys/conf.h>
40 #include <sys/priv.h>
41 #include <sys/kernel.h>
42 #include <sys/bus.h>
43 #include <sys/eventhandler.h>
44 #include <sys/module.h>
45 #include <sys/malloc.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <sys/pciio.h>
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pci_private.h>
52 #include <sys/firmware.h>
53 #include <sys/sbuf.h>
54 #include <sys/smp.h>
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/sysctl.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_types.h>
61 #include <net/if_dl.h>
62 #include <net/if_vlan_var.h>
63 #ifdef RSS
64 #include <net/rss_config.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #ifdef KERN_TLS
69 #include <netinet/tcp_seq.h>
70 #endif
71 #if defined(__i386__) || defined(__amd64__)
72 #include <machine/md_var.h>
73 #include <machine/cputypes.h>
74 #include <vm/vm.h>
75 #include <vm/pmap.h>
76 #endif
77 #ifdef DDB
78 #include <ddb/ddb.h>
79 #include <ddb/db_lex.h>
80 #endif
81 
82 #include "common/common.h"
83 #include "common/t4_msg.h"
84 #include "common/t4_regs.h"
85 #include "common/t4_regs_values.h"
86 #include "cudbg/cudbg.h"
87 #include "t4_clip.h"
88 #include "t4_ioctl.h"
89 #include "t4_l2t.h"
90 #include "t4_mp_ring.h"
91 #include "t4_if.h"
92 #include "t4_smt.h"
93 
94 /* T4 bus driver interface */
95 static int t4_probe(device_t);
96 static int t4_attach(device_t);
97 static int t4_detach(device_t);
98 static int t4_child_location(device_t, device_t, struct sbuf *);
99 static int t4_ready(device_t);
100 static int t4_read_port_device(device_t, int, device_t *);
101 static int t4_suspend(device_t);
102 static int t4_resume(device_t);
103 static int t4_reset_prepare(device_t, device_t);
104 static int t4_reset_post(device_t, device_t);
105 static device_method_t t4_methods[] = {
106 	DEVMETHOD(device_probe,		t4_probe),
107 	DEVMETHOD(device_attach,	t4_attach),
108 	DEVMETHOD(device_detach,	t4_detach),
109 	DEVMETHOD(device_suspend,	t4_suspend),
110 	DEVMETHOD(device_resume,	t4_resume),
111 
112 	DEVMETHOD(bus_child_location,	t4_child_location),
113 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
114 	DEVMETHOD(bus_reset_post,	t4_reset_post),
115 
116 	DEVMETHOD(t4_is_main_ready,	t4_ready),
117 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
118 
119 	DEVMETHOD_END
120 };
121 static driver_t t4_driver = {
122 	"t4nex",
123 	t4_methods,
124 	sizeof(struct adapter)
125 };
126 
127 
128 /* T4 port (cxgbe) interface */
129 static int cxgbe_probe(device_t);
130 static int cxgbe_attach(device_t);
131 static int cxgbe_detach(device_t);
132 device_method_t cxgbe_methods[] = {
133 	DEVMETHOD(device_probe,		cxgbe_probe),
134 	DEVMETHOD(device_attach,	cxgbe_attach),
135 	DEVMETHOD(device_detach,	cxgbe_detach),
136 	{ 0, 0 }
137 };
138 static driver_t cxgbe_driver = {
139 	"cxgbe",
140 	cxgbe_methods,
141 	sizeof(struct port_info)
142 };
143 
144 /* T4 VI (vcxgbe) interface */
145 static int vcxgbe_probe(device_t);
146 static int vcxgbe_attach(device_t);
147 static int vcxgbe_detach(device_t);
148 static device_method_t vcxgbe_methods[] = {
149 	DEVMETHOD(device_probe,		vcxgbe_probe),
150 	DEVMETHOD(device_attach,	vcxgbe_attach),
151 	DEVMETHOD(device_detach,	vcxgbe_detach),
152 	{ 0, 0 }
153 };
154 static driver_t vcxgbe_driver = {
155 	"vcxgbe",
156 	vcxgbe_methods,
157 	sizeof(struct vi_info)
158 };
159 
160 static d_ioctl_t t4_ioctl;
161 
162 static struct cdevsw t4_cdevsw = {
163        .d_version = D_VERSION,
164        .d_ioctl = t4_ioctl,
165        .d_name = "t4nex",
166 };
167 
168 /* T5 bus driver interface */
169 static int t5_probe(device_t);
170 static device_method_t t5_methods[] = {
171 	DEVMETHOD(device_probe,		t5_probe),
172 	DEVMETHOD(device_attach,	t4_attach),
173 	DEVMETHOD(device_detach,	t4_detach),
174 	DEVMETHOD(device_suspend,	t4_suspend),
175 	DEVMETHOD(device_resume,	t4_resume),
176 
177 	DEVMETHOD(bus_child_location,	t4_child_location),
178 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
179 	DEVMETHOD(bus_reset_post,	t4_reset_post),
180 
181 	DEVMETHOD(t4_is_main_ready,	t4_ready),
182 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
183 
184 	DEVMETHOD_END
185 };
186 static driver_t t5_driver = {
187 	"t5nex",
188 	t5_methods,
189 	sizeof(struct adapter)
190 };
191 
192 
193 /* T5 port (cxl) interface */
194 static driver_t cxl_driver = {
195 	"cxl",
196 	cxgbe_methods,
197 	sizeof(struct port_info)
198 };
199 
200 /* T5 VI (vcxl) interface */
201 static driver_t vcxl_driver = {
202 	"vcxl",
203 	vcxgbe_methods,
204 	sizeof(struct vi_info)
205 };
206 
207 /* T6 bus driver interface */
208 static int t6_probe(device_t);
209 static device_method_t t6_methods[] = {
210 	DEVMETHOD(device_probe,		t6_probe),
211 	DEVMETHOD(device_attach,	t4_attach),
212 	DEVMETHOD(device_detach,	t4_detach),
213 	DEVMETHOD(device_suspend,	t4_suspend),
214 	DEVMETHOD(device_resume,	t4_resume),
215 
216 	DEVMETHOD(bus_child_location,	t4_child_location),
217 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
218 	DEVMETHOD(bus_reset_post,	t4_reset_post),
219 
220 	DEVMETHOD(t4_is_main_ready,	t4_ready),
221 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
222 
223 	DEVMETHOD_END
224 };
225 static driver_t t6_driver = {
226 	"t6nex",
227 	t6_methods,
228 	sizeof(struct adapter)
229 };
230 
231 
232 /* T6 port (cc) interface */
233 static driver_t cc_driver = {
234 	"cc",
235 	cxgbe_methods,
236 	sizeof(struct port_info)
237 };
238 
239 /* T6 VI (vcc) interface */
240 static driver_t vcc_driver = {
241 	"vcc",
242 	vcxgbe_methods,
243 	sizeof(struct vi_info)
244 };
245 
246 /* ifnet interface */
247 static void cxgbe_init(void *);
248 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
249 static int cxgbe_transmit(if_t, struct mbuf *);
250 static void cxgbe_qflush(if_t);
251 #if defined(KERN_TLS) || defined(RATELIMIT)
252 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
253     struct m_snd_tag **);
254 #endif
255 
256 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
257 
258 /*
259  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
260  * then ADAPTER_LOCK, then t4_uld_list_lock.
261  */
262 static struct sx t4_list_lock;
263 SLIST_HEAD(, adapter) t4_list;
264 #ifdef TCP_OFFLOAD
265 static struct sx t4_uld_list_lock;
266 struct uld_info *t4_uld_list[ULD_MAX + 1];
267 #endif
268 
269 /*
270  * Tunables.  See tweak_tunables() too.
271  *
272  * Each tunable is set to a default value here if it's known at compile-time.
273  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274  * provide a reasonable default (upto n) when the driver is loaded.
275  *
276  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277  * T5 are under hw.cxl.
278  */
279 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280     "cxgbe(4) parameters");
281 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) T5+ parameters");
283 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) TOE parameters");
285 
286 /*
287  * Number of queues for tx and rx, NIC and offload.
288  */
289 #define NTXQ 16
290 int t4_ntxq = -NTXQ;
291 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292     "Number of TX queues per port");
293 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294 
295 #define NRXQ 8
296 int t4_nrxq = -NRXQ;
297 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298     "Number of RX queues per port");
299 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300 
301 #define NTXQ_VI 1
302 static int t4_ntxq_vi = -NTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304     "Number of TX queues per VI");
305 
306 #define NRXQ_VI 1
307 static int t4_nrxq_vi = -NRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309     "Number of RX queues per VI");
310 
311 static int t4_rsrv_noflowq = 0;
312 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313     0, "Reserve TX queue 0 of each VI for non-flowid packets");
314 
315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316 #define NOFLDTXQ 8
317 static int t4_nofldtxq = -NOFLDTXQ;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319     "Number of offload TX queues per port");
320 
321 #define NOFLDRXQ 2
322 static int t4_nofldrxq = -NOFLDRXQ;
323 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324     "Number of offload RX queues per port");
325 
326 #define NOFLDTXQ_VI 1
327 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329     "Number of offload TX queues per VI");
330 
331 #define NOFLDRXQ_VI 1
332 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334     "Number of offload RX queues per VI");
335 
336 #define TMR_IDX_OFLD 1
337 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340 
341 #define PKTC_IDX_OFLD (-1)
342 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345 
346 /* 0 means chip/fw default, non-zero number is value in microseconds */
347 static u_long t4_toe_keepalive_idle = 0;
348 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350 
351 /* 0 means chip/fw default, non-zero number is value in microseconds */
352 static u_long t4_toe_keepalive_interval = 0;
353 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355 
356 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357 static int t4_toe_keepalive_count = 0;
358 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360 
361 /* 0 means chip/fw default, non-zero number is value in microseconds */
362 static u_long t4_toe_rexmt_min = 0;
363 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365 
366 /* 0 means chip/fw default, non-zero number is value in microseconds */
367 static u_long t4_toe_rexmt_max = 0;
368 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370 
371 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372 static int t4_toe_rexmt_count = 0;
373 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375 
376 /* -1 means chip/fw default, other values are raw backoff values to use */
377 static int t4_toe_rexmt_backoff[16] = {
378 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379 };
380 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382     "cxgbe(4) TOE retransmit backoff values");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[0], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[1], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[2], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[3], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[4], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[5], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[6], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[7], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[8], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[9], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[10], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[11], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[12], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[13], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[14], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[15], 0, "");
415 
416 int t4_ddp_rcvbuf_len = 256 * 1024;
417 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
418     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
419 
420 unsigned int t4_ddp_rcvbuf_cache = 4;
421 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
422     &t4_ddp_rcvbuf_cache, 0,
423     "maximum number of free DDP RX buffers to cache per connection");
424 #endif
425 
426 #ifdef DEV_NETMAP
427 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
428 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
429 static int t4_native_netmap = NN_EXTRA_VI;
430 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
431     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
432 
433 #define NNMTXQ 8
434 static int t4_nnmtxq = -NNMTXQ;
435 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
436     "Number of netmap TX queues");
437 
438 #define NNMRXQ 8
439 static int t4_nnmrxq = -NNMRXQ;
440 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
441     "Number of netmap RX queues");
442 
443 #define NNMTXQ_VI 2
444 static int t4_nnmtxq_vi = -NNMTXQ_VI;
445 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
446     "Number of netmap TX queues per VI");
447 
448 #define NNMRXQ_VI 2
449 static int t4_nnmrxq_vi = -NNMRXQ_VI;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
451     "Number of netmap RX queues per VI");
452 #endif
453 
454 /*
455  * Holdoff parameters for ports.
456  */
457 #define TMR_IDX 1
458 int t4_tmr_idx = TMR_IDX;
459 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
460     0, "Holdoff timer index");
461 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
462 
463 #define PKTC_IDX (-1)
464 int t4_pktc_idx = PKTC_IDX;
465 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
466     0, "Holdoff packet counter index");
467 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
468 
469 /*
470  * Size (# of entries) of each tx and rx queue.
471  */
472 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
473 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
474     "Number of descriptors in each TX queue");
475 
476 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
477 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
478     "Number of descriptors in each RX queue");
479 
480 /*
481  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
482  */
483 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
485     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
486 
487 /*
488  * Configuration file.  All the _CF names here are special.
489  */
490 #define DEFAULT_CF	"default"
491 #define BUILTIN_CF	"built-in"
492 #define FLASH_CF	"flash"
493 #define UWIRE_CF	"uwire"
494 #define FPGA_CF		"fpga"
495 static char t4_cfg_file[32] = DEFAULT_CF;
496 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
497     sizeof(t4_cfg_file), "Firmware configuration file");
498 
499 /*
500  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
501  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
502  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
503  *            mark or when signalled to do so, 0 to never emit PAUSE.
504  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
505  *                 negotiated settings will override rx_pause/tx_pause.
506  *                 Otherwise rx_pause/tx_pause are applied forcibly.
507  */
508 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
509 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
510     &t4_pause_settings, 0,
511     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
512 
513 /*
514  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
515  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
516  *  0 to disable FEC.
517  */
518 static int t4_fec = -1;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
520     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
521 
522 /*
523  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
524  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
525  * driver runs as if this is set to 0.
526  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
527  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
528  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
529  *    the firmware anyway (may result in l1cfg errors with old firmwares).
530  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
531  *    means set all FEC bits that are valid for the speed.
532  */
533 static int t4_force_fec = -1;
534 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
535     "Controls the use of FORCE_FEC bit in L1 configuration.");
536 
537 /*
538  * Link autonegotiation.
539  * -1 to run with the firmware default.
540  *  0 to disable.
541  *  1 to enable.
542  */
543 static int t4_autoneg = -1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
545     "Link autonegotiation");
546 
547 /*
548  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
549  * encouraged respectively).  '-n' is the same as 'n' except the firmware
550  * version used in the checks is read from the firmware bundled with the driver.
551  */
552 static int t4_fw_install = 1;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
554     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
555 
556 /*
557  * ASIC features that will be used.  Disable the ones you don't want so that the
558  * chip resources aren't wasted on features that will not be used.
559  */
560 static int t4_nbmcaps_allowed = 0;
561 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
562     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
563 
564 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
565 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
566     &t4_linkcaps_allowed, 0, "Default link capabilities");
567 
568 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
569     FW_CAPS_CONFIG_SWITCH_EGRESS;
570 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
571     &t4_switchcaps_allowed, 0, "Default switch capabilities");
572 
573 #ifdef RATELIMIT
574 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
575 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
576 #else
577 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
578 	FW_CAPS_CONFIG_NIC_HASHFILTER;
579 #endif
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
581     &t4_niccaps_allowed, 0, "Default NIC capabilities");
582 
583 static int t4_toecaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
585     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
586 
587 static int t4_rdmacaps_allowed = -1;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
589     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
590 
591 static int t4_cryptocaps_allowed = -1;
592 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
593     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
594 
595 static int t4_iscsicaps_allowed = -1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
597     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
598 
599 static int t4_fcoecaps_allowed = 0;
600 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
601     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
602 
603 static int t5_write_combine = 0;
604 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
605     0, "Use WC instead of UC for BAR2");
606 
607 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
608 static int t4_doorbells_allowed = 0xf;
609 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
610 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
611 
612 static int t4_num_vis = 1;
613 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
614     "Number of VIs per port");
615 
616 /*
617  * PCIe Relaxed Ordering.
618  * -1: driver should figure out a good value.
619  * 0: disable RO.
620  * 1: enable RO.
621  * 2: leave RO alone.
622  */
623 static int pcie_relaxed_ordering = -1;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
625     &pcie_relaxed_ordering, 0,
626     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
627 
628 static int t4_panic_on_fatal_err = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
630     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
631 
632 static int t4_reset_on_fatal_err = 0;
633 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
634     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
635 
636 static int t4_clock_gate_on_suspend = 0;
637 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
638     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
639 
640 static int t4_tx_vm_wr = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
642     "Use VM work requests to transmit packets.");
643 
644 /*
645  * Set to non-zero to enable the attack filter.  A packet that matches any of
646  * these conditions will get dropped on ingress:
647  * 1) IP && source address == destination address.
648  * 2) TCP/IP && source address is not a unicast address.
649  * 3) TCP/IP && destination address is not a unicast address.
650  * 4) IP && source address is loopback (127.x.y.z).
651  * 5) IP && destination address is loopback (127.x.y.z).
652  * 6) IPv6 && source address == destination address.
653  * 7) IPv6 && source address is not a unicast address.
654  * 8) IPv6 && source address is loopback (::1/128).
655  * 9) IPv6 && destination address is loopback (::1/128).
656  * 10) IPv6 && source address is unspecified (::/128).
657  * 11) IPv6 && destination address is unspecified (::/128).
658  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
659  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
660  */
661 static int t4_attack_filter = 0;
662 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
663     &t4_attack_filter, 0, "Drop suspicious traffic");
664 
665 static int t4_drop_ip_fragments = 0;
666 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
667     &t4_drop_ip_fragments, 0, "Drop IP fragments");
668 
669 static int t4_drop_pkts_with_l2_errors = 1;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
671     &t4_drop_pkts_with_l2_errors, 0,
672     "Drop all frames with Layer 2 length or checksum errors");
673 
674 static int t4_drop_pkts_with_l3_errors = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l3_errors, 0,
677     "Drop all frames with IP version, length, or checksum errors");
678 
679 static int t4_drop_pkts_with_l4_errors = 0;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
681     &t4_drop_pkts_with_l4_errors, 0,
682     "Drop all frames with Layer 4 length, checksum, or other errors");
683 
684 #ifdef TCP_OFFLOAD
685 /*
686  * TOE tunables.
687  */
688 static int t4_cop_managed_offloading = 0;
689 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
690     &t4_cop_managed_offloading, 0,
691     "COP (Connection Offload Policy) controls all TOE offload");
692 #endif
693 
694 #ifdef KERN_TLS
695 /*
696  * This enables KERN_TLS for all adapters if set.
697  */
698 static int t4_kern_tls = 0;
699 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
700     "Enable KERN_TLS mode for T6 adapters");
701 
702 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
703     "cxgbe(4) KERN_TLS parameters");
704 
705 static int t4_tls_inline_keys = 0;
706 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
707     &t4_tls_inline_keys, 0,
708     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
709     "in card memory.");
710 
711 static int t4_tls_combo_wrs = 0;
712 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
713     0, "Attempt to combine TCB field updates with TLS record work requests.");
714 #endif
715 
716 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
717 static int vi_mac_funcs[] = {
718 	FW_VI_FUNC_ETH,
719 	FW_VI_FUNC_OFLD,
720 	FW_VI_FUNC_IWARP,
721 	FW_VI_FUNC_OPENISCSI,
722 	FW_VI_FUNC_OPENFCOE,
723 	FW_VI_FUNC_FOISCSI,
724 	FW_VI_FUNC_FOFCOE,
725 };
726 
727 struct intrs_and_queues {
728 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
729 	uint16_t num_vis;	/* number of VIs for each port */
730 	uint16_t nirq;		/* Total # of vectors */
731 	uint16_t ntxq;		/* # of NIC txq's for each port */
732 	uint16_t nrxq;		/* # of NIC rxq's for each port */
733 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
734 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
735 	uint16_t nnmtxq;	/* # of netmap txq's */
736 	uint16_t nnmrxq;	/* # of netmap rxq's */
737 
738 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
739 	uint16_t ntxq_vi;	/* # of NIC txq's */
740 	uint16_t nrxq_vi;	/* # of NIC rxq's */
741 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
742 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
743 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
744 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
745 };
746 
747 static void setup_memwin(struct adapter *);
748 static void position_memwin(struct adapter *, int, uint32_t);
749 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
750 static int fwmtype_to_hwmtype(int);
751 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
752     uint32_t *);
753 static int fixup_devlog_params(struct adapter *);
754 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
755 static int contact_firmware(struct adapter *);
756 static int partition_resources(struct adapter *);
757 static int get_params__pre_init(struct adapter *);
758 static int set_params__pre_init(struct adapter *);
759 static int get_params__post_init(struct adapter *);
760 static int set_params__post_init(struct adapter *);
761 static void t4_set_desc(struct adapter *);
762 static bool fixed_ifmedia(struct port_info *);
763 static void build_medialist(struct port_info *);
764 static void init_link_config(struct port_info *);
765 static int fixup_link_config(struct port_info *);
766 static int apply_link_config(struct port_info *);
767 static int cxgbe_init_synchronized(struct vi_info *);
768 static int cxgbe_uninit_synchronized(struct vi_info *);
769 static int adapter_full_init(struct adapter *);
770 static void adapter_full_uninit(struct adapter *);
771 static int vi_full_init(struct vi_info *);
772 static void vi_full_uninit(struct vi_info *);
773 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
774 static void quiesce_txq(struct sge_txq *);
775 static void quiesce_wrq(struct sge_wrq *);
776 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
777 static void quiesce_vi(struct vi_info *);
778 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
779     driver_intr_t *, void *, char *);
780 static int t4_free_irq(struct adapter *, struct irq *);
781 static void t4_init_atid_table(struct adapter *);
782 static void t4_free_atid_table(struct adapter *);
783 static void stop_atid_allocator(struct adapter *);
784 static void restart_atid_allocator(struct adapter *);
785 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
786 static void vi_refresh_stats(struct vi_info *);
787 static void cxgbe_refresh_stats(struct vi_info *);
788 static void cxgbe_tick(void *);
789 static void vi_tick(void *);
790 static void cxgbe_sysctls(struct port_info *);
791 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
792 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
793 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
794 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
795 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
796 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
797 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
798 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
799 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
800 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
802 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
803 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
804 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
805 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
806 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
807 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
808 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
809 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
810 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
811 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
812 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
813 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
814 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
817 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
818 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
822 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
824 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
825 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
826 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
827 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
828 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
829 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
830 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
831 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
839 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
840 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
841 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
842 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
843 #ifdef TCP_OFFLOAD
844 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
845 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
846 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
847 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
848 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
849 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
850 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
851 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
852 #endif
853 static int get_sge_context(struct adapter *, struct t4_sge_context *);
854 static int load_fw(struct adapter *, struct t4_data *);
855 static int load_cfg(struct adapter *, struct t4_data *);
856 static int load_boot(struct adapter *, struct t4_bootrom *);
857 static int load_bootcfg(struct adapter *, struct t4_data *);
858 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
859 static void free_offload_policy(struct t4_offload_policy *);
860 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
861 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
862 static int read_i2c(struct adapter *, struct t4_i2c_data *);
863 static int clear_stats(struct adapter *, u_int);
864 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
865 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
866 static inline int stop_adapter(struct adapter *);
867 static inline void set_adapter_hwstatus(struct adapter *, const bool);
868 static int stop_lld(struct adapter *);
869 static inline int restart_adapter(struct adapter *);
870 static int restart_lld(struct adapter *);
871 #ifdef TCP_OFFLOAD
872 static int deactivate_all_uld(struct adapter *);
873 static void stop_all_uld(struct adapter *);
874 static void restart_all_uld(struct adapter *);
875 #endif
876 #ifdef KERN_TLS
877 static int ktls_capability(struct adapter *, bool);
878 #endif
879 static int mod_event(module_t, int, void *);
880 static int notify_siblings(device_t, int);
881 static uint64_t vi_get_counter(if_t, ift_counter);
882 static uint64_t cxgbe_get_counter(if_t, ift_counter);
883 static void enable_vxlan_rx(struct adapter *);
884 static void reset_adapter_task(void *, int);
885 static void fatal_error_task(void *, int);
886 static void dump_devlog(struct adapter *);
887 static void dump_cim_regs(struct adapter *);
888 static void dump_cimla(struct adapter *);
889 
890 struct {
891 	uint16_t device;
892 	char *desc;
893 } t4_pciids[] = {
894 	{0xa000, "Chelsio Terminator 4 FPGA"},
895 	{0x4400, "Chelsio T440-dbg"},
896 	{0x4401, "Chelsio T420-CR"},
897 	{0x4402, "Chelsio T422-CR"},
898 	{0x4403, "Chelsio T440-CR"},
899 	{0x4404, "Chelsio T420-BCH"},
900 	{0x4405, "Chelsio T440-BCH"},
901 	{0x4406, "Chelsio T440-CH"},
902 	{0x4407, "Chelsio T420-SO"},
903 	{0x4408, "Chelsio T420-CX"},
904 	{0x4409, "Chelsio T420-BT"},
905 	{0x440a, "Chelsio T404-BT"},
906 	{0x440e, "Chelsio T440-LP-CR"},
907 }, t5_pciids[] = {
908 	{0xb000, "Chelsio Terminator 5 FPGA"},
909 	{0x5400, "Chelsio T580-dbg"},
910 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
911 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
912 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
913 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
914 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
915 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
916 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
917 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
918 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
919 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
920 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
921 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
922 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
923 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
924 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
925 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
926 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
927 
928 	/* Custom */
929 	{0x5483, "Custom T540-CR"},
930 	{0x5484, "Custom T540-BT"},
931 }, t6_pciids[] = {
932 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
933 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
934 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
935 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
936 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
937 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
938 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
939 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
940 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
941 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
942 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
943 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
944 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
945 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
946 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
947 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
948 
949 	/* Custom */
950 	{0x6480, "Custom T6225-CR"},
951 	{0x6481, "Custom T62100-CR"},
952 	{0x6482, "Custom T6225-CR"},
953 	{0x6483, "Custom T62100-CR"},
954 	{0x6484, "Custom T64100-CR"},
955 	{0x6485, "Custom T6240-SO"},
956 	{0x6486, "Custom T6225-SO-CR"},
957 	{0x6487, "Custom T6225-CR"},
958 };
959 
960 #ifdef TCP_OFFLOAD
961 /*
962  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
963  * be exactly the same for both rxq and ofld_rxq.
964  */
965 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
966 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
967 #endif
968 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
969 
970 static int
971 t4_probe(device_t dev)
972 {
973 	int i;
974 	uint16_t v = pci_get_vendor(dev);
975 	uint16_t d = pci_get_device(dev);
976 	uint8_t f = pci_get_function(dev);
977 
978 	if (v != PCI_VENDOR_ID_CHELSIO)
979 		return (ENXIO);
980 
981 	/* Attach only to PF0 of the FPGA */
982 	if (d == 0xa000 && f != 0)
983 		return (ENXIO);
984 
985 	for (i = 0; i < nitems(t4_pciids); i++) {
986 		if (d == t4_pciids[i].device) {
987 			device_set_desc(dev, t4_pciids[i].desc);
988 			return (BUS_PROBE_DEFAULT);
989 		}
990 	}
991 
992 	return (ENXIO);
993 }
994 
995 static int
996 t5_probe(device_t dev)
997 {
998 	int i;
999 	uint16_t v = pci_get_vendor(dev);
1000 	uint16_t d = pci_get_device(dev);
1001 	uint8_t f = pci_get_function(dev);
1002 
1003 	if (v != PCI_VENDOR_ID_CHELSIO)
1004 		return (ENXIO);
1005 
1006 	/* Attach only to PF0 of the FPGA */
1007 	if (d == 0xb000 && f != 0)
1008 		return (ENXIO);
1009 
1010 	for (i = 0; i < nitems(t5_pciids); i++) {
1011 		if (d == t5_pciids[i].device) {
1012 			device_set_desc(dev, t5_pciids[i].desc);
1013 			return (BUS_PROBE_DEFAULT);
1014 		}
1015 	}
1016 
1017 	return (ENXIO);
1018 }
1019 
1020 static int
1021 t6_probe(device_t dev)
1022 {
1023 	int i;
1024 	uint16_t v = pci_get_vendor(dev);
1025 	uint16_t d = pci_get_device(dev);
1026 
1027 	if (v != PCI_VENDOR_ID_CHELSIO)
1028 		return (ENXIO);
1029 
1030 	for (i = 0; i < nitems(t6_pciids); i++) {
1031 		if (d == t6_pciids[i].device) {
1032 			device_set_desc(dev, t6_pciids[i].desc);
1033 			return (BUS_PROBE_DEFAULT);
1034 		}
1035 	}
1036 
1037 	return (ENXIO);
1038 }
1039 
1040 static void
1041 t5_attribute_workaround(device_t dev)
1042 {
1043 	device_t root_port;
1044 	uint32_t v;
1045 
1046 	/*
1047 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1048 	 * Ordering attributes when replying to a TLP from a Root
1049 	 * Port.  As a workaround, find the parent Root Port and
1050 	 * disable No Snoop and Relaxed Ordering.  Note that this
1051 	 * affects all devices under this root port.
1052 	 */
1053 	root_port = pci_find_pcie_root_port(dev);
1054 	if (root_port == NULL) {
1055 		device_printf(dev, "Unable to find parent root port\n");
1056 		return;
1057 	}
1058 
1059 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1060 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1061 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1062 	    0)
1063 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1064 		    device_get_nameunit(root_port));
1065 }
1066 
1067 static const struct devnames devnames[] = {
1068 	{
1069 		.nexus_name = "t4nex",
1070 		.ifnet_name = "cxgbe",
1071 		.vi_ifnet_name = "vcxgbe",
1072 		.pf03_drv_name = "t4iov",
1073 		.vf_nexus_name = "t4vf",
1074 		.vf_ifnet_name = "cxgbev"
1075 	}, {
1076 		.nexus_name = "t5nex",
1077 		.ifnet_name = "cxl",
1078 		.vi_ifnet_name = "vcxl",
1079 		.pf03_drv_name = "t5iov",
1080 		.vf_nexus_name = "t5vf",
1081 		.vf_ifnet_name = "cxlv"
1082 	}, {
1083 		.nexus_name = "t6nex",
1084 		.ifnet_name = "cc",
1085 		.vi_ifnet_name = "vcc",
1086 		.pf03_drv_name = "t6iov",
1087 		.vf_nexus_name = "t6vf",
1088 		.vf_ifnet_name = "ccv"
1089 	}
1090 };
1091 
1092 void
1093 t4_init_devnames(struct adapter *sc)
1094 {
1095 	int id;
1096 
1097 	id = chip_id(sc);
1098 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1099 		sc->names = &devnames[id - CHELSIO_T4];
1100 	else {
1101 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1102 		sc->names = NULL;
1103 	}
1104 }
1105 
1106 static int
1107 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1108 {
1109 	const char *parent, *name;
1110 	long value;
1111 	int line, unit;
1112 
1113 	line = 0;
1114 	parent = device_get_nameunit(sc->dev);
1115 	name = sc->names->ifnet_name;
1116 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1117 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1118 		    value == pi->port_id)
1119 			return (unit);
1120 	}
1121 	return (-1);
1122 }
1123 
1124 static void
1125 t4_calibration(void *arg)
1126 {
1127 	struct adapter *sc;
1128 	struct clock_sync *cur, *nex;
1129 	uint64_t hw;
1130 	sbintime_t sbt;
1131 	int next_up;
1132 
1133 	sc = (struct adapter *)arg;
1134 
1135 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1136 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1137 	sbt = sbinuptime();
1138 
1139 	cur = &sc->cal_info[sc->cal_current];
1140 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1141 	nex = &sc->cal_info[next_up];
1142 	if (__predict_false(sc->cal_count == 0)) {
1143 		/* First time in, just get the values in */
1144 		cur->hw_cur = hw;
1145 		cur->sbt_cur = sbt;
1146 		sc->cal_count++;
1147 		goto done;
1148 	}
1149 
1150 	if (cur->hw_cur == hw) {
1151 		/* The clock is not advancing? */
1152 		sc->cal_count = 0;
1153 		atomic_store_rel_int(&cur->gen, 0);
1154 		goto done;
1155 	}
1156 
1157 	seqc_write_begin(&nex->gen);
1158 	nex->hw_prev = cur->hw_cur;
1159 	nex->sbt_prev = cur->sbt_cur;
1160 	nex->hw_cur = hw;
1161 	nex->sbt_cur = sbt;
1162 	seqc_write_end(&nex->gen);
1163 	sc->cal_current = next_up;
1164 done:
1165 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1166 	    sc, C_DIRECT_EXEC);
1167 }
1168 
1169 static void
1170 t4_calibration_start(struct adapter *sc)
1171 {
1172 	/*
1173 	 * Here if we have not done a calibration
1174 	 * then do so otherwise start the appropriate
1175 	 * timer.
1176 	 */
1177 	int i;
1178 
1179 	for (i = 0; i < CNT_CAL_INFO; i++) {
1180 		sc->cal_info[i].gen = 0;
1181 	}
1182 	sc->cal_current = 0;
1183 	sc->cal_count = 0;
1184 	sc->cal_gen = 0;
1185 	t4_calibration(sc);
1186 }
1187 
1188 static int
1189 t4_attach(device_t dev)
1190 {
1191 	struct adapter *sc;
1192 	int rc = 0, i, j, rqidx, tqidx, nports;
1193 	struct make_dev_args mda;
1194 	struct intrs_and_queues iaq;
1195 	struct sge *s;
1196 	uint32_t *buf;
1197 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1198 	int ofld_tqidx;
1199 #endif
1200 #ifdef TCP_OFFLOAD
1201 	int ofld_rqidx;
1202 #endif
1203 #ifdef DEV_NETMAP
1204 	int nm_rqidx, nm_tqidx;
1205 #endif
1206 	int num_vis;
1207 
1208 	sc = device_get_softc(dev);
1209 	sc->dev = dev;
1210 	sysctl_ctx_init(&sc->ctx);
1211 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1212 
1213 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1214 		t5_attribute_workaround(dev);
1215 	pci_enable_busmaster(dev);
1216 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1217 		uint32_t v;
1218 
1219 		pci_set_max_read_req(dev, 4096);
1220 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1221 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1222 		if (pcie_relaxed_ordering == 0 &&
1223 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1224 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1225 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1226 		} else if (pcie_relaxed_ordering == 1 &&
1227 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1228 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1229 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1230 		}
1231 	}
1232 
1233 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1234 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1235 	sc->traceq = -1;
1236 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1237 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1238 	    device_get_nameunit(dev));
1239 
1240 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1241 	    device_get_nameunit(dev));
1242 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1243 	t4_add_adapter(sc);
1244 
1245 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1246 	TAILQ_INIT(&sc->sfl);
1247 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1248 
1249 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1250 
1251 	sc->policy = NULL;
1252 	rw_init(&sc->policy_lock, "connection offload policy");
1253 
1254 	callout_init(&sc->ktls_tick, 1);
1255 
1256 	callout_init(&sc->cal_callout, 1);
1257 
1258 	refcount_init(&sc->vxlan_refcount, 0);
1259 
1260 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1261 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1262 
1263 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1264 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1265 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1266 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1267 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1268 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1269 
1270 	rc = t4_map_bars_0_and_4(sc);
1271 	if (rc != 0)
1272 		goto done; /* error message displayed already */
1273 
1274 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1275 
1276 	/* Prepare the adapter for operation. */
1277 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1278 	rc = -t4_prep_adapter(sc, buf);
1279 	free(buf, M_CXGBE);
1280 	if (rc != 0) {
1281 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1282 		goto done;
1283 	}
1284 
1285 	/*
1286 	 * This is the real PF# to which we're attaching.  Works from within PCI
1287 	 * passthrough environments too, where pci_get_function() could return a
1288 	 * different PF# depending on the passthrough configuration.  We need to
1289 	 * use the real PF# in all our communication with the firmware.
1290 	 */
1291 	j = t4_read_reg(sc, A_PL_WHOAMI);
1292 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1293 	sc->mbox = sc->pf;
1294 
1295 	t4_init_devnames(sc);
1296 	if (sc->names == NULL) {
1297 		rc = ENOTSUP;
1298 		goto done; /* error message displayed already */
1299 	}
1300 
1301 	/*
1302 	 * Do this really early, with the memory windows set up even before the
1303 	 * character device.  The userland tool's register i/o and mem read
1304 	 * will work even in "recovery mode".
1305 	 */
1306 	setup_memwin(sc);
1307 	if (t4_init_devlog_params(sc, 0) == 0)
1308 		fixup_devlog_params(sc);
1309 	make_dev_args_init(&mda);
1310 	mda.mda_devsw = &t4_cdevsw;
1311 	mda.mda_uid = UID_ROOT;
1312 	mda.mda_gid = GID_WHEEL;
1313 	mda.mda_mode = 0600;
1314 	mda.mda_si_drv1 = sc;
1315 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1316 	if (rc != 0)
1317 		device_printf(dev, "failed to create nexus char device: %d.\n",
1318 		    rc);
1319 
1320 	/* Go no further if recovery mode has been requested. */
1321 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1322 		device_printf(dev, "recovery mode.\n");
1323 		goto done;
1324 	}
1325 
1326 #if defined(__i386__)
1327 	if ((cpu_feature & CPUID_CX8) == 0) {
1328 		device_printf(dev, "64 bit atomics not available.\n");
1329 		rc = ENOTSUP;
1330 		goto done;
1331 	}
1332 #endif
1333 
1334 	/* Contact the firmware and try to become the master driver. */
1335 	rc = contact_firmware(sc);
1336 	if (rc != 0)
1337 		goto done; /* error message displayed already */
1338 	MPASS(sc->flags & FW_OK);
1339 
1340 	rc = get_params__pre_init(sc);
1341 	if (rc != 0)
1342 		goto done; /* error message displayed already */
1343 
1344 	if (sc->flags & MASTER_PF) {
1345 		rc = partition_resources(sc);
1346 		if (rc != 0)
1347 			goto done; /* error message displayed already */
1348 	}
1349 
1350 	rc = get_params__post_init(sc);
1351 	if (rc != 0)
1352 		goto done; /* error message displayed already */
1353 
1354 	rc = set_params__post_init(sc);
1355 	if (rc != 0)
1356 		goto done; /* error message displayed already */
1357 
1358 	rc = t4_map_bar_2(sc);
1359 	if (rc != 0)
1360 		goto done; /* error message displayed already */
1361 
1362 	rc = t4_adj_doorbells(sc);
1363 	if (rc != 0)
1364 		goto done; /* error message displayed already */
1365 
1366 	rc = t4_create_dma_tag(sc);
1367 	if (rc != 0)
1368 		goto done; /* error message displayed already */
1369 
1370 	/*
1371 	 * First pass over all the ports - allocate VIs and initialize some
1372 	 * basic parameters like mac address, port type, etc.
1373 	 */
1374 	for_each_port(sc, i) {
1375 		struct port_info *pi;
1376 
1377 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1378 		sc->port[i] = pi;
1379 
1380 		/* These must be set before t4_port_init */
1381 		pi->adapter = sc;
1382 		pi->port_id = i;
1383 		/*
1384 		 * XXX: vi[0] is special so we can't delay this allocation until
1385 		 * pi->nvi's final value is known.
1386 		 */
1387 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1388 		    M_ZERO | M_WAITOK);
1389 
1390 		/*
1391 		 * Allocate the "main" VI and initialize parameters
1392 		 * like mac addr.
1393 		 */
1394 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1395 		if (rc != 0) {
1396 			device_printf(dev, "unable to initialize port %d: %d\n",
1397 			    i, rc);
1398 			free(pi->vi, M_CXGBE);
1399 			free(pi, M_CXGBE);
1400 			sc->port[i] = NULL;
1401 			goto done;
1402 		}
1403 
1404 		if (is_bt(pi->port_type))
1405 			setbit(&sc->bt_map, pi->tx_chan);
1406 		else
1407 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1408 
1409 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1410 		    device_get_nameunit(dev), i);
1411 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1412 		sc->chan_map[pi->tx_chan] = i;
1413 
1414 		/*
1415 		 * The MPS counter for FCS errors doesn't work correctly on the
1416 		 * T6 so we use the MAC counter here.  Which MAC is in use
1417 		 * depends on the link settings which will be known when the
1418 		 * link comes up.
1419 		 */
1420 		if (is_t6(sc))
1421 			pi->fcs_reg = -1;
1422 		else {
1423 			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1424 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1425 		}
1426 		pi->fcs_base = 0;
1427 
1428 		/* All VIs on this port share this media. */
1429 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1430 		    cxgbe_media_status);
1431 
1432 		PORT_LOCK(pi);
1433 		init_link_config(pi);
1434 		fixup_link_config(pi);
1435 		build_medialist(pi);
1436 		if (fixed_ifmedia(pi))
1437 			pi->flags |= FIXED_IFMEDIA;
1438 		PORT_UNLOCK(pi);
1439 
1440 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1441 		    t4_ifnet_unit(sc, pi));
1442 		if (pi->dev == NULL) {
1443 			device_printf(dev,
1444 			    "failed to add device for port %d.\n", i);
1445 			rc = ENXIO;
1446 			goto done;
1447 		}
1448 		pi->vi[0].dev = pi->dev;
1449 		device_set_softc(pi->dev, pi);
1450 	}
1451 
1452 	/*
1453 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1454 	 */
1455 	nports = sc->params.nports;
1456 	rc = cfg_itype_and_nqueues(sc, &iaq);
1457 	if (rc != 0)
1458 		goto done; /* error message displayed already */
1459 
1460 	num_vis = iaq.num_vis;
1461 	sc->intr_type = iaq.intr_type;
1462 	sc->intr_count = iaq.nirq;
1463 
1464 	s = &sc->sge;
1465 	s->nrxq = nports * iaq.nrxq;
1466 	s->ntxq = nports * iaq.ntxq;
1467 	if (num_vis > 1) {
1468 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1469 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1470 	}
1471 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1472 	s->neq += nports;		/* ctrl queues: 1 per port */
1473 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1474 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1475 	if (is_offload(sc) || is_ethoffload(sc)) {
1476 		s->nofldtxq = nports * iaq.nofldtxq;
1477 		if (num_vis > 1)
1478 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1479 		s->neq += s->nofldtxq;
1480 
1481 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1482 		    M_CXGBE, M_ZERO | M_WAITOK);
1483 	}
1484 #endif
1485 #ifdef TCP_OFFLOAD
1486 	if (is_offload(sc)) {
1487 		s->nofldrxq = nports * iaq.nofldrxq;
1488 		if (num_vis > 1)
1489 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1490 		s->neq += s->nofldrxq;	/* free list */
1491 		s->niq += s->nofldrxq;
1492 
1493 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1494 		    M_CXGBE, M_ZERO | M_WAITOK);
1495 	}
1496 #endif
1497 #ifdef DEV_NETMAP
1498 	s->nnmrxq = 0;
1499 	s->nnmtxq = 0;
1500 	if (t4_native_netmap & NN_MAIN_VI) {
1501 		s->nnmrxq += nports * iaq.nnmrxq;
1502 		s->nnmtxq += nports * iaq.nnmtxq;
1503 	}
1504 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1505 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1506 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1507 	}
1508 	s->neq += s->nnmtxq + s->nnmrxq;
1509 	s->niq += s->nnmrxq;
1510 
1511 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1512 	    M_CXGBE, M_ZERO | M_WAITOK);
1513 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1514 	    M_CXGBE, M_ZERO | M_WAITOK);
1515 #endif
1516 	MPASS(s->niq <= s->iqmap_sz);
1517 	MPASS(s->neq <= s->eqmap_sz);
1518 
1519 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1520 	    M_ZERO | M_WAITOK);
1521 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1522 	    M_ZERO | M_WAITOK);
1523 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1524 	    M_ZERO | M_WAITOK);
1525 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1526 	    M_ZERO | M_WAITOK);
1527 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1528 	    M_ZERO | M_WAITOK);
1529 
1530 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1531 	    M_ZERO | M_WAITOK);
1532 
1533 	t4_init_l2t(sc, M_WAITOK);
1534 	t4_init_smt(sc, M_WAITOK);
1535 	t4_init_tx_sched(sc);
1536 	t4_init_atid_table(sc);
1537 #ifdef RATELIMIT
1538 	t4_init_etid_table(sc);
1539 #endif
1540 #ifdef INET6
1541 	t4_init_clip_table(sc);
1542 #endif
1543 	if (sc->vres.key.size != 0)
1544 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1545 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1546 
1547 	/*
1548 	 * Second pass over the ports.  This time we know the number of rx and
1549 	 * tx queues that each port should get.
1550 	 */
1551 	rqidx = tqidx = 0;
1552 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1553 	ofld_tqidx = 0;
1554 #endif
1555 #ifdef TCP_OFFLOAD
1556 	ofld_rqidx = 0;
1557 #endif
1558 #ifdef DEV_NETMAP
1559 	nm_rqidx = nm_tqidx = 0;
1560 #endif
1561 	for_each_port(sc, i) {
1562 		struct port_info *pi = sc->port[i];
1563 		struct vi_info *vi;
1564 
1565 		if (pi == NULL)
1566 			continue;
1567 
1568 		pi->nvi = num_vis;
1569 		for_each_vi(pi, j, vi) {
1570 			vi->pi = pi;
1571 			vi->adapter = sc;
1572 			vi->first_intr = -1;
1573 			vi->qsize_rxq = t4_qsize_rxq;
1574 			vi->qsize_txq = t4_qsize_txq;
1575 
1576 			vi->first_rxq = rqidx;
1577 			vi->first_txq = tqidx;
1578 			vi->tmr_idx = t4_tmr_idx;
1579 			vi->pktc_idx = t4_pktc_idx;
1580 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1581 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1582 
1583 			rqidx += vi->nrxq;
1584 			tqidx += vi->ntxq;
1585 
1586 			if (j == 0 && vi->ntxq > 1)
1587 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1588 			else
1589 				vi->rsrv_noflowq = 0;
1590 
1591 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1592 			vi->first_ofld_txq = ofld_tqidx;
1593 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1594 			ofld_tqidx += vi->nofldtxq;
1595 #endif
1596 #ifdef TCP_OFFLOAD
1597 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1598 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1599 			vi->first_ofld_rxq = ofld_rqidx;
1600 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1601 
1602 			ofld_rqidx += vi->nofldrxq;
1603 #endif
1604 #ifdef DEV_NETMAP
1605 			vi->first_nm_rxq = nm_rqidx;
1606 			vi->first_nm_txq = nm_tqidx;
1607 			if (j == 0) {
1608 				vi->nnmrxq = iaq.nnmrxq;
1609 				vi->nnmtxq = iaq.nnmtxq;
1610 			} else {
1611 				vi->nnmrxq = iaq.nnmrxq_vi;
1612 				vi->nnmtxq = iaq.nnmtxq_vi;
1613 			}
1614 			nm_rqidx += vi->nnmrxq;
1615 			nm_tqidx += vi->nnmtxq;
1616 #endif
1617 		}
1618 	}
1619 
1620 	rc = t4_setup_intr_handlers(sc);
1621 	if (rc != 0) {
1622 		device_printf(dev,
1623 		    "failed to setup interrupt handlers: %d\n", rc);
1624 		goto done;
1625 	}
1626 
1627 	rc = bus_generic_probe(dev);
1628 	if (rc != 0) {
1629 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1630 		goto done;
1631 	}
1632 
1633 	/*
1634 	 * Ensure thread-safe mailbox access (in debug builds).
1635 	 *
1636 	 * So far this was the only thread accessing the mailbox but various
1637 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1638 	 * will access the mailbox from different threads.
1639 	 */
1640 	sc->flags |= CHK_MBOX_ACCESS;
1641 
1642 	rc = bus_generic_attach(dev);
1643 	if (rc != 0) {
1644 		device_printf(dev,
1645 		    "failed to attach all child ports: %d\n", rc);
1646 		goto done;
1647 	}
1648 	t4_calibration_start(sc);
1649 
1650 	device_printf(dev,
1651 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1652 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1653 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1654 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1655 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1656 
1657 	t4_set_desc(sc);
1658 
1659 	notify_siblings(dev, 0);
1660 
1661 done:
1662 	if (rc != 0 && sc->cdev) {
1663 		/* cdev was created and so cxgbetool works; recover that way. */
1664 		device_printf(dev,
1665 		    "error during attach, adapter is now in recovery mode.\n");
1666 		rc = 0;
1667 	}
1668 
1669 	if (rc != 0)
1670 		t4_detach_common(dev);
1671 	else
1672 		t4_sysctls(sc);
1673 
1674 	return (rc);
1675 }
1676 
1677 static int
1678 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1679 {
1680 	struct adapter *sc;
1681 	struct port_info *pi;
1682 	int i;
1683 
1684 	sc = device_get_softc(bus);
1685 	for_each_port(sc, i) {
1686 		pi = sc->port[i];
1687 		if (pi != NULL && pi->dev == dev) {
1688 			sbuf_printf(sb, "port=%d", pi->port_id);
1689 			break;
1690 		}
1691 	}
1692 	return (0);
1693 }
1694 
1695 static int
1696 t4_ready(device_t dev)
1697 {
1698 	struct adapter *sc;
1699 
1700 	sc = device_get_softc(dev);
1701 	if (sc->flags & FW_OK)
1702 		return (0);
1703 	return (ENXIO);
1704 }
1705 
1706 static int
1707 t4_read_port_device(device_t dev, int port, device_t *child)
1708 {
1709 	struct adapter *sc;
1710 	struct port_info *pi;
1711 
1712 	sc = device_get_softc(dev);
1713 	if (port < 0 || port >= MAX_NPORTS)
1714 		return (EINVAL);
1715 	pi = sc->port[port];
1716 	if (pi == NULL || pi->dev == NULL)
1717 		return (ENXIO);
1718 	*child = pi->dev;
1719 	return (0);
1720 }
1721 
1722 static int
1723 notify_siblings(device_t dev, int detaching)
1724 {
1725 	device_t sibling;
1726 	int error, i;
1727 
1728 	error = 0;
1729 	for (i = 0; i < PCI_FUNCMAX; i++) {
1730 		if (i == pci_get_function(dev))
1731 			continue;
1732 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1733 		    pci_get_slot(dev), i);
1734 		if (sibling == NULL || !device_is_attached(sibling))
1735 			continue;
1736 		if (detaching)
1737 			error = T4_DETACH_CHILD(sibling);
1738 		else
1739 			(void)T4_ATTACH_CHILD(sibling);
1740 		if (error)
1741 			break;
1742 	}
1743 	return (error);
1744 }
1745 
1746 /*
1747  * Idempotent
1748  */
1749 static int
1750 t4_detach(device_t dev)
1751 {
1752 	int rc;
1753 
1754 	rc = notify_siblings(dev, 1);
1755 	if (rc) {
1756 		device_printf(dev,
1757 		    "failed to detach sibling devices: %d\n", rc);
1758 		return (rc);
1759 	}
1760 
1761 	return (t4_detach_common(dev));
1762 }
1763 
1764 int
1765 t4_detach_common(device_t dev)
1766 {
1767 	struct adapter *sc;
1768 	struct port_info *pi;
1769 	int i, rc;
1770 
1771 	sc = device_get_softc(dev);
1772 
1773 #ifdef TCP_OFFLOAD
1774 	rc = deactivate_all_uld(sc);
1775 	if (rc) {
1776 		device_printf(dev,
1777 		    "failed to detach upper layer drivers: %d\n", rc);
1778 		return (rc);
1779 	}
1780 #endif
1781 
1782 	if (sc->cdev) {
1783 		destroy_dev(sc->cdev);
1784 		sc->cdev = NULL;
1785 	}
1786 
1787 	sx_xlock(&t4_list_lock);
1788 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1789 	sx_xunlock(&t4_list_lock);
1790 
1791 	sc->flags &= ~CHK_MBOX_ACCESS;
1792 	if (sc->flags & FULL_INIT_DONE) {
1793 		if (!(sc->flags & IS_VF))
1794 			t4_intr_disable(sc);
1795 	}
1796 
1797 	if (device_is_attached(dev)) {
1798 		rc = bus_generic_detach(dev);
1799 		if (rc) {
1800 			device_printf(dev,
1801 			    "failed to detach child devices: %d\n", rc);
1802 			return (rc);
1803 		}
1804 	}
1805 
1806 	for (i = 0; i < sc->intr_count; i++)
1807 		t4_free_irq(sc, &sc->irq[i]);
1808 
1809 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1810 		t4_free_tx_sched(sc);
1811 
1812 	for (i = 0; i < MAX_NPORTS; i++) {
1813 		pi = sc->port[i];
1814 		if (pi) {
1815 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1816 			if (pi->dev)
1817 				device_delete_child(dev, pi->dev);
1818 
1819 			mtx_destroy(&pi->pi_lock);
1820 			free(pi->vi, M_CXGBE);
1821 			free(pi, M_CXGBE);
1822 		}
1823 	}
1824 	callout_stop(&sc->cal_callout);
1825 	callout_drain(&sc->cal_callout);
1826 	device_delete_children(dev);
1827 	sysctl_ctx_free(&sc->ctx);
1828 	adapter_full_uninit(sc);
1829 
1830 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1831 		t4_fw_bye(sc, sc->mbox);
1832 
1833 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1834 		pci_release_msi(dev);
1835 
1836 	if (sc->regs_res)
1837 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1838 		    sc->regs_res);
1839 
1840 	if (sc->udbs_res)
1841 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1842 		    sc->udbs_res);
1843 
1844 	if (sc->msix_res)
1845 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1846 		    sc->msix_res);
1847 
1848 	if (sc->l2t)
1849 		t4_free_l2t(sc);
1850 	if (sc->smt)
1851 		t4_free_smt(sc->smt);
1852 	t4_free_atid_table(sc);
1853 #ifdef RATELIMIT
1854 	t4_free_etid_table(sc);
1855 #endif
1856 	if (sc->key_map)
1857 		vmem_destroy(sc->key_map);
1858 #ifdef INET6
1859 	t4_destroy_clip_table(sc);
1860 #endif
1861 
1862 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1863 	free(sc->sge.ofld_txq, M_CXGBE);
1864 #endif
1865 #ifdef TCP_OFFLOAD
1866 	free(sc->sge.ofld_rxq, M_CXGBE);
1867 #endif
1868 #ifdef DEV_NETMAP
1869 	free(sc->sge.nm_rxq, M_CXGBE);
1870 	free(sc->sge.nm_txq, M_CXGBE);
1871 #endif
1872 	free(sc->irq, M_CXGBE);
1873 	free(sc->sge.rxq, M_CXGBE);
1874 	free(sc->sge.txq, M_CXGBE);
1875 	free(sc->sge.ctrlq, M_CXGBE);
1876 	free(sc->sge.iqmap, M_CXGBE);
1877 	free(sc->sge.eqmap, M_CXGBE);
1878 	free(sc->tids.ftid_tab, M_CXGBE);
1879 	free(sc->tids.hpftid_tab, M_CXGBE);
1880 	free_hftid_hash(&sc->tids);
1881 	free(sc->tids.tid_tab, M_CXGBE);
1882 	t4_destroy_dma_tag(sc);
1883 
1884 	callout_drain(&sc->ktls_tick);
1885 	callout_drain(&sc->sfl_callout);
1886 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1887 		mtx_destroy(&sc->tids.ftid_lock);
1888 		cv_destroy(&sc->tids.ftid_cv);
1889 	}
1890 	if (mtx_initialized(&sc->tids.atid_lock))
1891 		mtx_destroy(&sc->tids.atid_lock);
1892 	if (mtx_initialized(&sc->ifp_lock))
1893 		mtx_destroy(&sc->ifp_lock);
1894 
1895 	if (rw_initialized(&sc->policy_lock)) {
1896 		rw_destroy(&sc->policy_lock);
1897 #ifdef TCP_OFFLOAD
1898 		if (sc->policy != NULL)
1899 			free_offload_policy(sc->policy);
1900 #endif
1901 	}
1902 
1903 	for (i = 0; i < NUM_MEMWIN; i++) {
1904 		struct memwin *mw = &sc->memwin[i];
1905 
1906 		if (rw_initialized(&mw->mw_lock))
1907 			rw_destroy(&mw->mw_lock);
1908 	}
1909 
1910 	mtx_destroy(&sc->sfl_lock);
1911 	mtx_destroy(&sc->reg_lock);
1912 	mtx_destroy(&sc->sc_lock);
1913 
1914 	bzero(sc, sizeof(*sc));
1915 
1916 	return (0);
1917 }
1918 
1919 static inline int
1920 stop_adapter(struct adapter *sc)
1921 {
1922 	struct port_info *pi;
1923 	int i;
1924 
1925 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1926 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1927 			 __func__, curthread, sc->flags, sc->error_flags);
1928 		return (EALREADY);
1929 	}
1930 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1931 		 sc->flags, sc->error_flags);
1932 	t4_shutdown_adapter(sc);
1933 	for_each_port(sc, i) {
1934 		pi = sc->port[i];
1935 		PORT_LOCK(pi);
1936 		if (pi->up_vis > 0 && pi->link_cfg.link_ok) {
1937 			/*
1938 			 * t4_shutdown_adapter has already shut down all the
1939 			 * PHYs but it also disables interrupts and DMA so there
1940 			 * won't be a link interrupt.  Update the state manually
1941 			 * if the link was up previously and inform the kernel.
1942 			 */
1943 			pi->link_cfg.link_ok = false;
1944 			t4_os_link_changed(pi);
1945 		}
1946 		PORT_UNLOCK(pi);
1947 	}
1948 
1949 	return (0);
1950 }
1951 
1952 static inline int
1953 restart_adapter(struct adapter *sc)
1954 {
1955 	uint32_t val;
1956 
1957 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1958 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1959 			 __func__, curthread, sc->flags, sc->error_flags);
1960 		return (EALREADY);
1961 	}
1962 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1963 		 sc->flags, sc->error_flags);
1964 
1965 	MPASS(hw_off_limits(sc));
1966 	MPASS((sc->flags & FW_OK) == 0);
1967 	MPASS((sc->flags & MASTER_PF) == 0);
1968 	MPASS(sc->reset_thread == NULL);
1969 
1970 	/*
1971 	 * The adapter is supposed to be back on PCIE with its config space and
1972 	 * BARs restored to their state before reset.  Register access via
1973 	 * t4_read_reg BAR0 should just work.
1974 	 */
1975 	sc->reset_thread = curthread;
1976 	val = t4_read_reg(sc, A_PL_WHOAMI);
1977 	if (val == 0xffffffff || val == 0xeeeeeeee) {
1978 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
1979 		sc->reset_thread = NULL;
1980 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
1981 		return (ENXIO);
1982 	}
1983 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
1984 	atomic_add_int(&sc->incarnation, 1);
1985 	atomic_add_int(&sc->num_resets, 1);
1986 
1987 	return (0);
1988 }
1989 
1990 static inline void
1991 set_adapter_hwstatus(struct adapter *sc, const bool usable)
1992 {
1993 	mtx_lock(&sc->reg_lock);
1994 	if (usable) {
1995 		/* Must be marked reusable by the designated thread. */
1996 		MPASS(sc->reset_thread == curthread);
1997 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
1998 	} else {
1999 		/* Mark the adapter totally off limits. */
2000 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2001 		sc->flags &= ~(FW_OK | MASTER_PF);
2002 		sc->reset_thread = NULL;
2003 	}
2004 	mtx_unlock(&sc->reg_lock);
2005 }
2006 
2007 static int
2008 stop_lld(struct adapter *sc)
2009 {
2010 	struct port_info *pi;
2011 	struct vi_info *vi;
2012 	if_t ifp;
2013 	struct sge_rxq *rxq;
2014 	struct sge_txq *txq;
2015 	struct sge_wrq *wrq;
2016 #ifdef TCP_OFFLOAD
2017 	struct sge_ofld_rxq *ofld_rxq;
2018 #endif
2019 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2020 	struct sge_ofld_txq *ofld_txq;
2021 #endif
2022 	int rc, i, j, k;
2023 
2024 	/*
2025 	 * XXX: Can there be a synch_op in progress that will hang because
2026 	 * hardware has been stopped?  We'll hang too and the solution will be
2027 	 * to use a version of begin_synch_op that wakes up existing synch_op
2028 	 * with errors.  Maybe stop_adapter should do this wakeup?
2029 	 *
2030 	 * I don't think any synch_op could get stranded waiting for DMA or
2031 	 * interrupt so I think we're okay here.  Remove this comment block
2032 	 * after testing.
2033 	 */
2034 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2035 	if (rc != 0)
2036 		return (ENXIO);
2037 
2038 	/* Quiesce all activity. */
2039 	for_each_port(sc, i) {
2040 		pi = sc->port[i];
2041 		pi->vxlan_tcam_entry = false;
2042 		for_each_vi(pi, j, vi) {
2043 			vi->xact_addr_filt = -1;
2044 			mtx_lock(&vi->tick_mtx);
2045 			vi->flags |= VI_SKIP_STATS;
2046 			mtx_unlock(&vi->tick_mtx);
2047 			if (!(vi->flags & VI_INIT_DONE))
2048 				continue;
2049 
2050 			ifp = vi->ifp;
2051 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2052 				mtx_lock(&vi->tick_mtx);
2053 				callout_stop(&vi->tick);
2054 				mtx_unlock(&vi->tick_mtx);
2055 				callout_drain(&vi->tick);
2056 			}
2057 
2058 			/*
2059 			 * Note that the HW is not available.
2060 			 */
2061 			for_each_txq(vi, k, txq) {
2062 				TXQ_LOCK(txq);
2063 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2064 				TXQ_UNLOCK(txq);
2065 			}
2066 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2067 			for_each_ofld_txq(vi, k, ofld_txq) {
2068 				TXQ_LOCK(&ofld_txq->wrq);
2069 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2070 				TXQ_UNLOCK(&ofld_txq->wrq);
2071 			}
2072 #endif
2073 			for_each_rxq(vi, k, rxq) {
2074 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2075 			}
2076 #if defined(TCP_OFFLOAD)
2077 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2078 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2079 			}
2080 #endif
2081 
2082 			quiesce_vi(vi);
2083 		}
2084 
2085 		if (sc->flags & FULL_INIT_DONE) {
2086 			/* Control queue */
2087 			wrq = &sc->sge.ctrlq[i];
2088 			TXQ_LOCK(wrq);
2089 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2090 			TXQ_UNLOCK(wrq);
2091 			quiesce_wrq(wrq);
2092 		}
2093 
2094 		if (pi->flags & HAS_TRACEQ) {
2095 			pi->flags &= ~HAS_TRACEQ;
2096 			sc->traceq = -1;
2097 			sc->tracer_valid = 0;
2098 			sc->tracer_enabled = 0;
2099 		}
2100 	}
2101 	if (sc->flags & FULL_INIT_DONE) {
2102 		/* Firmware event queue */
2103 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2104 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2105 	}
2106 
2107 	/* Stop calibration */
2108 	callout_stop(&sc->cal_callout);
2109 	callout_drain(&sc->cal_callout);
2110 
2111 	if (t4_clock_gate_on_suspend) {
2112 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2113 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2114 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2115 	}
2116 
2117 	end_synchronized_op(sc, 0);
2118 
2119 	stop_atid_allocator(sc);
2120 	t4_stop_l2t(sc);
2121 
2122 	return (rc);
2123 }
2124 
2125 int
2126 suspend_adapter(struct adapter *sc)
2127 {
2128 	stop_adapter(sc);
2129 	stop_lld(sc);
2130 #ifdef TCP_OFFLOAD
2131 	stop_all_uld(sc);
2132 #endif
2133 	set_adapter_hwstatus(sc, false);
2134 
2135 	return (0);
2136 }
2137 
2138 static int
2139 t4_suspend(device_t dev)
2140 {
2141 	struct adapter *sc = device_get_softc(dev);
2142 	int rc;
2143 
2144 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2145 	rc = suspend_adapter(sc);
2146 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2147 
2148 	return (rc);
2149 }
2150 
2151 struct adapter_pre_reset_state {
2152 	u_int flags;
2153 	uint16_t nbmcaps;
2154 	uint16_t linkcaps;
2155 	uint16_t switchcaps;
2156 	uint16_t niccaps;
2157 	uint16_t toecaps;
2158 	uint16_t rdmacaps;
2159 	uint16_t cryptocaps;
2160 	uint16_t iscsicaps;
2161 	uint16_t fcoecaps;
2162 
2163 	u_int cfcsum;
2164 	char cfg_file[32];
2165 
2166 	struct adapter_params params;
2167 	struct t4_virt_res vres;
2168 	struct tid_info tids;
2169 	struct sge sge;
2170 
2171 	int rawf_base;
2172 	int nrawf;
2173 
2174 };
2175 
2176 static void
2177 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2178 {
2179 
2180 	ASSERT_SYNCHRONIZED_OP(sc);
2181 
2182 	o->flags = sc->flags;
2183 
2184 	o->nbmcaps =  sc->nbmcaps;
2185 	o->linkcaps = sc->linkcaps;
2186 	o->switchcaps = sc->switchcaps;
2187 	o->niccaps = sc->niccaps;
2188 	o->toecaps = sc->toecaps;
2189 	o->rdmacaps = sc->rdmacaps;
2190 	o->cryptocaps = sc->cryptocaps;
2191 	o->iscsicaps = sc->iscsicaps;
2192 	o->fcoecaps = sc->fcoecaps;
2193 
2194 	o->cfcsum = sc->cfcsum;
2195 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2196 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2197 
2198 	o->params = sc->params;
2199 	o->vres = sc->vres;
2200 	o->tids = sc->tids;
2201 	o->sge = sc->sge;
2202 
2203 	o->rawf_base = sc->rawf_base;
2204 	o->nrawf = sc->nrawf;
2205 }
2206 
2207 static int
2208 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2209 {
2210 	int rc = 0;
2211 
2212 	ASSERT_SYNCHRONIZED_OP(sc);
2213 
2214 	/* Capabilities */
2215 #define COMPARE_CAPS(c) do { \
2216 	if (o->c##caps != sc->c##caps) { \
2217 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2218 		    sc->c##caps); \
2219 		rc = EINVAL; \
2220 	} \
2221 } while (0)
2222 	COMPARE_CAPS(nbm);
2223 	COMPARE_CAPS(link);
2224 	COMPARE_CAPS(switch);
2225 	COMPARE_CAPS(nic);
2226 	COMPARE_CAPS(toe);
2227 	COMPARE_CAPS(rdma);
2228 	COMPARE_CAPS(crypto);
2229 	COMPARE_CAPS(iscsi);
2230 	COMPARE_CAPS(fcoe);
2231 #undef COMPARE_CAPS
2232 
2233 	/* Firmware config file */
2234 	if (o->cfcsum != sc->cfcsum) {
2235 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2236 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2237 		rc = EINVAL;
2238 	}
2239 
2240 #define COMPARE_PARAM(p, name) do { \
2241 	if (o->p != sc->p) { \
2242 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2243 		rc = EINVAL; \
2244 	} \
2245 } while (0)
2246 	COMPARE_PARAM(sge.iq_start, iq_start);
2247 	COMPARE_PARAM(sge.eq_start, eq_start);
2248 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2249 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2250 	COMPARE_PARAM(tids.nftids, nftids);
2251 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2252 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2253 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2254 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2255 	COMPARE_PARAM(tids.tid_base, tid_base);
2256 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2257 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2258 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2259 	COMPARE_PARAM(rawf_base, rawf_base);
2260 	COMPARE_PARAM(nrawf, nrawf);
2261 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2262 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2263 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2264 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2265 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2266 	COMPARE_PARAM(tids.ntids, ntids);
2267 	COMPARE_PARAM(tids.etid_base, etid_base);
2268 	COMPARE_PARAM(tids.etid_end, etid_end);
2269 	COMPARE_PARAM(tids.netids, netids);
2270 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2271 	COMPARE_PARAM(params.ethoffload, ethoffload);
2272 	COMPARE_PARAM(tids.natids, natids);
2273 	COMPARE_PARAM(tids.stid_base, stid_base);
2274 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2275 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2276 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2277 	COMPARE_PARAM(vres.stag.start, stag_start);
2278 	COMPARE_PARAM(vres.stag.size, stag_size);
2279 	COMPARE_PARAM(vres.rq.start, rq_start);
2280 	COMPARE_PARAM(vres.rq.size, rq_size);
2281 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2282 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2283 	COMPARE_PARAM(vres.qp.start, qp_start);
2284 	COMPARE_PARAM(vres.qp.size, qp_size);
2285 	COMPARE_PARAM(vres.cq.start, cq_start);
2286 	COMPARE_PARAM(vres.cq.size, cq_size);
2287 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2288 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2289 	COMPARE_PARAM(vres.srq.start, srq_start);
2290 	COMPARE_PARAM(vres.srq.size, srq_size);
2291 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2292 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2293 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2294 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2295 	COMPARE_PARAM(vres.key.start, key_start);
2296 	COMPARE_PARAM(vres.key.size, key_size);
2297 #undef COMPARE_PARAM
2298 
2299 	return (rc);
2300 }
2301 
2302 static int
2303 restart_lld(struct adapter *sc)
2304 {
2305 	struct adapter_pre_reset_state *old_state = NULL;
2306 	struct port_info *pi;
2307 	struct vi_info *vi;
2308 	if_t ifp;
2309 	struct sge_txq *txq;
2310 	int rc, i, j, k;
2311 
2312 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2313 	if (rc != 0)
2314 		return (ENXIO);
2315 
2316 	/* Restore memory window. */
2317 	setup_memwin(sc);
2318 
2319 	/* Go no further if recovery mode has been requested. */
2320 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2321 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2322 		rc = 0;
2323 		set_adapter_hwstatus(sc, true);
2324 		goto done;
2325 	}
2326 
2327 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2328 	save_caps_and_params(sc, old_state);
2329 
2330 	/* Reestablish contact with firmware and become the primary PF. */
2331 	rc = contact_firmware(sc);
2332 	if (rc != 0)
2333 		goto done; /* error message displayed already */
2334 	MPASS(sc->flags & FW_OK);
2335 
2336 	if (sc->flags & MASTER_PF) {
2337 		rc = partition_resources(sc);
2338 		if (rc != 0)
2339 			goto done; /* error message displayed already */
2340 	}
2341 
2342 	rc = get_params__post_init(sc);
2343 	if (rc != 0)
2344 		goto done; /* error message displayed already */
2345 
2346 	rc = set_params__post_init(sc);
2347 	if (rc != 0)
2348 		goto done; /* error message displayed already */
2349 
2350 	rc = compare_caps_and_params(sc, old_state);
2351 	if (rc != 0)
2352 		goto done; /* error message displayed already */
2353 
2354 	for_each_port(sc, i) {
2355 		pi = sc->port[i];
2356 		MPASS(pi != NULL);
2357 		MPASS(pi->vi != NULL);
2358 		MPASS(pi->vi[0].dev == pi->dev);
2359 
2360 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2361 		if (rc != 0) {
2362 			CH_ERR(sc,
2363 			    "failed to re-initialize port %d: %d\n", i, rc);
2364 			goto done;
2365 		}
2366 		MPASS(sc->chan_map[pi->tx_chan] == i);
2367 
2368 		PORT_LOCK(pi);
2369 		fixup_link_config(pi);
2370 		build_medialist(pi);
2371 		PORT_UNLOCK(pi);
2372 		for_each_vi(pi, j, vi) {
2373 			if (IS_MAIN_VI(vi))
2374 				continue;
2375 			rc = alloc_extra_vi(sc, pi, vi);
2376 			if (rc != 0) {
2377 				CH_ERR(vi,
2378 				    "failed to re-allocate extra VI: %d\n", rc);
2379 				goto done;
2380 			}
2381 		}
2382 	}
2383 
2384 	/*
2385 	 * Interrupts and queues are about to be enabled and other threads will
2386 	 * want to access the hardware too.  It is safe to do so.  Note that
2387 	 * this thread is still in the middle of a synchronized_op.
2388 	 */
2389 	set_adapter_hwstatus(sc, true);
2390 
2391 	if (sc->flags & FULL_INIT_DONE) {
2392 		rc = adapter_full_init(sc);
2393 		if (rc != 0) {
2394 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2395 			goto done;
2396 		}
2397 
2398 		if (sc->vxlan_refcount > 0)
2399 			enable_vxlan_rx(sc);
2400 
2401 		for_each_port(sc, i) {
2402 			pi = sc->port[i];
2403 			for_each_vi(pi, j, vi) {
2404 				mtx_lock(&vi->tick_mtx);
2405 				vi->flags &= ~VI_SKIP_STATS;
2406 				mtx_unlock(&vi->tick_mtx);
2407 				if (!(vi->flags & VI_INIT_DONE))
2408 					continue;
2409 				rc = vi_full_init(vi);
2410 				if (rc != 0) {
2411 					CH_ERR(vi, "failed to re-initialize "
2412 					    "interface: %d\n", rc);
2413 					goto done;
2414 				}
2415 				if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
2416 					sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
2417 					t4_write_reg(sc, is_t4(sc) ?
2418 					    A_MPS_TRC_RSS_CONTROL :
2419 					    A_MPS_T5_TRC_RSS_CONTROL,
2420 					    V_RSSCONTROL(pi->tx_chan) |
2421 					    V_QUEUENUMBER(sc->traceq));
2422 					pi->flags |= HAS_TRACEQ;
2423 				}
2424 
2425 				ifp = vi->ifp;
2426 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2427 					continue;
2428 				/*
2429 				 * Note that we do not setup multicast addresses
2430 				 * in the first pass.  This ensures that the
2431 				 * unicast DMACs for all VIs on all ports get an
2432 				 * MPS TCAM entry.
2433 				 */
2434 				rc = update_mac_settings(ifp, XGMAC_ALL &
2435 				    ~XGMAC_MCADDRS);
2436 				if (rc != 0) {
2437 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2438 					goto done;
2439 				}
2440 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2441 				    true);
2442 				if (rc != 0) {
2443 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2444 					goto done;
2445 				}
2446 				for_each_txq(vi, k, txq) {
2447 					TXQ_LOCK(txq);
2448 					txq->eq.flags |= EQ_ENABLED;
2449 					TXQ_UNLOCK(txq);
2450 				}
2451 				mtx_lock(&vi->tick_mtx);
2452 				callout_schedule(&vi->tick, hz);
2453 				mtx_unlock(&vi->tick_mtx);
2454 			}
2455 			PORT_LOCK(pi);
2456 			if (pi->up_vis > 0) {
2457 				t4_update_port_info(pi);
2458 				fixup_link_config(pi);
2459 				build_medialist(pi);
2460 				apply_link_config(pi);
2461 				if (pi->link_cfg.link_ok)
2462 					t4_os_link_changed(pi);
2463 			}
2464 			PORT_UNLOCK(pi);
2465 		}
2466 
2467 		/* Now reprogram the L2 multicast addresses. */
2468 		for_each_port(sc, i) {
2469 			pi = sc->port[i];
2470 			for_each_vi(pi, j, vi) {
2471 				if (!(vi->flags & VI_INIT_DONE))
2472 					continue;
2473 				ifp = vi->ifp;
2474 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2475 					continue;
2476 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2477 				if (rc != 0) {
2478 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2479 					rc = 0;	/* carry on */
2480 				}
2481 			}
2482 		}
2483 	}
2484 
2485 	/* Reset all calibration */
2486 	t4_calibration_start(sc);
2487 done:
2488 	end_synchronized_op(sc, 0);
2489 	free(old_state, M_CXGBE);
2490 
2491 	restart_atid_allocator(sc);
2492 	t4_restart_l2t(sc);
2493 
2494 	return (rc);
2495 }
2496 
2497 int
2498 resume_adapter(struct adapter *sc)
2499 {
2500 	restart_adapter(sc);
2501 	restart_lld(sc);
2502 #ifdef TCP_OFFLOAD
2503 	restart_all_uld(sc);
2504 #endif
2505 	return (0);
2506 }
2507 
2508 static int
2509 t4_resume(device_t dev)
2510 {
2511 	struct adapter *sc = device_get_softc(dev);
2512 	int rc;
2513 
2514 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2515 	rc = resume_adapter(sc);
2516 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2517 
2518 	return (rc);
2519 }
2520 
2521 static int
2522 t4_reset_prepare(device_t dev, device_t child)
2523 {
2524 	struct adapter *sc = device_get_softc(dev);
2525 
2526 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2527 	return (0);
2528 }
2529 
2530 static int
2531 t4_reset_post(device_t dev, device_t child)
2532 {
2533 	struct adapter *sc = device_get_softc(dev);
2534 
2535 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2536 	return (0);
2537 }
2538 
2539 static int
2540 reset_adapter_with_pci_bus_reset(struct adapter *sc)
2541 {
2542 	int rc;
2543 
2544 	mtx_lock(&Giant);
2545 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2546 	mtx_unlock(&Giant);
2547 	return (rc);
2548 }
2549 
2550 static int
2551 reset_adapter_with_pl_rst(struct adapter *sc)
2552 {
2553 	suspend_adapter(sc);
2554 
2555 	/* This is a t4_write_reg without the hw_off_limits check. */
2556 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2557 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2558 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2559 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2560 
2561 	resume_adapter(sc);
2562 
2563 	return (0);
2564 }
2565 
2566 static inline int
2567 reset_adapter(struct adapter *sc)
2568 {
2569 	if (vm_guest == 0)
2570 		return (reset_adapter_with_pci_bus_reset(sc));
2571 	else
2572 		return (reset_adapter_with_pl_rst(sc));
2573 }
2574 
2575 static void
2576 reset_adapter_task(void *arg, int pending)
2577 {
2578 	struct adapter *sc = arg;
2579 	const int flags = sc->flags;
2580 	const int eflags = sc->error_flags;
2581 	int rc;
2582 
2583 	if (pending > 1)
2584 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2585 	rc = reset_adapter(sc);
2586 	if (rc != 0) {
2587 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2588 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2589 		       rc, flags, sc->flags, eflags, sc->error_flags);
2590 	}
2591 }
2592 
2593 static int
2594 cxgbe_probe(device_t dev)
2595 {
2596 	struct port_info *pi = device_get_softc(dev);
2597 
2598 	device_set_descf(dev, "port %d", pi->port_id);
2599 
2600 	return (BUS_PROBE_DEFAULT);
2601 }
2602 
2603 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2604     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2605     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2606     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2607 #define T4_CAP_ENABLE (T4_CAP)
2608 
2609 static void
2610 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2611 {
2612 	if_t ifp;
2613 	struct sbuf *sb;
2614 	struct sysctl_ctx_list *ctx = &vi->ctx;
2615 	struct sysctl_oid_list *children;
2616 	struct pfil_head_args pa;
2617 	struct adapter *sc = vi->adapter;
2618 
2619 	sysctl_ctx_init(ctx);
2620 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2621 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2622 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2623 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2624 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2625 #ifdef DEV_NETMAP
2626 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2627 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2628 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2629 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2630 #endif
2631 #ifdef TCP_OFFLOAD
2632 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2633 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2634 #endif
2635 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2636 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2637 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2638 #endif
2639 
2640 	vi->xact_addr_filt = -1;
2641 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2642 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2643 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2644 		vi->flags |= TX_USES_VM_WR;
2645 
2646 	/* Allocate an ifnet and set it up */
2647 	ifp = if_alloc_dev(IFT_ETHER, dev);
2648 	vi->ifp = ifp;
2649 	if_setsoftc(ifp, vi);
2650 
2651 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2652 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2653 
2654 	if_setinitfn(ifp, cxgbe_init);
2655 	if_setioctlfn(ifp, cxgbe_ioctl);
2656 	if_settransmitfn(ifp, cxgbe_transmit);
2657 	if_setqflushfn(ifp, cxgbe_qflush);
2658 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2659 		if_setgetcounterfn(ifp, vi_get_counter);
2660 	else
2661 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2662 #if defined(KERN_TLS) || defined(RATELIMIT)
2663 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2664 #endif
2665 #ifdef RATELIMIT
2666 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2667 #endif
2668 
2669 	if_setcapabilities(ifp, T4_CAP);
2670 	if_setcapenable(ifp, T4_CAP_ENABLE);
2671 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2672 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2673 	if (chip_id(sc) >= CHELSIO_T6) {
2674 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2675 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2676 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2677 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2678 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2679 	}
2680 
2681 #ifdef TCP_OFFLOAD
2682 	if (vi->nofldrxq != 0)
2683 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2684 #endif
2685 #ifdef RATELIMIT
2686 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2687 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2688 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2689 	}
2690 #endif
2691 
2692 	if_sethwtsomax(ifp, IP_MAXPACKET);
2693 	if (vi->flags & TX_USES_VM_WR)
2694 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2695 	else
2696 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2697 #ifdef RATELIMIT
2698 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2699 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2700 #endif
2701 	if_sethwtsomaxsegsize(ifp, 65536);
2702 #ifdef KERN_TLS
2703 	if (is_ktls(sc)) {
2704 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2705 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2706 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2707 	}
2708 #endif
2709 
2710 	ether_ifattach(ifp, vi->hw_addr);
2711 #ifdef DEV_NETMAP
2712 	if (vi->nnmrxq != 0)
2713 		cxgbe_nm_attach(vi);
2714 #endif
2715 	sb = sbuf_new_auto();
2716 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2717 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2718 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2719 	case IFCAP_TOE:
2720 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2721 		break;
2722 	case IFCAP_TOE | IFCAP_TXRTLMT:
2723 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2724 		break;
2725 	case IFCAP_TXRTLMT:
2726 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2727 		break;
2728 	}
2729 #endif
2730 #ifdef TCP_OFFLOAD
2731 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2732 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2733 #endif
2734 #ifdef DEV_NETMAP
2735 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2736 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2737 		    vi->nnmtxq, vi->nnmrxq);
2738 #endif
2739 	sbuf_finish(sb);
2740 	device_printf(dev, "%s\n", sbuf_data(sb));
2741 	sbuf_delete(sb);
2742 
2743 	vi_sysctls(vi);
2744 
2745 	pa.pa_version = PFIL_VERSION;
2746 	pa.pa_flags = PFIL_IN;
2747 	pa.pa_type = PFIL_TYPE_ETHERNET;
2748 	pa.pa_headname = if_name(ifp);
2749 	vi->pfil = pfil_head_register(&pa);
2750 }
2751 
2752 static int
2753 cxgbe_attach(device_t dev)
2754 {
2755 	struct port_info *pi = device_get_softc(dev);
2756 	struct adapter *sc = pi->adapter;
2757 	struct vi_info *vi;
2758 	int i;
2759 
2760 	sysctl_ctx_init(&pi->ctx);
2761 
2762 	cxgbe_vi_attach(dev, &pi->vi[0]);
2763 
2764 	for_each_vi(pi, i, vi) {
2765 		if (i == 0)
2766 			continue;
2767 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2768 		if (vi->dev == NULL) {
2769 			device_printf(dev, "failed to add VI %d\n", i);
2770 			continue;
2771 		}
2772 		device_set_softc(vi->dev, vi);
2773 	}
2774 
2775 	cxgbe_sysctls(pi);
2776 
2777 	bus_generic_attach(dev);
2778 
2779 	return (0);
2780 }
2781 
2782 static void
2783 cxgbe_vi_detach(struct vi_info *vi)
2784 {
2785 	if_t ifp = vi->ifp;
2786 
2787 	if (vi->pfil != NULL) {
2788 		pfil_head_unregister(vi->pfil);
2789 		vi->pfil = NULL;
2790 	}
2791 
2792 	ether_ifdetach(ifp);
2793 
2794 	/* Let detach proceed even if these fail. */
2795 #ifdef DEV_NETMAP
2796 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2797 		cxgbe_nm_detach(vi);
2798 #endif
2799 	cxgbe_uninit_synchronized(vi);
2800 	callout_drain(&vi->tick);
2801 	mtx_destroy(&vi->tick_mtx);
2802 	sysctl_ctx_free(&vi->ctx);
2803 	vi_full_uninit(vi);
2804 
2805 	if_free(vi->ifp);
2806 	vi->ifp = NULL;
2807 }
2808 
2809 static int
2810 cxgbe_detach(device_t dev)
2811 {
2812 	struct port_info *pi = device_get_softc(dev);
2813 	struct adapter *sc = pi->adapter;
2814 	int rc;
2815 
2816 	/* Detach the extra VIs first. */
2817 	rc = bus_generic_detach(dev);
2818 	if (rc)
2819 		return (rc);
2820 	device_delete_children(dev);
2821 
2822 	sysctl_ctx_free(&pi->ctx);
2823 	begin_vi_detach(sc, &pi->vi[0]);
2824 	if (pi->flags & HAS_TRACEQ) {
2825 		sc->traceq = -1;	/* cloner should not create ifnet */
2826 		t4_tracer_port_detach(sc);
2827 	}
2828 	cxgbe_vi_detach(&pi->vi[0]);
2829 	ifmedia_removeall(&pi->media);
2830 	end_vi_detach(sc, &pi->vi[0]);
2831 
2832 	return (0);
2833 }
2834 
2835 static void
2836 cxgbe_init(void *arg)
2837 {
2838 	struct vi_info *vi = arg;
2839 	struct adapter *sc = vi->adapter;
2840 
2841 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2842 		return;
2843 	cxgbe_init_synchronized(vi);
2844 	end_synchronized_op(sc, 0);
2845 }
2846 
2847 static int
2848 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2849 {
2850 	int rc = 0, mtu, flags;
2851 	struct vi_info *vi = if_getsoftc(ifp);
2852 	struct port_info *pi = vi->pi;
2853 	struct adapter *sc = pi->adapter;
2854 	struct ifreq *ifr = (struct ifreq *)data;
2855 	uint32_t mask;
2856 
2857 	switch (cmd) {
2858 	case SIOCSIFMTU:
2859 		mtu = ifr->ifr_mtu;
2860 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2861 			return (EINVAL);
2862 
2863 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2864 		if (rc)
2865 			return (rc);
2866 		if_setmtu(ifp, mtu);
2867 		if (vi->flags & VI_INIT_DONE) {
2868 			t4_update_fl_bufsize(ifp);
2869 			if (!hw_off_limits(sc) &&
2870 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2871 				rc = update_mac_settings(ifp, XGMAC_MTU);
2872 		}
2873 		end_synchronized_op(sc, 0);
2874 		break;
2875 
2876 	case SIOCSIFFLAGS:
2877 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2878 		if (rc)
2879 			return (rc);
2880 
2881 		if (hw_off_limits(sc)) {
2882 			rc = ENXIO;
2883 			goto fail;
2884 		}
2885 
2886 		if (if_getflags(ifp) & IFF_UP) {
2887 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2888 				flags = vi->if_flags;
2889 				if ((if_getflags(ifp) ^ flags) &
2890 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2891 					rc = update_mac_settings(ifp,
2892 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2893 				}
2894 			} else {
2895 				rc = cxgbe_init_synchronized(vi);
2896 			}
2897 			vi->if_flags = if_getflags(ifp);
2898 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2899 			rc = cxgbe_uninit_synchronized(vi);
2900 		}
2901 		end_synchronized_op(sc, 0);
2902 		break;
2903 
2904 	case SIOCADDMULTI:
2905 	case SIOCDELMULTI:
2906 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2907 		if (rc)
2908 			return (rc);
2909 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2910 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2911 		end_synchronized_op(sc, 0);
2912 		break;
2913 
2914 	case SIOCSIFCAP:
2915 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2916 		if (rc)
2917 			return (rc);
2918 
2919 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2920 		if (mask & IFCAP_TXCSUM) {
2921 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2922 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2923 
2924 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2925 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2926 				mask &= ~IFCAP_TSO4;
2927 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2928 				if_printf(ifp,
2929 				    "tso4 disabled due to -txcsum.\n");
2930 			}
2931 		}
2932 		if (mask & IFCAP_TXCSUM_IPV6) {
2933 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2934 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2935 
2936 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2937 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2938 				mask &= ~IFCAP_TSO6;
2939 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2940 				if_printf(ifp,
2941 				    "tso6 disabled due to -txcsum6.\n");
2942 			}
2943 		}
2944 		if (mask & IFCAP_RXCSUM)
2945 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2946 		if (mask & IFCAP_RXCSUM_IPV6)
2947 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2948 
2949 		/*
2950 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2951 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2952 		 * sending a TSO request our way, so it's sufficient to toggle
2953 		 * IFCAP_TSOx only.
2954 		 */
2955 		if (mask & IFCAP_TSO4) {
2956 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2957 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2958 				if_printf(ifp, "enable txcsum first.\n");
2959 				rc = EAGAIN;
2960 				goto fail;
2961 			}
2962 			if_togglecapenable(ifp, IFCAP_TSO4);
2963 		}
2964 		if (mask & IFCAP_TSO6) {
2965 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2966 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2967 				if_printf(ifp, "enable txcsum6 first.\n");
2968 				rc = EAGAIN;
2969 				goto fail;
2970 			}
2971 			if_togglecapenable(ifp, IFCAP_TSO6);
2972 		}
2973 		if (mask & IFCAP_LRO) {
2974 #if defined(INET) || defined(INET6)
2975 			int i;
2976 			struct sge_rxq *rxq;
2977 
2978 			if_togglecapenable(ifp, IFCAP_LRO);
2979 			for_each_rxq(vi, i, rxq) {
2980 				if (if_getcapenable(ifp) & IFCAP_LRO)
2981 					rxq->iq.flags |= IQ_LRO_ENABLED;
2982 				else
2983 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2984 			}
2985 #endif
2986 		}
2987 #ifdef TCP_OFFLOAD
2988 		if (mask & IFCAP_TOE) {
2989 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2990 
2991 			rc = toe_capability(vi, enable);
2992 			if (rc != 0)
2993 				goto fail;
2994 
2995 			if_togglecapenable(ifp, mask);
2996 		}
2997 #endif
2998 		if (mask & IFCAP_VLAN_HWTAGGING) {
2999 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
3000 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
3001 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
3002 		}
3003 		if (mask & IFCAP_VLAN_MTU) {
3004 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
3005 
3006 			/* Need to find out how to disable auto-mtu-inflation */
3007 		}
3008 		if (mask & IFCAP_VLAN_HWTSO)
3009 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
3010 		if (mask & IFCAP_VLAN_HWCSUM)
3011 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
3012 #ifdef RATELIMIT
3013 		if (mask & IFCAP_TXRTLMT)
3014 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
3015 #endif
3016 		if (mask & IFCAP_HWRXTSTMP) {
3017 			int i;
3018 			struct sge_rxq *rxq;
3019 
3020 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
3021 			for_each_rxq(vi, i, rxq) {
3022 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
3023 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
3024 				else
3025 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
3026 			}
3027 		}
3028 		if (mask & IFCAP_MEXTPG)
3029 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3030 
3031 #ifdef KERN_TLS
3032 		if (mask & IFCAP_TXTLS) {
3033 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3034 
3035 			rc = ktls_capability(sc, enable);
3036 			if (rc != 0)
3037 				goto fail;
3038 
3039 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3040 		}
3041 #endif
3042 		if (mask & IFCAP_VXLAN_HWCSUM) {
3043 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3044 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3045 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3046 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3047 		}
3048 		if (mask & IFCAP_VXLAN_HWTSO) {
3049 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3050 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3051 			    CSUM_INNER_IP_TSO);
3052 		}
3053 
3054 #ifdef VLAN_CAPABILITIES
3055 		VLAN_CAPABILITIES(ifp);
3056 #endif
3057 fail:
3058 		end_synchronized_op(sc, 0);
3059 		break;
3060 
3061 	case SIOCSIFMEDIA:
3062 	case SIOCGIFMEDIA:
3063 	case SIOCGIFXMEDIA:
3064 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3065 		break;
3066 
3067 	case SIOCGI2C: {
3068 		struct ifi2creq i2c;
3069 
3070 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3071 		if (rc != 0)
3072 			break;
3073 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3074 			rc = EPERM;
3075 			break;
3076 		}
3077 		if (i2c.len > sizeof(i2c.data)) {
3078 			rc = EINVAL;
3079 			break;
3080 		}
3081 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3082 		if (rc)
3083 			return (rc);
3084 		if (hw_off_limits(sc))
3085 			rc = ENXIO;
3086 		else
3087 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3088 			    i2c.offset, i2c.len, &i2c.data[0]);
3089 		end_synchronized_op(sc, 0);
3090 		if (rc == 0)
3091 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3092 		break;
3093 	}
3094 
3095 	default:
3096 		rc = ether_ioctl(ifp, cmd, data);
3097 	}
3098 
3099 	return (rc);
3100 }
3101 
3102 static int
3103 cxgbe_transmit(if_t ifp, struct mbuf *m)
3104 {
3105 	struct vi_info *vi = if_getsoftc(ifp);
3106 	struct port_info *pi = vi->pi;
3107 	struct adapter *sc;
3108 	struct sge_txq *txq;
3109 	void *items[1];
3110 	int rc;
3111 
3112 	M_ASSERTPKTHDR(m);
3113 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3114 #if defined(KERN_TLS) || defined(RATELIMIT)
3115 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3116 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3117 #endif
3118 
3119 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3120 		m_freem(m);
3121 		return (ENETDOWN);
3122 	}
3123 
3124 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3125 	if (__predict_false(rc != 0)) {
3126 		if (__predict_true(rc == EINPROGRESS)) {
3127 			/* queued by parse_pkt */
3128 			MPASS(m != NULL);
3129 			return (0);
3130 		}
3131 
3132 		MPASS(m == NULL);			/* was freed already */
3133 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3134 		return (rc);
3135 	}
3136 
3137 	/* Select a txq. */
3138 	sc = vi->adapter;
3139 	txq = &sc->sge.txq[vi->first_txq];
3140 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3141 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3142 		    vi->rsrv_noflowq);
3143 
3144 	items[0] = m;
3145 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3146 	if (__predict_false(rc != 0))
3147 		m_freem(m);
3148 
3149 	return (rc);
3150 }
3151 
3152 static void
3153 cxgbe_qflush(if_t ifp)
3154 {
3155 	struct vi_info *vi = if_getsoftc(ifp);
3156 	struct sge_txq *txq;
3157 	int i;
3158 
3159 	/* queues do not exist if !VI_INIT_DONE. */
3160 	if (vi->flags & VI_INIT_DONE) {
3161 		for_each_txq(vi, i, txq) {
3162 			TXQ_LOCK(txq);
3163 			txq->eq.flags |= EQ_QFLUSH;
3164 			TXQ_UNLOCK(txq);
3165 			while (!mp_ring_is_idle(txq->r)) {
3166 				mp_ring_check_drainage(txq->r, 4096);
3167 				pause("qflush", 1);
3168 			}
3169 			TXQ_LOCK(txq);
3170 			txq->eq.flags &= ~EQ_QFLUSH;
3171 			TXQ_UNLOCK(txq);
3172 		}
3173 	}
3174 	if_qflush(ifp);
3175 }
3176 
3177 static uint64_t
3178 vi_get_counter(if_t ifp, ift_counter c)
3179 {
3180 	struct vi_info *vi = if_getsoftc(ifp);
3181 	struct fw_vi_stats_vf *s = &vi->stats;
3182 
3183 	mtx_lock(&vi->tick_mtx);
3184 	vi_refresh_stats(vi);
3185 	mtx_unlock(&vi->tick_mtx);
3186 
3187 	switch (c) {
3188 	case IFCOUNTER_IPACKETS:
3189 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3190 		    s->rx_ucast_frames);
3191 	case IFCOUNTER_IERRORS:
3192 		return (s->rx_err_frames);
3193 	case IFCOUNTER_OPACKETS:
3194 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3195 		    s->tx_ucast_frames + s->tx_offload_frames);
3196 	case IFCOUNTER_OERRORS:
3197 		return (s->tx_drop_frames);
3198 	case IFCOUNTER_IBYTES:
3199 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3200 		    s->rx_ucast_bytes);
3201 	case IFCOUNTER_OBYTES:
3202 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3203 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3204 	case IFCOUNTER_IMCASTS:
3205 		return (s->rx_mcast_frames);
3206 	case IFCOUNTER_OMCASTS:
3207 		return (s->tx_mcast_frames);
3208 	case IFCOUNTER_OQDROPS: {
3209 		uint64_t drops;
3210 
3211 		drops = 0;
3212 		if (vi->flags & VI_INIT_DONE) {
3213 			int i;
3214 			struct sge_txq *txq;
3215 
3216 			for_each_txq(vi, i, txq)
3217 				drops += counter_u64_fetch(txq->r->dropped);
3218 		}
3219 
3220 		return (drops);
3221 
3222 	}
3223 
3224 	default:
3225 		return (if_get_counter_default(ifp, c));
3226 	}
3227 }
3228 
3229 static uint64_t
3230 cxgbe_get_counter(if_t ifp, ift_counter c)
3231 {
3232 	struct vi_info *vi = if_getsoftc(ifp);
3233 	struct port_info *pi = vi->pi;
3234 	struct port_stats *s = &pi->stats;
3235 
3236 	mtx_lock(&vi->tick_mtx);
3237 	cxgbe_refresh_stats(vi);
3238 	mtx_unlock(&vi->tick_mtx);
3239 
3240 	switch (c) {
3241 	case IFCOUNTER_IPACKETS:
3242 		return (s->rx_frames);
3243 
3244 	case IFCOUNTER_IERRORS:
3245 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3246 		    s->rx_fcs_err + s->rx_len_err);
3247 
3248 	case IFCOUNTER_OPACKETS:
3249 		return (s->tx_frames);
3250 
3251 	case IFCOUNTER_OERRORS:
3252 		return (s->tx_error_frames);
3253 
3254 	case IFCOUNTER_IBYTES:
3255 		return (s->rx_octets);
3256 
3257 	case IFCOUNTER_OBYTES:
3258 		return (s->tx_octets);
3259 
3260 	case IFCOUNTER_IMCASTS:
3261 		return (s->rx_mcast_frames);
3262 
3263 	case IFCOUNTER_OMCASTS:
3264 		return (s->tx_mcast_frames);
3265 
3266 	case IFCOUNTER_IQDROPS:
3267 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3268 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3269 		    s->rx_trunc3 + pi->tnl_cong_drops);
3270 
3271 	case IFCOUNTER_OQDROPS: {
3272 		uint64_t drops;
3273 
3274 		drops = s->tx_drop;
3275 		if (vi->flags & VI_INIT_DONE) {
3276 			int i;
3277 			struct sge_txq *txq;
3278 
3279 			for_each_txq(vi, i, txq)
3280 				drops += counter_u64_fetch(txq->r->dropped);
3281 		}
3282 
3283 		return (drops);
3284 
3285 	}
3286 
3287 	default:
3288 		return (if_get_counter_default(ifp, c));
3289 	}
3290 }
3291 
3292 #if defined(KERN_TLS) || defined(RATELIMIT)
3293 static int
3294 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3295     struct m_snd_tag **pt)
3296 {
3297 	int error;
3298 
3299 	switch (params->hdr.type) {
3300 #ifdef RATELIMIT
3301 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3302 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3303 		break;
3304 #endif
3305 #ifdef KERN_TLS
3306 	case IF_SND_TAG_TYPE_TLS:
3307 	{
3308 		struct vi_info *vi = if_getsoftc(ifp);
3309 
3310 		if (is_t6(vi->pi->adapter))
3311 			error = t6_tls_tag_alloc(ifp, params, pt);
3312 		else
3313 			error = EOPNOTSUPP;
3314 		break;
3315 	}
3316 #endif
3317 	default:
3318 		error = EOPNOTSUPP;
3319 	}
3320 	return (error);
3321 }
3322 #endif
3323 
3324 /*
3325  * The kernel picks a media from the list we had provided but we still validate
3326  * the requeste.
3327  */
3328 int
3329 cxgbe_media_change(if_t ifp)
3330 {
3331 	struct vi_info *vi = if_getsoftc(ifp);
3332 	struct port_info *pi = vi->pi;
3333 	struct ifmedia *ifm = &pi->media;
3334 	struct link_config *lc = &pi->link_cfg;
3335 	struct adapter *sc = pi->adapter;
3336 	int rc;
3337 
3338 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3339 	if (rc != 0)
3340 		return (rc);
3341 	PORT_LOCK(pi);
3342 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3343 		/* ifconfig .. media autoselect */
3344 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3345 			rc = ENOTSUP; /* AN not supported by transceiver */
3346 			goto done;
3347 		}
3348 		lc->requested_aneg = AUTONEG_ENABLE;
3349 		lc->requested_speed = 0;
3350 		lc->requested_fc |= PAUSE_AUTONEG;
3351 	} else {
3352 		lc->requested_aneg = AUTONEG_DISABLE;
3353 		lc->requested_speed =
3354 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3355 		lc->requested_fc = 0;
3356 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3357 			lc->requested_fc |= PAUSE_RX;
3358 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3359 			lc->requested_fc |= PAUSE_TX;
3360 	}
3361 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3362 		fixup_link_config(pi);
3363 		rc = apply_link_config(pi);
3364 	}
3365 done:
3366 	PORT_UNLOCK(pi);
3367 	end_synchronized_op(sc, 0);
3368 	return (rc);
3369 }
3370 
3371 /*
3372  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3373  * given speed.
3374  */
3375 static int
3376 port_mword(struct port_info *pi, uint32_t speed)
3377 {
3378 
3379 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3380 	MPASS(powerof2(speed));
3381 
3382 	switch(pi->port_type) {
3383 	case FW_PORT_TYPE_BT_SGMII:
3384 	case FW_PORT_TYPE_BT_XFI:
3385 	case FW_PORT_TYPE_BT_XAUI:
3386 		/* BaseT */
3387 		switch (speed) {
3388 		case FW_PORT_CAP32_SPEED_100M:
3389 			return (IFM_100_T);
3390 		case FW_PORT_CAP32_SPEED_1G:
3391 			return (IFM_1000_T);
3392 		case FW_PORT_CAP32_SPEED_10G:
3393 			return (IFM_10G_T);
3394 		}
3395 		break;
3396 	case FW_PORT_TYPE_KX4:
3397 		if (speed == FW_PORT_CAP32_SPEED_10G)
3398 			return (IFM_10G_KX4);
3399 		break;
3400 	case FW_PORT_TYPE_CX4:
3401 		if (speed == FW_PORT_CAP32_SPEED_10G)
3402 			return (IFM_10G_CX4);
3403 		break;
3404 	case FW_PORT_TYPE_KX:
3405 		if (speed == FW_PORT_CAP32_SPEED_1G)
3406 			return (IFM_1000_KX);
3407 		break;
3408 	case FW_PORT_TYPE_KR:
3409 	case FW_PORT_TYPE_BP_AP:
3410 	case FW_PORT_TYPE_BP4_AP:
3411 	case FW_PORT_TYPE_BP40_BA:
3412 	case FW_PORT_TYPE_KR4_100G:
3413 	case FW_PORT_TYPE_KR_SFP28:
3414 	case FW_PORT_TYPE_KR_XLAUI:
3415 		switch (speed) {
3416 		case FW_PORT_CAP32_SPEED_1G:
3417 			return (IFM_1000_KX);
3418 		case FW_PORT_CAP32_SPEED_10G:
3419 			return (IFM_10G_KR);
3420 		case FW_PORT_CAP32_SPEED_25G:
3421 			return (IFM_25G_KR);
3422 		case FW_PORT_CAP32_SPEED_40G:
3423 			return (IFM_40G_KR4);
3424 		case FW_PORT_CAP32_SPEED_50G:
3425 			return (IFM_50G_KR2);
3426 		case FW_PORT_CAP32_SPEED_100G:
3427 			return (IFM_100G_KR4);
3428 		}
3429 		break;
3430 	case FW_PORT_TYPE_FIBER_XFI:
3431 	case FW_PORT_TYPE_FIBER_XAUI:
3432 	case FW_PORT_TYPE_SFP:
3433 	case FW_PORT_TYPE_QSFP_10G:
3434 	case FW_PORT_TYPE_QSA:
3435 	case FW_PORT_TYPE_QSFP:
3436 	case FW_PORT_TYPE_CR4_QSFP:
3437 	case FW_PORT_TYPE_CR_QSFP:
3438 	case FW_PORT_TYPE_CR2_QSFP:
3439 	case FW_PORT_TYPE_SFP28:
3440 		/* Pluggable transceiver */
3441 		switch (pi->mod_type) {
3442 		case FW_PORT_MOD_TYPE_LR:
3443 			switch (speed) {
3444 			case FW_PORT_CAP32_SPEED_1G:
3445 				return (IFM_1000_LX);
3446 			case FW_PORT_CAP32_SPEED_10G:
3447 				return (IFM_10G_LR);
3448 			case FW_PORT_CAP32_SPEED_25G:
3449 				return (IFM_25G_LR);
3450 			case FW_PORT_CAP32_SPEED_40G:
3451 				return (IFM_40G_LR4);
3452 			case FW_PORT_CAP32_SPEED_50G:
3453 				return (IFM_50G_LR2);
3454 			case FW_PORT_CAP32_SPEED_100G:
3455 				return (IFM_100G_LR4);
3456 			}
3457 			break;
3458 		case FW_PORT_MOD_TYPE_SR:
3459 			switch (speed) {
3460 			case FW_PORT_CAP32_SPEED_1G:
3461 				return (IFM_1000_SX);
3462 			case FW_PORT_CAP32_SPEED_10G:
3463 				return (IFM_10G_SR);
3464 			case FW_PORT_CAP32_SPEED_25G:
3465 				return (IFM_25G_SR);
3466 			case FW_PORT_CAP32_SPEED_40G:
3467 				return (IFM_40G_SR4);
3468 			case FW_PORT_CAP32_SPEED_50G:
3469 				return (IFM_50G_SR2);
3470 			case FW_PORT_CAP32_SPEED_100G:
3471 				return (IFM_100G_SR4);
3472 			}
3473 			break;
3474 		case FW_PORT_MOD_TYPE_ER:
3475 			if (speed == FW_PORT_CAP32_SPEED_10G)
3476 				return (IFM_10G_ER);
3477 			break;
3478 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3479 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3480 			switch (speed) {
3481 			case FW_PORT_CAP32_SPEED_1G:
3482 				return (IFM_1000_CX);
3483 			case FW_PORT_CAP32_SPEED_10G:
3484 				return (IFM_10G_TWINAX);
3485 			case FW_PORT_CAP32_SPEED_25G:
3486 				return (IFM_25G_CR);
3487 			case FW_PORT_CAP32_SPEED_40G:
3488 				return (IFM_40G_CR4);
3489 			case FW_PORT_CAP32_SPEED_50G:
3490 				return (IFM_50G_CR2);
3491 			case FW_PORT_CAP32_SPEED_100G:
3492 				return (IFM_100G_CR4);
3493 			}
3494 			break;
3495 		case FW_PORT_MOD_TYPE_LRM:
3496 			if (speed == FW_PORT_CAP32_SPEED_10G)
3497 				return (IFM_10G_LRM);
3498 			break;
3499 		case FW_PORT_MOD_TYPE_NA:
3500 			MPASS(0);	/* Not pluggable? */
3501 			/* fall throough */
3502 		case FW_PORT_MOD_TYPE_ERROR:
3503 		case FW_PORT_MOD_TYPE_UNKNOWN:
3504 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3505 			break;
3506 		case FW_PORT_MOD_TYPE_NONE:
3507 			return (IFM_NONE);
3508 		}
3509 		break;
3510 	case FW_PORT_TYPE_NONE:
3511 		return (IFM_NONE);
3512 	}
3513 
3514 	return (IFM_UNKNOWN);
3515 }
3516 
3517 void
3518 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3519 {
3520 	struct vi_info *vi = if_getsoftc(ifp);
3521 	struct port_info *pi = vi->pi;
3522 	struct adapter *sc = pi->adapter;
3523 	struct link_config *lc = &pi->link_cfg;
3524 
3525 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3526 		return;
3527 	PORT_LOCK(pi);
3528 
3529 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3530 		/*
3531 		 * If all the interfaces are administratively down the firmware
3532 		 * does not report transceiver changes.  Refresh port info here
3533 		 * so that ifconfig displays accurate ifmedia at all times.
3534 		 * This is the only reason we have a synchronized op in this
3535 		 * function.  Just PORT_LOCK would have been enough otherwise.
3536 		 */
3537 		t4_update_port_info(pi);
3538 		build_medialist(pi);
3539 	}
3540 
3541 	/* ifm_status */
3542 	ifmr->ifm_status = IFM_AVALID;
3543 	if (lc->link_ok == false)
3544 		goto done;
3545 	ifmr->ifm_status |= IFM_ACTIVE;
3546 
3547 	/* ifm_active */
3548 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3549 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3550 	if (lc->fc & PAUSE_RX)
3551 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3552 	if (lc->fc & PAUSE_TX)
3553 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3554 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3555 done:
3556 	PORT_UNLOCK(pi);
3557 	end_synchronized_op(sc, 0);
3558 }
3559 
3560 static int
3561 vcxgbe_probe(device_t dev)
3562 {
3563 	struct vi_info *vi = device_get_softc(dev);
3564 
3565 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3566 	    vi - vi->pi->vi);
3567 
3568 	return (BUS_PROBE_DEFAULT);
3569 }
3570 
3571 static int
3572 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3573 {
3574 	int func, index, rc;
3575 	uint32_t param, val;
3576 
3577 	ASSERT_SYNCHRONIZED_OP(sc);
3578 
3579 	index = vi - pi->vi;
3580 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3581 	KASSERT(index < nitems(vi_mac_funcs),
3582 	    ("%s: VI %s doesn't have a MAC func", __func__,
3583 	    device_get_nameunit(vi->dev)));
3584 	func = vi_mac_funcs[index];
3585 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3586 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3587 	if (rc < 0) {
3588 		CH_ERR(vi, "failed to allocate virtual interface %d"
3589 		    "for port %d: %d\n", index, pi->port_id, -rc);
3590 		return (-rc);
3591 	}
3592 	vi->viid = rc;
3593 
3594 	if (vi->rss_size == 1) {
3595 		/*
3596 		 * This VI didn't get a slice of the RSS table.  Reduce the
3597 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3598 		 * configuration file (nvi, rssnvi for this PF) if this is a
3599 		 * problem.
3600 		 */
3601 		device_printf(vi->dev, "RSS table not available.\n");
3602 		vi->rss_base = 0xffff;
3603 
3604 		return (0);
3605 	}
3606 
3607 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3608 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3609 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3610 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3611 	if (rc)
3612 		vi->rss_base = 0xffff;
3613 	else {
3614 		MPASS((val >> 16) == vi->rss_size);
3615 		vi->rss_base = val & 0xffff;
3616 	}
3617 
3618 	return (0);
3619 }
3620 
3621 static int
3622 vcxgbe_attach(device_t dev)
3623 {
3624 	struct vi_info *vi;
3625 	struct port_info *pi;
3626 	struct adapter *sc;
3627 	int rc;
3628 
3629 	vi = device_get_softc(dev);
3630 	pi = vi->pi;
3631 	sc = pi->adapter;
3632 
3633 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3634 	if (rc)
3635 		return (rc);
3636 	rc = alloc_extra_vi(sc, pi, vi);
3637 	end_synchronized_op(sc, 0);
3638 	if (rc)
3639 		return (rc);
3640 
3641 	cxgbe_vi_attach(dev, vi);
3642 
3643 	return (0);
3644 }
3645 
3646 static int
3647 vcxgbe_detach(device_t dev)
3648 {
3649 	struct vi_info *vi;
3650 	struct adapter *sc;
3651 
3652 	vi = device_get_softc(dev);
3653 	sc = vi->adapter;
3654 
3655 	begin_vi_detach(sc, vi);
3656 	cxgbe_vi_detach(vi);
3657 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3658 	end_vi_detach(sc, vi);
3659 
3660 	return (0);
3661 }
3662 
3663 static struct callout fatal_callout;
3664 static struct taskqueue *reset_tq;
3665 
3666 static void
3667 delayed_panic(void *arg)
3668 {
3669 	struct adapter *sc = arg;
3670 
3671 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3672 }
3673 
3674 static void
3675 fatal_error_task(void *arg, int pending)
3676 {
3677 	struct adapter *sc = arg;
3678 	int rc;
3679 
3680 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3681 		dump_cim_regs(sc);
3682 		dump_cimla(sc);
3683 		dump_devlog(sc);
3684 	}
3685 
3686 	if (t4_reset_on_fatal_err) {
3687 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3688 		rc = reset_adapter(sc);
3689 		if (rc == 0 && t4_panic_on_fatal_err) {
3690 			CH_ALERT(sc, "reset was successful, "
3691 			    "system will NOT panic.\n");
3692 			return;
3693 		}
3694 	}
3695 
3696 	if (t4_panic_on_fatal_err) {
3697 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3698 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3699 	}
3700 }
3701 
3702 void
3703 t4_fatal_err(struct adapter *sc, bool fw_error)
3704 {
3705 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3706 
3707 	stop_adapter(sc);
3708 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3709 		return;
3710 	if (fw_error) {
3711 		/*
3712 		 * We are here because of a firmware error/timeout and not
3713 		 * because of a hardware interrupt.  It is possible (although
3714 		 * not very likely) that an error interrupt was also raised but
3715 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3716 		 * main INT_CAUSE registers here to make sure we haven't missed
3717 		 * anything interesting.
3718 		 */
3719 		t4_slow_intr_handler(sc, verbose);
3720 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3721 	}
3722 	t4_report_fw_error(sc);
3723 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3724 	    device_get_nameunit(sc->dev), fw_error);
3725 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3726 }
3727 
3728 void
3729 t4_add_adapter(struct adapter *sc)
3730 {
3731 	sx_xlock(&t4_list_lock);
3732 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3733 	sx_xunlock(&t4_list_lock);
3734 }
3735 
3736 int
3737 t4_map_bars_0_and_4(struct adapter *sc)
3738 {
3739 	sc->regs_rid = PCIR_BAR(0);
3740 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3741 	    &sc->regs_rid, RF_ACTIVE);
3742 	if (sc->regs_res == NULL) {
3743 		device_printf(sc->dev, "cannot map registers.\n");
3744 		return (ENXIO);
3745 	}
3746 	sc->bt = rman_get_bustag(sc->regs_res);
3747 	sc->bh = rman_get_bushandle(sc->regs_res);
3748 	sc->mmio_len = rman_get_size(sc->regs_res);
3749 	setbit(&sc->doorbells, DOORBELL_KDB);
3750 
3751 	sc->msix_rid = PCIR_BAR(4);
3752 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3753 	    &sc->msix_rid, RF_ACTIVE);
3754 	if (sc->msix_res == NULL) {
3755 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3756 		return (ENXIO);
3757 	}
3758 
3759 	return (0);
3760 }
3761 
3762 int
3763 t4_map_bar_2(struct adapter *sc)
3764 {
3765 
3766 	/*
3767 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3768 	 * to map it if RDMA is disabled.
3769 	 */
3770 	if (is_t4(sc) && sc->rdmacaps == 0)
3771 		return (0);
3772 
3773 	sc->udbs_rid = PCIR_BAR(2);
3774 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3775 	    &sc->udbs_rid, RF_ACTIVE);
3776 	if (sc->udbs_res == NULL) {
3777 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3778 		return (ENXIO);
3779 	}
3780 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3781 
3782 	if (chip_id(sc) >= CHELSIO_T5) {
3783 		setbit(&sc->doorbells, DOORBELL_UDB);
3784 #if defined(__i386__) || defined(__amd64__)
3785 		if (t5_write_combine) {
3786 			int rc, mode;
3787 
3788 			/*
3789 			 * Enable write combining on BAR2.  This is the
3790 			 * userspace doorbell BAR and is split into 128B
3791 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3792 			 * with an egress queue.  The first 64B has the doorbell
3793 			 * and the second 64B can be used to submit a tx work
3794 			 * request with an implicit doorbell.
3795 			 */
3796 
3797 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3798 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3799 			if (rc == 0) {
3800 				clrbit(&sc->doorbells, DOORBELL_UDB);
3801 				setbit(&sc->doorbells, DOORBELL_WCWR);
3802 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3803 			} else {
3804 				device_printf(sc->dev,
3805 				    "couldn't enable write combining: %d\n",
3806 				    rc);
3807 			}
3808 
3809 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3810 			t4_write_reg(sc, A_SGE_STAT_CFG,
3811 			    V_STATSOURCE_T5(7) | mode);
3812 		}
3813 #endif
3814 	}
3815 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3816 
3817 	return (0);
3818 }
3819 
3820 int
3821 t4_adj_doorbells(struct adapter *sc)
3822 {
3823 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3824 		sc->doorbells &= t4_doorbells_allowed;
3825 		return (0);
3826 	}
3827 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3828 	       sc->doorbells, t4_doorbells_allowed);
3829 	return (EINVAL);
3830 }
3831 
3832 struct memwin_init {
3833 	uint32_t base;
3834 	uint32_t aperture;
3835 };
3836 
3837 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3838 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3839 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3840 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3841 };
3842 
3843 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3844 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3845 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3846 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3847 };
3848 
3849 static void
3850 setup_memwin(struct adapter *sc)
3851 {
3852 	const struct memwin_init *mw_init;
3853 	struct memwin *mw;
3854 	int i;
3855 	uint32_t bar0;
3856 
3857 	if (is_t4(sc)) {
3858 		/*
3859 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3860 		 * mechanism.  Works from within PCI passthrough environments
3861 		 * too, where rman_get_start() can return a different value.  We
3862 		 * need to program the T4 memory window decoders with the actual
3863 		 * addresses that will be coming across the PCIe link.
3864 		 */
3865 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3866 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3867 
3868 		mw_init = &t4_memwin[0];
3869 	} else {
3870 		/* T5+ use the relative offset inside the PCIe BAR */
3871 		bar0 = 0;
3872 
3873 		mw_init = &t5_memwin[0];
3874 	}
3875 
3876 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3877 		if (!rw_initialized(&mw->mw_lock)) {
3878 			rw_init(&mw->mw_lock, "memory window access");
3879 			mw->mw_base = mw_init->base;
3880 			mw->mw_aperture = mw_init->aperture;
3881 			mw->mw_curpos = 0;
3882 		}
3883 		t4_write_reg(sc,
3884 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3885 		    (mw->mw_base + bar0) | V_BIR(0) |
3886 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3887 		rw_wlock(&mw->mw_lock);
3888 		position_memwin(sc, i, mw->mw_curpos);
3889 		rw_wunlock(&mw->mw_lock);
3890 	}
3891 
3892 	/* flush */
3893 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3894 }
3895 
3896 /*
3897  * Positions the memory window at the given address in the card's address space.
3898  * There are some alignment requirements and the actual position may be at an
3899  * address prior to the requested address.  mw->mw_curpos always has the actual
3900  * position of the window.
3901  */
3902 static void
3903 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3904 {
3905 	struct memwin *mw;
3906 	uint32_t pf;
3907 	uint32_t reg;
3908 
3909 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3910 	mw = &sc->memwin[idx];
3911 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3912 
3913 	if (is_t4(sc)) {
3914 		pf = 0;
3915 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3916 	} else {
3917 		pf = V_PFNUM(sc->pf);
3918 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3919 	}
3920 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3921 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3922 	t4_read_reg(sc, reg);	/* flush */
3923 }
3924 
3925 int
3926 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3927     int len, int rw)
3928 {
3929 	struct memwin *mw;
3930 	uint32_t mw_end, v;
3931 
3932 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3933 
3934 	/* Memory can only be accessed in naturally aligned 4 byte units */
3935 	if (addr & 3 || len & 3 || len <= 0)
3936 		return (EINVAL);
3937 
3938 	mw = &sc->memwin[idx];
3939 	while (len > 0) {
3940 		rw_rlock(&mw->mw_lock);
3941 		mw_end = mw->mw_curpos + mw->mw_aperture;
3942 		if (addr >= mw_end || addr < mw->mw_curpos) {
3943 			/* Will need to reposition the window */
3944 			if (!rw_try_upgrade(&mw->mw_lock)) {
3945 				rw_runlock(&mw->mw_lock);
3946 				rw_wlock(&mw->mw_lock);
3947 			}
3948 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3949 			position_memwin(sc, idx, addr);
3950 			rw_downgrade(&mw->mw_lock);
3951 			mw_end = mw->mw_curpos + mw->mw_aperture;
3952 		}
3953 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3954 		while (addr < mw_end && len > 0) {
3955 			if (rw == 0) {
3956 				v = t4_read_reg(sc, mw->mw_base + addr -
3957 				    mw->mw_curpos);
3958 				*val++ = le32toh(v);
3959 			} else {
3960 				v = *val++;
3961 				t4_write_reg(sc, mw->mw_base + addr -
3962 				    mw->mw_curpos, htole32(v));
3963 			}
3964 			addr += 4;
3965 			len -= 4;
3966 		}
3967 		rw_runlock(&mw->mw_lock);
3968 	}
3969 
3970 	return (0);
3971 }
3972 
3973 CTASSERT(M_TID_COOKIE == M_COOKIE);
3974 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3975 
3976 static void
3977 t4_init_atid_table(struct adapter *sc)
3978 {
3979 	struct tid_info *t;
3980 	int i;
3981 
3982 	t = &sc->tids;
3983 	if (t->natids == 0)
3984 		return;
3985 
3986 	MPASS(t->atid_tab == NULL);
3987 
3988 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3989 	    M_ZERO | M_WAITOK);
3990 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3991 	t->afree = t->atid_tab;
3992 	t->atids_in_use = 0;
3993 	t->atid_alloc_stopped = false;
3994 	for (i = 1; i < t->natids; i++)
3995 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3996 	t->atid_tab[t->natids - 1].next = NULL;
3997 }
3998 
3999 static void
4000 t4_free_atid_table(struct adapter *sc)
4001 {
4002 	struct tid_info *t;
4003 
4004 	t = &sc->tids;
4005 
4006 	KASSERT(t->atids_in_use == 0,
4007 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4008 
4009 	if (mtx_initialized(&t->atid_lock))
4010 		mtx_destroy(&t->atid_lock);
4011 	free(t->atid_tab, M_CXGBE);
4012 	t->atid_tab = NULL;
4013 }
4014 
4015 static void
4016 stop_atid_allocator(struct adapter *sc)
4017 {
4018 	struct tid_info *t = &sc->tids;
4019 
4020 	mtx_lock(&t->atid_lock);
4021 	t->atid_alloc_stopped = true;
4022 	mtx_unlock(&t->atid_lock);
4023 }
4024 
4025 static void
4026 restart_atid_allocator(struct adapter *sc)
4027 {
4028 	struct tid_info *t = &sc->tids;
4029 
4030 	mtx_lock(&t->atid_lock);
4031 	KASSERT(t->atids_in_use == 0,
4032 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4033 	t->atid_alloc_stopped = false;
4034 	mtx_unlock(&t->atid_lock);
4035 }
4036 
4037 int
4038 alloc_atid(struct adapter *sc, void *ctx)
4039 {
4040 	struct tid_info *t = &sc->tids;
4041 	int atid = -1;
4042 
4043 	mtx_lock(&t->atid_lock);
4044 	if (t->afree && !t->atid_alloc_stopped) {
4045 		union aopen_entry *p = t->afree;
4046 
4047 		atid = p - t->atid_tab;
4048 		MPASS(atid <= M_TID_TID);
4049 		t->afree = p->next;
4050 		p->data = ctx;
4051 		t->atids_in_use++;
4052 	}
4053 	mtx_unlock(&t->atid_lock);
4054 	return (atid);
4055 }
4056 
4057 void *
4058 lookup_atid(struct adapter *sc, int atid)
4059 {
4060 	struct tid_info *t = &sc->tids;
4061 
4062 	return (t->atid_tab[atid].data);
4063 }
4064 
4065 void
4066 free_atid(struct adapter *sc, int atid)
4067 {
4068 	struct tid_info *t = &sc->tids;
4069 	union aopen_entry *p = &t->atid_tab[atid];
4070 
4071 	mtx_lock(&t->atid_lock);
4072 	p->next = t->afree;
4073 	t->afree = p;
4074 	t->atids_in_use--;
4075 	mtx_unlock(&t->atid_lock);
4076 }
4077 
4078 static void
4079 queue_tid_release(struct adapter *sc, int tid)
4080 {
4081 
4082 	CXGBE_UNIMPLEMENTED("deferred tid release");
4083 }
4084 
4085 void
4086 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4087 {
4088 	struct wrqe *wr;
4089 	struct cpl_tid_release *req;
4090 
4091 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4092 	if (wr == NULL) {
4093 		queue_tid_release(sc, tid);	/* defer */
4094 		return;
4095 	}
4096 	req = wrtod(wr);
4097 
4098 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4099 
4100 	t4_wrq_tx(sc, wr);
4101 }
4102 
4103 static int
4104 t4_range_cmp(const void *a, const void *b)
4105 {
4106 	return ((const struct t4_range *)a)->start -
4107 	       ((const struct t4_range *)b)->start;
4108 }
4109 
4110 /*
4111  * Verify that the memory range specified by the addr/len pair is valid within
4112  * the card's address space.
4113  */
4114 static int
4115 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4116 {
4117 	struct t4_range mem_ranges[4], *r, *next;
4118 	uint32_t em, addr_len;
4119 	int i, n, remaining;
4120 
4121 	/* Memory can only be accessed in naturally aligned 4 byte units */
4122 	if (addr & 3 || len & 3 || len == 0)
4123 		return (EINVAL);
4124 
4125 	/* Enabled memories */
4126 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4127 
4128 	r = &mem_ranges[0];
4129 	n = 0;
4130 	bzero(r, sizeof(mem_ranges));
4131 	if (em & F_EDRAM0_ENABLE) {
4132 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4133 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4134 		if (r->size > 0) {
4135 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4136 			if (addr >= r->start &&
4137 			    addr + len <= r->start + r->size)
4138 				return (0);
4139 			r++;
4140 			n++;
4141 		}
4142 	}
4143 	if (em & F_EDRAM1_ENABLE) {
4144 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4145 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4146 		if (r->size > 0) {
4147 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4148 			if (addr >= r->start &&
4149 			    addr + len <= r->start + r->size)
4150 				return (0);
4151 			r++;
4152 			n++;
4153 		}
4154 	}
4155 	if (em & F_EXT_MEM_ENABLE) {
4156 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4157 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4158 		if (r->size > 0) {
4159 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4160 			if (addr >= r->start &&
4161 			    addr + len <= r->start + r->size)
4162 				return (0);
4163 			r++;
4164 			n++;
4165 		}
4166 	}
4167 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4168 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4169 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4170 		if (r->size > 0) {
4171 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4172 			if (addr >= r->start &&
4173 			    addr + len <= r->start + r->size)
4174 				return (0);
4175 			r++;
4176 			n++;
4177 		}
4178 	}
4179 	MPASS(n <= nitems(mem_ranges));
4180 
4181 	if (n > 1) {
4182 		/* Sort and merge the ranges. */
4183 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4184 
4185 		/* Start from index 0 and examine the next n - 1 entries. */
4186 		r = &mem_ranges[0];
4187 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4188 
4189 			MPASS(r->size > 0);	/* r is a valid entry. */
4190 			next = r + 1;
4191 			MPASS(next->size > 0);	/* and so is the next one. */
4192 
4193 			while (r->start + r->size >= next->start) {
4194 				/* Merge the next one into the current entry. */
4195 				r->size = max(r->start + r->size,
4196 				    next->start + next->size) - r->start;
4197 				n--;	/* One fewer entry in total. */
4198 				if (--remaining == 0)
4199 					goto done;	/* short circuit */
4200 				next++;
4201 			}
4202 			if (next != r + 1) {
4203 				/*
4204 				 * Some entries were merged into r and next
4205 				 * points to the first valid entry that couldn't
4206 				 * be merged.
4207 				 */
4208 				MPASS(next->size > 0);	/* must be valid */
4209 				memcpy(r + 1, next, remaining * sizeof(*r));
4210 #ifdef INVARIANTS
4211 				/*
4212 				 * This so that the foo->size assertion in the
4213 				 * next iteration of the loop do the right
4214 				 * thing for entries that were pulled up and are
4215 				 * no longer valid.
4216 				 */
4217 				MPASS(n < nitems(mem_ranges));
4218 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4219 				    sizeof(struct t4_range));
4220 #endif
4221 			}
4222 		}
4223 done:
4224 		/* Done merging the ranges. */
4225 		MPASS(n > 0);
4226 		r = &mem_ranges[0];
4227 		for (i = 0; i < n; i++, r++) {
4228 			if (addr >= r->start &&
4229 			    addr + len <= r->start + r->size)
4230 				return (0);
4231 		}
4232 	}
4233 
4234 	return (EFAULT);
4235 }
4236 
4237 static int
4238 fwmtype_to_hwmtype(int mtype)
4239 {
4240 
4241 	switch (mtype) {
4242 	case FW_MEMTYPE_EDC0:
4243 		return (MEM_EDC0);
4244 	case FW_MEMTYPE_EDC1:
4245 		return (MEM_EDC1);
4246 	case FW_MEMTYPE_EXTMEM:
4247 		return (MEM_MC0);
4248 	case FW_MEMTYPE_EXTMEM1:
4249 		return (MEM_MC1);
4250 	default:
4251 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4252 	}
4253 }
4254 
4255 /*
4256  * Verify that the memory range specified by the memtype/offset/len pair is
4257  * valid and lies entirely within the memtype specified.  The global address of
4258  * the start of the range is returned in addr.
4259  */
4260 static int
4261 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4262     uint32_t *addr)
4263 {
4264 	uint32_t em, addr_len, maddr;
4265 
4266 	/* Memory can only be accessed in naturally aligned 4 byte units */
4267 	if (off & 3 || len & 3 || len == 0)
4268 		return (EINVAL);
4269 
4270 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4271 	switch (fwmtype_to_hwmtype(mtype)) {
4272 	case MEM_EDC0:
4273 		if (!(em & F_EDRAM0_ENABLE))
4274 			return (EINVAL);
4275 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4276 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4277 		break;
4278 	case MEM_EDC1:
4279 		if (!(em & F_EDRAM1_ENABLE))
4280 			return (EINVAL);
4281 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4282 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4283 		break;
4284 	case MEM_MC:
4285 		if (!(em & F_EXT_MEM_ENABLE))
4286 			return (EINVAL);
4287 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4288 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4289 		break;
4290 	case MEM_MC1:
4291 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4292 			return (EINVAL);
4293 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4294 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4295 		break;
4296 	default:
4297 		return (EINVAL);
4298 	}
4299 
4300 	*addr = maddr + off;	/* global address */
4301 	return (validate_mem_range(sc, *addr, len));
4302 }
4303 
4304 static int
4305 fixup_devlog_params(struct adapter *sc)
4306 {
4307 	struct devlog_params *dparams = &sc->params.devlog;
4308 	int rc;
4309 
4310 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4311 	    dparams->size, &dparams->addr);
4312 
4313 	return (rc);
4314 }
4315 
4316 static void
4317 update_nirq(struct intrs_and_queues *iaq, int nports)
4318 {
4319 
4320 	iaq->nirq = T4_EXTRA_INTR;
4321 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4322 	iaq->nirq += nports * iaq->nofldrxq;
4323 	iaq->nirq += nports * (iaq->num_vis - 1) *
4324 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4325 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4326 }
4327 
4328 /*
4329  * Adjust requirements to fit the number of interrupts available.
4330  */
4331 static void
4332 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4333     int navail)
4334 {
4335 	int old_nirq;
4336 	const int nports = sc->params.nports;
4337 
4338 	MPASS(nports > 0);
4339 	MPASS(navail > 0);
4340 
4341 	bzero(iaq, sizeof(*iaq));
4342 	iaq->intr_type = itype;
4343 	iaq->num_vis = t4_num_vis;
4344 	iaq->ntxq = t4_ntxq;
4345 	iaq->ntxq_vi = t4_ntxq_vi;
4346 	iaq->nrxq = t4_nrxq;
4347 	iaq->nrxq_vi = t4_nrxq_vi;
4348 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4349 	if (is_offload(sc) || is_ethoffload(sc)) {
4350 		iaq->nofldtxq = t4_nofldtxq;
4351 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4352 	}
4353 #endif
4354 #ifdef TCP_OFFLOAD
4355 	if (is_offload(sc)) {
4356 		iaq->nofldrxq = t4_nofldrxq;
4357 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4358 	}
4359 #endif
4360 #ifdef DEV_NETMAP
4361 	if (t4_native_netmap & NN_MAIN_VI) {
4362 		iaq->nnmtxq = t4_nnmtxq;
4363 		iaq->nnmrxq = t4_nnmrxq;
4364 	}
4365 	if (t4_native_netmap & NN_EXTRA_VI) {
4366 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4367 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4368 	}
4369 #endif
4370 
4371 	update_nirq(iaq, nports);
4372 	if (iaq->nirq <= navail &&
4373 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4374 		/*
4375 		 * This is the normal case -- there are enough interrupts for
4376 		 * everything.
4377 		 */
4378 		goto done;
4379 	}
4380 
4381 	/*
4382 	 * If extra VIs have been configured try reducing their count and see if
4383 	 * that works.
4384 	 */
4385 	while (iaq->num_vis > 1) {
4386 		iaq->num_vis--;
4387 		update_nirq(iaq, nports);
4388 		if (iaq->nirq <= navail &&
4389 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4390 			device_printf(sc->dev, "virtual interfaces per port "
4391 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4392 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4393 			    "itype %d, navail %u, nirq %d.\n",
4394 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4395 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4396 			    itype, navail, iaq->nirq);
4397 			goto done;
4398 		}
4399 	}
4400 
4401 	/*
4402 	 * Extra VIs will not be created.  Log a message if they were requested.
4403 	 */
4404 	MPASS(iaq->num_vis == 1);
4405 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4406 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4407 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4408 	if (iaq->num_vis != t4_num_vis) {
4409 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4410 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4411 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4412 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4413 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4414 	}
4415 
4416 	/*
4417 	 * Keep reducing the number of NIC rx queues to the next lower power of
4418 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4419 	 * if that works.
4420 	 */
4421 	do {
4422 		if (iaq->nrxq > 1) {
4423 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4424 			if (iaq->nnmrxq > iaq->nrxq)
4425 				iaq->nnmrxq = iaq->nrxq;
4426 		}
4427 		if (iaq->nofldrxq > 1)
4428 			iaq->nofldrxq >>= 1;
4429 
4430 		old_nirq = iaq->nirq;
4431 		update_nirq(iaq, nports);
4432 		if (iaq->nirq <= navail &&
4433 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4434 			device_printf(sc->dev, "running with reduced number of "
4435 			    "rx queues because of shortage of interrupts.  "
4436 			    "nrxq=%u, nofldrxq=%u.  "
4437 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4438 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4439 			goto done;
4440 		}
4441 	} while (old_nirq != iaq->nirq);
4442 
4443 	/* One interrupt for everything.  Ugh. */
4444 	device_printf(sc->dev, "running with minimal number of queues.  "
4445 	    "itype %d, navail %u.\n", itype, navail);
4446 	iaq->nirq = 1;
4447 	iaq->nrxq = 1;
4448 	iaq->ntxq = 1;
4449 	if (iaq->nofldrxq > 0) {
4450 		iaq->nofldrxq = 1;
4451 		iaq->nofldtxq = 1;
4452 	}
4453 	iaq->nnmtxq = 0;
4454 	iaq->nnmrxq = 0;
4455 done:
4456 	MPASS(iaq->num_vis > 0);
4457 	if (iaq->num_vis > 1) {
4458 		MPASS(iaq->nrxq_vi > 0);
4459 		MPASS(iaq->ntxq_vi > 0);
4460 	}
4461 	MPASS(iaq->nirq > 0);
4462 	MPASS(iaq->nrxq > 0);
4463 	MPASS(iaq->ntxq > 0);
4464 	if (itype == INTR_MSI) {
4465 		MPASS(powerof2(iaq->nirq));
4466 	}
4467 }
4468 
4469 static int
4470 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4471 {
4472 	int rc, itype, navail, nalloc;
4473 
4474 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4475 
4476 		if ((itype & t4_intr_types) == 0)
4477 			continue;	/* not allowed */
4478 
4479 		if (itype == INTR_MSIX)
4480 			navail = pci_msix_count(sc->dev);
4481 		else if (itype == INTR_MSI)
4482 			navail = pci_msi_count(sc->dev);
4483 		else
4484 			navail = 1;
4485 restart:
4486 		if (navail == 0)
4487 			continue;
4488 
4489 		calculate_iaq(sc, iaq, itype, navail);
4490 		nalloc = iaq->nirq;
4491 		rc = 0;
4492 		if (itype == INTR_MSIX)
4493 			rc = pci_alloc_msix(sc->dev, &nalloc);
4494 		else if (itype == INTR_MSI)
4495 			rc = pci_alloc_msi(sc->dev, &nalloc);
4496 
4497 		if (rc == 0 && nalloc > 0) {
4498 			if (nalloc == iaq->nirq)
4499 				return (0);
4500 
4501 			/*
4502 			 * Didn't get the number requested.  Use whatever number
4503 			 * the kernel is willing to allocate.
4504 			 */
4505 			device_printf(sc->dev, "fewer vectors than requested, "
4506 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4507 			    itype, iaq->nirq, nalloc);
4508 			pci_release_msi(sc->dev);
4509 			navail = nalloc;
4510 			goto restart;
4511 		}
4512 
4513 		device_printf(sc->dev,
4514 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4515 		    itype, rc, iaq->nirq, nalloc);
4516 	}
4517 
4518 	device_printf(sc->dev,
4519 	    "failed to find a usable interrupt type.  "
4520 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4521 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4522 
4523 	return (ENXIO);
4524 }
4525 
4526 #define FW_VERSION(chip) ( \
4527     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4528     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4529     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4530     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4531 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4532 
4533 /* Just enough of fw_hdr to cover all version info. */
4534 struct fw_h {
4535 	__u8	ver;
4536 	__u8	chip;
4537 	__be16	len512;
4538 	__be32	fw_ver;
4539 	__be32	tp_microcode_ver;
4540 	__u8	intfver_nic;
4541 	__u8	intfver_vnic;
4542 	__u8	intfver_ofld;
4543 	__u8	intfver_ri;
4544 	__u8	intfver_iscsipdu;
4545 	__u8	intfver_iscsi;
4546 	__u8	intfver_fcoepdu;
4547 	__u8	intfver_fcoe;
4548 };
4549 /* Spot check a couple of fields. */
4550 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4551 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4552 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4553 
4554 struct fw_info {
4555 	uint8_t chip;
4556 	char *kld_name;
4557 	char *fw_mod_name;
4558 	struct fw_h fw_h;
4559 } fw_info[] = {
4560 	{
4561 		.chip = CHELSIO_T4,
4562 		.kld_name = "t4fw_cfg",
4563 		.fw_mod_name = "t4fw",
4564 		.fw_h = {
4565 			.chip = FW_HDR_CHIP_T4,
4566 			.fw_ver = htobe32(FW_VERSION(T4)),
4567 			.intfver_nic = FW_INTFVER(T4, NIC),
4568 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4569 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4570 			.intfver_ri = FW_INTFVER(T4, RI),
4571 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4572 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4573 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4574 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4575 		},
4576 	}, {
4577 		.chip = CHELSIO_T5,
4578 		.kld_name = "t5fw_cfg",
4579 		.fw_mod_name = "t5fw",
4580 		.fw_h = {
4581 			.chip = FW_HDR_CHIP_T5,
4582 			.fw_ver = htobe32(FW_VERSION(T5)),
4583 			.intfver_nic = FW_INTFVER(T5, NIC),
4584 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4585 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4586 			.intfver_ri = FW_INTFVER(T5, RI),
4587 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4588 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4589 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4590 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4591 		},
4592 	}, {
4593 		.chip = CHELSIO_T6,
4594 		.kld_name = "t6fw_cfg",
4595 		.fw_mod_name = "t6fw",
4596 		.fw_h = {
4597 			.chip = FW_HDR_CHIP_T6,
4598 			.fw_ver = htobe32(FW_VERSION(T6)),
4599 			.intfver_nic = FW_INTFVER(T6, NIC),
4600 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4601 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4602 			.intfver_ri = FW_INTFVER(T6, RI),
4603 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4604 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4605 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4606 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4607 		},
4608 	}
4609 };
4610 
4611 static struct fw_info *
4612 find_fw_info(int chip)
4613 {
4614 	int i;
4615 
4616 	for (i = 0; i < nitems(fw_info); i++) {
4617 		if (fw_info[i].chip == chip)
4618 			return (&fw_info[i]);
4619 	}
4620 	return (NULL);
4621 }
4622 
4623 /*
4624  * Is the given firmware API compatible with the one the driver was compiled
4625  * with?
4626  */
4627 static int
4628 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4629 {
4630 
4631 	/* short circuit if it's the exact same firmware version */
4632 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4633 		return (1);
4634 
4635 	/*
4636 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4637 	 * features that are supported in the driver.
4638 	 */
4639 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4640 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4641 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4642 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4643 		return (1);
4644 #undef SAME_INTF
4645 
4646 	return (0);
4647 }
4648 
4649 static int
4650 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4651     const struct firmware **fw)
4652 {
4653 	struct fw_info *fw_info;
4654 
4655 	*dcfg = NULL;
4656 	if (fw != NULL)
4657 		*fw = NULL;
4658 
4659 	fw_info = find_fw_info(chip_id(sc));
4660 	if (fw_info == NULL) {
4661 		device_printf(sc->dev,
4662 		    "unable to look up firmware information for chip %d.\n",
4663 		    chip_id(sc));
4664 		return (EINVAL);
4665 	}
4666 
4667 	*dcfg = firmware_get(fw_info->kld_name);
4668 	if (*dcfg != NULL) {
4669 		if (fw != NULL)
4670 			*fw = firmware_get(fw_info->fw_mod_name);
4671 		return (0);
4672 	}
4673 
4674 	return (ENOENT);
4675 }
4676 
4677 static void
4678 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4679     const struct firmware *fw)
4680 {
4681 
4682 	if (fw != NULL)
4683 		firmware_put(fw, FIRMWARE_UNLOAD);
4684 	if (dcfg != NULL)
4685 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4686 }
4687 
4688 /*
4689  * Return values:
4690  * 0 means no firmware install attempted.
4691  * ERESTART means a firmware install was attempted and was successful.
4692  * +ve errno means a firmware install was attempted but failed.
4693  */
4694 static int
4695 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4696     const struct fw_h *drv_fw, const char *reason, int *already)
4697 {
4698 	const struct firmware *cfg, *fw;
4699 	const uint32_t c = be32toh(card_fw->fw_ver);
4700 	uint32_t d, k;
4701 	int rc, fw_install;
4702 	struct fw_h bundled_fw;
4703 	bool load_attempted;
4704 
4705 	cfg = fw = NULL;
4706 	load_attempted = false;
4707 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4708 
4709 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4710 	if (t4_fw_install < 0) {
4711 		rc = load_fw_module(sc, &cfg, &fw);
4712 		if (rc != 0 || fw == NULL) {
4713 			device_printf(sc->dev,
4714 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4715 			    " will use compiled-in firmware version for"
4716 			    "hw.cxgbe.fw_install checks.\n",
4717 			    rc, cfg, fw);
4718 		} else {
4719 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4720 		}
4721 		load_attempted = true;
4722 	}
4723 	d = be32toh(bundled_fw.fw_ver);
4724 
4725 	if (reason != NULL)
4726 		goto install;
4727 
4728 	if ((sc->flags & FW_OK) == 0) {
4729 
4730 		if (c == 0xffffffff) {
4731 			reason = "missing";
4732 			goto install;
4733 		}
4734 
4735 		rc = 0;
4736 		goto done;
4737 	}
4738 
4739 	if (!fw_compatible(card_fw, &bundled_fw)) {
4740 		reason = "incompatible or unusable";
4741 		goto install;
4742 	}
4743 
4744 	if (d > c) {
4745 		reason = "older than the version bundled with this driver";
4746 		goto install;
4747 	}
4748 
4749 	if (fw_install == 2 && d != c) {
4750 		reason = "different than the version bundled with this driver";
4751 		goto install;
4752 	}
4753 
4754 	/* No reason to do anything to the firmware already on the card. */
4755 	rc = 0;
4756 	goto done;
4757 
4758 install:
4759 	rc = 0;
4760 	if ((*already)++)
4761 		goto done;
4762 
4763 	if (fw_install == 0) {
4764 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4765 		    "but the driver is prohibited from installing a firmware "
4766 		    "on the card.\n",
4767 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4768 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4769 
4770 		goto done;
4771 	}
4772 
4773 	/*
4774 	 * We'll attempt to install a firmware.  Load the module first (if it
4775 	 * hasn't been loaded already).
4776 	 */
4777 	if (!load_attempted) {
4778 		rc = load_fw_module(sc, &cfg, &fw);
4779 		if (rc != 0 || fw == NULL) {
4780 			device_printf(sc->dev,
4781 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4782 			    rc, cfg, fw);
4783 			/* carry on */
4784 		}
4785 	}
4786 	if (fw == NULL) {
4787 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4788 		    "but the driver cannot take corrective action because it "
4789 		    "is unable to load the firmware module.\n",
4790 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4791 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4792 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4793 		goto done;
4794 	}
4795 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4796 	if (k != d) {
4797 		MPASS(t4_fw_install > 0);
4798 		device_printf(sc->dev,
4799 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4800 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4801 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4802 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4803 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4804 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4805 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4806 		goto done;
4807 	}
4808 
4809 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4810 	    "installing firmware %u.%u.%u.%u on card.\n",
4811 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4812 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4813 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4814 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4815 
4816 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4817 	if (rc != 0) {
4818 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4819 	} else {
4820 		/* Installed successfully, update the cached header too. */
4821 		rc = ERESTART;
4822 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4823 	}
4824 done:
4825 	unload_fw_module(sc, cfg, fw);
4826 
4827 	return (rc);
4828 }
4829 
4830 /*
4831  * Establish contact with the firmware and attempt to become the master driver.
4832  *
4833  * A firmware will be installed to the card if needed (if the driver is allowed
4834  * to do so).
4835  */
4836 static int
4837 contact_firmware(struct adapter *sc)
4838 {
4839 	int rc, already = 0;
4840 	enum dev_state state;
4841 	struct fw_info *fw_info;
4842 	struct fw_hdr *card_fw;		/* fw on the card */
4843 	const struct fw_h *drv_fw;
4844 
4845 	fw_info = find_fw_info(chip_id(sc));
4846 	if (fw_info == NULL) {
4847 		device_printf(sc->dev,
4848 		    "unable to look up firmware information for chip %d.\n",
4849 		    chip_id(sc));
4850 		return (EINVAL);
4851 	}
4852 	drv_fw = &fw_info->fw_h;
4853 
4854 	/* Read the header of the firmware on the card */
4855 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4856 restart:
4857 	rc = -t4_get_fw_hdr(sc, card_fw);
4858 	if (rc != 0) {
4859 		device_printf(sc->dev,
4860 		    "unable to read firmware header from card's flash: %d\n",
4861 		    rc);
4862 		goto done;
4863 	}
4864 
4865 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4866 	    &already);
4867 	if (rc == ERESTART)
4868 		goto restart;
4869 	if (rc != 0)
4870 		goto done;
4871 
4872 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4873 	if (rc < 0 || state == DEV_STATE_ERR) {
4874 		rc = -rc;
4875 		device_printf(sc->dev,
4876 		    "failed to connect to the firmware: %d, %d.  "
4877 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4878 #if 0
4879 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4880 		    "not responding properly to HELLO", &already) == ERESTART)
4881 			goto restart;
4882 #endif
4883 		goto done;
4884 	}
4885 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4886 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4887 
4888 	if (rc == sc->pf) {
4889 		sc->flags |= MASTER_PF;
4890 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4891 		    NULL, &already);
4892 		if (rc == ERESTART)
4893 			rc = 0;
4894 		else if (rc != 0)
4895 			goto done;
4896 	} else if (state == DEV_STATE_UNINIT) {
4897 		/*
4898 		 * We didn't get to be the master so we definitely won't be
4899 		 * configuring the chip.  It's a bug if someone else hasn't
4900 		 * configured it already.
4901 		 */
4902 		device_printf(sc->dev, "couldn't be master(%d), "
4903 		    "device not already initialized either(%d).  "
4904 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4905 		rc = EPROTO;
4906 		goto done;
4907 	} else {
4908 		/*
4909 		 * Some other PF is the master and has configured the chip.
4910 		 * This is allowed but untested.
4911 		 */
4912 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4913 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4914 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4915 		sc->cfcsum = 0;
4916 		rc = 0;
4917 	}
4918 done:
4919 	if (rc != 0 && sc->flags & FW_OK) {
4920 		t4_fw_bye(sc, sc->mbox);
4921 		sc->flags &= ~FW_OK;
4922 	}
4923 	free(card_fw, M_CXGBE);
4924 	return (rc);
4925 }
4926 
4927 static int
4928 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4929     uint32_t mtype, uint32_t moff)
4930 {
4931 	struct fw_info *fw_info;
4932 	const struct firmware *dcfg, *rcfg = NULL;
4933 	const uint32_t *cfdata;
4934 	uint32_t cflen, addr;
4935 	int rc;
4936 
4937 	load_fw_module(sc, &dcfg, NULL);
4938 
4939 	/* Card specific interpretation of "default". */
4940 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4941 		if (pci_get_device(sc->dev) == 0x440a)
4942 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4943 		if (is_fpga(sc))
4944 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4945 	}
4946 
4947 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4948 		if (dcfg == NULL) {
4949 			device_printf(sc->dev,
4950 			    "KLD with default config is not available.\n");
4951 			rc = ENOENT;
4952 			goto done;
4953 		}
4954 		cfdata = dcfg->data;
4955 		cflen = dcfg->datasize & ~3;
4956 	} else {
4957 		char s[32];
4958 
4959 		fw_info = find_fw_info(chip_id(sc));
4960 		if (fw_info == NULL) {
4961 			device_printf(sc->dev,
4962 			    "unable to look up firmware information for chip %d.\n",
4963 			    chip_id(sc));
4964 			rc = EINVAL;
4965 			goto done;
4966 		}
4967 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4968 
4969 		rcfg = firmware_get(s);
4970 		if (rcfg == NULL) {
4971 			device_printf(sc->dev,
4972 			    "unable to load module \"%s\" for configuration "
4973 			    "profile \"%s\".\n", s, cfg_file);
4974 			rc = ENOENT;
4975 			goto done;
4976 		}
4977 		cfdata = rcfg->data;
4978 		cflen = rcfg->datasize & ~3;
4979 	}
4980 
4981 	if (cflen > FLASH_CFG_MAX_SIZE) {
4982 		device_printf(sc->dev,
4983 		    "config file too long (%d, max allowed is %d).\n",
4984 		    cflen, FLASH_CFG_MAX_SIZE);
4985 		rc = EINVAL;
4986 		goto done;
4987 	}
4988 
4989 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4990 	if (rc != 0) {
4991 		device_printf(sc->dev,
4992 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4993 		    __func__, mtype, moff, cflen, rc);
4994 		rc = EINVAL;
4995 		goto done;
4996 	}
4997 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4998 done:
4999 	if (rcfg != NULL)
5000 		firmware_put(rcfg, FIRMWARE_UNLOAD);
5001 	unload_fw_module(sc, dcfg, NULL);
5002 	return (rc);
5003 }
5004 
5005 struct caps_allowed {
5006 	uint16_t nbmcaps;
5007 	uint16_t linkcaps;
5008 	uint16_t switchcaps;
5009 	uint16_t niccaps;
5010 	uint16_t toecaps;
5011 	uint16_t rdmacaps;
5012 	uint16_t cryptocaps;
5013 	uint16_t iscsicaps;
5014 	uint16_t fcoecaps;
5015 };
5016 
5017 #define FW_PARAM_DEV(param) \
5018 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
5019 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
5020 #define FW_PARAM_PFVF(param) \
5021 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
5022 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
5023 
5024 /*
5025  * Provide a configuration profile to the firmware and have it initialize the
5026  * chip accordingly.  This may involve uploading a configuration file to the
5027  * card.
5028  */
5029 static int
5030 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5031     const struct caps_allowed *caps_allowed)
5032 {
5033 	int rc;
5034 	struct fw_caps_config_cmd caps;
5035 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5036 
5037 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5038 	if (rc != 0) {
5039 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5040 		return (rc);
5041 	}
5042 
5043 	bzero(&caps, sizeof(caps));
5044 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5045 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5046 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5047 		mtype = 0;
5048 		moff = 0;
5049 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5050 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5051 		mtype = FW_MEMTYPE_FLASH;
5052 		moff = t4_flash_cfg_addr(sc);
5053 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5054 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5055 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5056 		    FW_LEN16(caps));
5057 	} else {
5058 		/*
5059 		 * Ask the firmware where it wants us to upload the config file.
5060 		 */
5061 		param = FW_PARAM_DEV(CF);
5062 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5063 		if (rc != 0) {
5064 			/* No support for config file?  Shouldn't happen. */
5065 			device_printf(sc->dev,
5066 			    "failed to query config file location: %d.\n", rc);
5067 			goto done;
5068 		}
5069 		mtype = G_FW_PARAMS_PARAM_Y(val);
5070 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5071 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5072 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5073 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5074 		    FW_LEN16(caps));
5075 
5076 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
5077 		if (rc != 0) {
5078 			device_printf(sc->dev,
5079 			    "failed to upload config file to card: %d.\n", rc);
5080 			goto done;
5081 		}
5082 	}
5083 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5084 	if (rc != 0) {
5085 		device_printf(sc->dev, "failed to pre-process config file: %d "
5086 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5087 		goto done;
5088 	}
5089 
5090 	finicsum = be32toh(caps.finicsum);
5091 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5092 	if (finicsum != cfcsum) {
5093 		device_printf(sc->dev,
5094 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5095 		    finicsum, cfcsum);
5096 	}
5097 	sc->cfcsum = cfcsum;
5098 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5099 
5100 	/*
5101 	 * Let the firmware know what features will (not) be used so it can tune
5102 	 * things accordingly.
5103 	 */
5104 #define LIMIT_CAPS(x) do { \
5105 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5106 } while (0)
5107 	LIMIT_CAPS(nbm);
5108 	LIMIT_CAPS(link);
5109 	LIMIT_CAPS(switch);
5110 	LIMIT_CAPS(nic);
5111 	LIMIT_CAPS(toe);
5112 	LIMIT_CAPS(rdma);
5113 	LIMIT_CAPS(crypto);
5114 	LIMIT_CAPS(iscsi);
5115 	LIMIT_CAPS(fcoe);
5116 #undef LIMIT_CAPS
5117 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5118 		/*
5119 		 * TOE and hashfilters are mutually exclusive.  It is a config
5120 		 * file or firmware bug if both are reported as available.  Try
5121 		 * to cope with the situation in non-debug builds by disabling
5122 		 * TOE.
5123 		 */
5124 		MPASS(caps.toecaps == 0);
5125 
5126 		caps.toecaps = 0;
5127 		caps.rdmacaps = 0;
5128 		caps.iscsicaps = 0;
5129 	}
5130 
5131 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5132 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5133 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5134 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5135 	if (rc != 0) {
5136 		device_printf(sc->dev,
5137 		    "failed to process config file: %d.\n", rc);
5138 		goto done;
5139 	}
5140 
5141 	t4_tweak_chip_settings(sc);
5142 	set_params__pre_init(sc);
5143 
5144 	/* get basic stuff going */
5145 	rc = -t4_fw_initialize(sc, sc->mbox);
5146 	if (rc != 0) {
5147 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5148 		goto done;
5149 	}
5150 done:
5151 	return (rc);
5152 }
5153 
5154 /*
5155  * Partition chip resources for use between various PFs, VFs, etc.
5156  */
5157 static int
5158 partition_resources(struct adapter *sc)
5159 {
5160 	char cfg_file[sizeof(t4_cfg_file)];
5161 	struct caps_allowed caps_allowed;
5162 	int rc;
5163 	bool fallback;
5164 
5165 	/* Only the master driver gets to configure the chip resources. */
5166 	MPASS(sc->flags & MASTER_PF);
5167 
5168 #define COPY_CAPS(x) do { \
5169 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5170 } while (0)
5171 	bzero(&caps_allowed, sizeof(caps_allowed));
5172 	COPY_CAPS(nbm);
5173 	COPY_CAPS(link);
5174 	COPY_CAPS(switch);
5175 	COPY_CAPS(nic);
5176 	COPY_CAPS(toe);
5177 	COPY_CAPS(rdma);
5178 	COPY_CAPS(crypto);
5179 	COPY_CAPS(iscsi);
5180 	COPY_CAPS(fcoe);
5181 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5182 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5183 retry:
5184 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5185 	if (rc != 0 && fallback) {
5186 		dump_devlog(sc);
5187 		device_printf(sc->dev,
5188 		    "failed (%d) to configure card with \"%s\" profile, "
5189 		    "will fall back to a basic configuration and retry.\n",
5190 		    rc, cfg_file);
5191 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5192 		bzero(&caps_allowed, sizeof(caps_allowed));
5193 		COPY_CAPS(switch);
5194 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5195 		fallback = false;
5196 		goto retry;
5197 	}
5198 #undef COPY_CAPS
5199 	return (rc);
5200 }
5201 
5202 /*
5203  * Retrieve parameters that are needed (or nice to have) very early.
5204  */
5205 static int
5206 get_params__pre_init(struct adapter *sc)
5207 {
5208 	int rc;
5209 	uint32_t param[2], val[2];
5210 
5211 	t4_get_version_info(sc);
5212 
5213 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5214 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5215 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5216 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5217 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5218 
5219 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5220 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5221 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5222 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5223 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5224 
5225 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5226 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5227 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5228 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5229 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5230 
5231 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5232 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5233 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5234 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5235 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5236 
5237 	param[0] = FW_PARAM_DEV(PORTVEC);
5238 	param[1] = FW_PARAM_DEV(CCLK);
5239 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5240 	if (rc != 0) {
5241 		device_printf(sc->dev,
5242 		    "failed to query parameters (pre_init): %d.\n", rc);
5243 		return (rc);
5244 	}
5245 
5246 	sc->params.portvec = val[0];
5247 	sc->params.nports = bitcount32(val[0]);
5248 	sc->params.vpd.cclk = val[1];
5249 
5250 	/* Read device log parameters. */
5251 	rc = -t4_init_devlog_params(sc, 1);
5252 	if (rc == 0)
5253 		fixup_devlog_params(sc);
5254 	else {
5255 		device_printf(sc->dev,
5256 		    "failed to get devlog parameters: %d.\n", rc);
5257 		rc = 0;	/* devlog isn't critical for device operation */
5258 	}
5259 
5260 	return (rc);
5261 }
5262 
5263 /*
5264  * Any params that need to be set before FW_INITIALIZE.
5265  */
5266 static int
5267 set_params__pre_init(struct adapter *sc)
5268 {
5269 	int rc = 0;
5270 	uint32_t param, val;
5271 
5272 	if (chip_id(sc) >= CHELSIO_T6) {
5273 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5274 		val = 1;
5275 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5276 		/* firmwares < 1.20.1.0 do not have this param. */
5277 		if (rc == FW_EINVAL &&
5278 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5279 			rc = 0;
5280 		}
5281 		if (rc != 0) {
5282 			device_printf(sc->dev,
5283 			    "failed to enable high priority filters :%d.\n",
5284 			    rc);
5285 		}
5286 
5287 		param = FW_PARAM_DEV(PPOD_EDRAM);
5288 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5289 		if (rc == 0 && val == 1) {
5290 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5291 			    &val);
5292 			if (rc != 0) {
5293 				device_printf(sc->dev,
5294 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5295 			}
5296 		}
5297 	}
5298 
5299 	/* Enable opaque VIIDs with firmwares that support it. */
5300 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5301 	val = 1;
5302 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5303 	if (rc == 0 && val == 1)
5304 		sc->params.viid_smt_extn_support = true;
5305 	else
5306 		sc->params.viid_smt_extn_support = false;
5307 
5308 	return (rc);
5309 }
5310 
5311 /*
5312  * Retrieve various parameters that are of interest to the driver.  The device
5313  * has been initialized by the firmware at this point.
5314  */
5315 static int
5316 get_params__post_init(struct adapter *sc)
5317 {
5318 	int rc;
5319 	uint32_t param[7], val[7];
5320 	struct fw_caps_config_cmd caps;
5321 
5322 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5323 	param[1] = FW_PARAM_PFVF(EQ_START);
5324 	param[2] = FW_PARAM_PFVF(FILTER_START);
5325 	param[3] = FW_PARAM_PFVF(FILTER_END);
5326 	param[4] = FW_PARAM_PFVF(L2T_START);
5327 	param[5] = FW_PARAM_PFVF(L2T_END);
5328 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5329 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5330 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5331 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5332 	if (rc != 0) {
5333 		device_printf(sc->dev,
5334 		    "failed to query parameters (post_init): %d.\n", rc);
5335 		return (rc);
5336 	}
5337 
5338 	sc->sge.iq_start = val[0];
5339 	sc->sge.eq_start = val[1];
5340 	if ((int)val[3] > (int)val[2]) {
5341 		sc->tids.ftid_base = val[2];
5342 		sc->tids.ftid_end = val[3];
5343 		sc->tids.nftids = val[3] - val[2] + 1;
5344 	}
5345 	sc->vres.l2t.start = val[4];
5346 	sc->vres.l2t.size = val[5] - val[4] + 1;
5347 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5348 	if (sc->vres.l2t.size > 0)
5349 		MPASS(fls(val[5]) <= S_SYNC_WR);
5350 	sc->params.core_vdd = val[6];
5351 
5352 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5353 	param[1] = FW_PARAM_PFVF(EQ_END);
5354 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5355 	if (rc != 0) {
5356 		device_printf(sc->dev,
5357 		    "failed to query parameters (post_init2): %d.\n", rc);
5358 		return (rc);
5359 	}
5360 	MPASS((int)val[0] >= sc->sge.iq_start);
5361 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5362 	MPASS((int)val[1] >= sc->sge.eq_start);
5363 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5364 
5365 	if (chip_id(sc) >= CHELSIO_T6) {
5366 
5367 		sc->tids.tid_base = t4_read_reg(sc,
5368 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5369 
5370 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5371 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5372 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5373 		if (rc != 0) {
5374 			device_printf(sc->dev,
5375 			   "failed to query hpfilter parameters: %d.\n", rc);
5376 			return (rc);
5377 		}
5378 		if ((int)val[1] > (int)val[0]) {
5379 			sc->tids.hpftid_base = val[0];
5380 			sc->tids.hpftid_end = val[1];
5381 			sc->tids.nhpftids = val[1] - val[0] + 1;
5382 
5383 			/*
5384 			 * These should go off if the layout changes and the
5385 			 * driver needs to catch up.
5386 			 */
5387 			MPASS(sc->tids.hpftid_base == 0);
5388 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5389 		}
5390 
5391 		param[0] = FW_PARAM_PFVF(RAWF_START);
5392 		param[1] = FW_PARAM_PFVF(RAWF_END);
5393 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5394 		if (rc != 0) {
5395 			device_printf(sc->dev,
5396 			   "failed to query rawf parameters: %d.\n", rc);
5397 			return (rc);
5398 		}
5399 		if ((int)val[1] > (int)val[0]) {
5400 			sc->rawf_base = val[0];
5401 			sc->nrawf = val[1] - val[0] + 1;
5402 		}
5403 	}
5404 
5405 	/*
5406 	 * The parameters that follow may not be available on all firmwares.  We
5407 	 * query them individually rather than in a compound query because old
5408 	 * firmwares fail the entire query if an unknown parameter is queried.
5409 	 */
5410 
5411 	/*
5412 	 * MPS buffer group configuration.
5413 	 */
5414 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5415 	val[0] = 0;
5416 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5417 	if (rc == 0)
5418 		sc->params.mps_bg_map = val[0];
5419 	else
5420 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5421 
5422 	param[0] = FW_PARAM_DEV(TPCHMAP);
5423 	val[0] = 0;
5424 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5425 	if (rc == 0)
5426 		sc->params.tp_ch_map = val[0];
5427 	else
5428 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5429 
5430 	/*
5431 	 * Determine whether the firmware supports the filter2 work request.
5432 	 */
5433 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5434 	val[0] = 0;
5435 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5436 	if (rc == 0)
5437 		sc->params.filter2_wr_support = val[0] != 0;
5438 	else
5439 		sc->params.filter2_wr_support = 0;
5440 
5441 	/*
5442 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5443 	 */
5444 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5445 	val[0] = 0;
5446 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5447 	if (rc == 0)
5448 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5449 	else
5450 		sc->params.ulptx_memwrite_dsgl = false;
5451 
5452 	/* FW_RI_FR_NSMR_TPTE_WR support */
5453 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5454 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5455 	if (rc == 0)
5456 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5457 	else
5458 		sc->params.fr_nsmr_tpte_wr_support = false;
5459 
5460 	/* Support for 512 SGL entries per FR MR. */
5461 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5462 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5463 	if (rc == 0)
5464 		sc->params.dev_512sgl_mr = val[0] != 0;
5465 	else
5466 		sc->params.dev_512sgl_mr = false;
5467 
5468 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5469 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5470 	if (rc == 0)
5471 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5472 	else
5473 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5474 
5475 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5476 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5477 	if (rc == 0) {
5478 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5479 		sc->params.nsched_cls = val[0];
5480 	} else
5481 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5482 
5483 	/* get capabilites */
5484 	bzero(&caps, sizeof(caps));
5485 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5486 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5487 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5488 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5489 	if (rc != 0) {
5490 		device_printf(sc->dev,
5491 		    "failed to get card capabilities: %d.\n", rc);
5492 		return (rc);
5493 	}
5494 
5495 #define READ_CAPS(x) do { \
5496 	sc->x = htobe16(caps.x); \
5497 } while (0)
5498 	READ_CAPS(nbmcaps);
5499 	READ_CAPS(linkcaps);
5500 	READ_CAPS(switchcaps);
5501 	READ_CAPS(niccaps);
5502 	READ_CAPS(toecaps);
5503 	READ_CAPS(rdmacaps);
5504 	READ_CAPS(cryptocaps);
5505 	READ_CAPS(iscsicaps);
5506 	READ_CAPS(fcoecaps);
5507 
5508 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5509 		MPASS(chip_id(sc) > CHELSIO_T4);
5510 		MPASS(sc->toecaps == 0);
5511 		sc->toecaps = 0;
5512 
5513 		param[0] = FW_PARAM_DEV(NTID);
5514 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5515 		if (rc != 0) {
5516 			device_printf(sc->dev,
5517 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5518 			return (rc);
5519 		}
5520 		sc->tids.ntids = val[0];
5521 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5522 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5523 			sc->tids.ntids -= sc->tids.nhpftids;
5524 		}
5525 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5526 		sc->params.hash_filter = 1;
5527 	}
5528 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5529 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5530 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5531 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5532 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5533 		if (rc != 0) {
5534 			device_printf(sc->dev,
5535 			    "failed to query NIC parameters: %d.\n", rc);
5536 			return (rc);
5537 		}
5538 		if ((int)val[1] > (int)val[0]) {
5539 			sc->tids.etid_base = val[0];
5540 			sc->tids.etid_end = val[1];
5541 			sc->tids.netids = val[1] - val[0] + 1;
5542 			sc->params.eo_wr_cred = val[2];
5543 			sc->params.ethoffload = 1;
5544 		}
5545 	}
5546 	if (sc->toecaps) {
5547 		/* query offload-related parameters */
5548 		param[0] = FW_PARAM_DEV(NTID);
5549 		param[1] = FW_PARAM_PFVF(SERVER_START);
5550 		param[2] = FW_PARAM_PFVF(SERVER_END);
5551 		param[3] = FW_PARAM_PFVF(TDDP_START);
5552 		param[4] = FW_PARAM_PFVF(TDDP_END);
5553 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5554 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5555 		if (rc != 0) {
5556 			device_printf(sc->dev,
5557 			    "failed to query TOE parameters: %d.\n", rc);
5558 			return (rc);
5559 		}
5560 		sc->tids.ntids = val[0];
5561 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5562 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5563 			sc->tids.ntids -= sc->tids.nhpftids;
5564 		}
5565 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5566 		if ((int)val[2] > (int)val[1]) {
5567 			sc->tids.stid_base = val[1];
5568 			sc->tids.nstids = val[2] - val[1] + 1;
5569 		}
5570 		sc->vres.ddp.start = val[3];
5571 		sc->vres.ddp.size = val[4] - val[3] + 1;
5572 		sc->params.ofldq_wr_cred = val[5];
5573 		sc->params.offload = 1;
5574 	} else {
5575 		/*
5576 		 * The firmware attempts memfree TOE configuration for -SO cards
5577 		 * and will report toecaps=0 if it runs out of resources (this
5578 		 * depends on the config file).  It may not report 0 for other
5579 		 * capabilities dependent on the TOE in this case.  Set them to
5580 		 * 0 here so that the driver doesn't bother tracking resources
5581 		 * that will never be used.
5582 		 */
5583 		sc->iscsicaps = 0;
5584 		sc->rdmacaps = 0;
5585 	}
5586 	if (sc->rdmacaps) {
5587 		param[0] = FW_PARAM_PFVF(STAG_START);
5588 		param[1] = FW_PARAM_PFVF(STAG_END);
5589 		param[2] = FW_PARAM_PFVF(RQ_START);
5590 		param[3] = FW_PARAM_PFVF(RQ_END);
5591 		param[4] = FW_PARAM_PFVF(PBL_START);
5592 		param[5] = FW_PARAM_PFVF(PBL_END);
5593 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5594 		if (rc != 0) {
5595 			device_printf(sc->dev,
5596 			    "failed to query RDMA parameters(1): %d.\n", rc);
5597 			return (rc);
5598 		}
5599 		sc->vres.stag.start = val[0];
5600 		sc->vres.stag.size = val[1] - val[0] + 1;
5601 		sc->vres.rq.start = val[2];
5602 		sc->vres.rq.size = val[3] - val[2] + 1;
5603 		sc->vres.pbl.start = val[4];
5604 		sc->vres.pbl.size = val[5] - val[4] + 1;
5605 
5606 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5607 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5608 		param[2] = FW_PARAM_PFVF(CQ_START);
5609 		param[3] = FW_PARAM_PFVF(CQ_END);
5610 		param[4] = FW_PARAM_PFVF(OCQ_START);
5611 		param[5] = FW_PARAM_PFVF(OCQ_END);
5612 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5613 		if (rc != 0) {
5614 			device_printf(sc->dev,
5615 			    "failed to query RDMA parameters(2): %d.\n", rc);
5616 			return (rc);
5617 		}
5618 		sc->vres.qp.start = val[0];
5619 		sc->vres.qp.size = val[1] - val[0] + 1;
5620 		sc->vres.cq.start = val[2];
5621 		sc->vres.cq.size = val[3] - val[2] + 1;
5622 		sc->vres.ocq.start = val[4];
5623 		sc->vres.ocq.size = val[5] - val[4] + 1;
5624 
5625 		param[0] = FW_PARAM_PFVF(SRQ_START);
5626 		param[1] = FW_PARAM_PFVF(SRQ_END);
5627 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5628 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5629 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5630 		if (rc != 0) {
5631 			device_printf(sc->dev,
5632 			    "failed to query RDMA parameters(3): %d.\n", rc);
5633 			return (rc);
5634 		}
5635 		sc->vres.srq.start = val[0];
5636 		sc->vres.srq.size = val[1] - val[0] + 1;
5637 		sc->params.max_ordird_qp = val[2];
5638 		sc->params.max_ird_adapter = val[3];
5639 	}
5640 	if (sc->iscsicaps) {
5641 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5642 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5643 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5644 		if (rc != 0) {
5645 			device_printf(sc->dev,
5646 			    "failed to query iSCSI parameters: %d.\n", rc);
5647 			return (rc);
5648 		}
5649 		sc->vres.iscsi.start = val[0];
5650 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5651 	}
5652 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5653 		param[0] = FW_PARAM_PFVF(TLS_START);
5654 		param[1] = FW_PARAM_PFVF(TLS_END);
5655 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5656 		if (rc != 0) {
5657 			device_printf(sc->dev,
5658 			    "failed to query TLS parameters: %d.\n", rc);
5659 			return (rc);
5660 		}
5661 		sc->vres.key.start = val[0];
5662 		sc->vres.key.size = val[1] - val[0] + 1;
5663 	}
5664 
5665 	/*
5666 	 * We've got the params we wanted to query directly from the firmware.
5667 	 * Grab some others via other means.
5668 	 */
5669 	t4_init_sge_params(sc);
5670 	t4_init_tp_params(sc);
5671 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5672 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5673 
5674 	rc = t4_verify_chip_settings(sc);
5675 	if (rc != 0)
5676 		return (rc);
5677 	t4_init_rx_buf_info(sc);
5678 
5679 	return (rc);
5680 }
5681 
5682 #ifdef KERN_TLS
5683 static void
5684 ktls_tick(void *arg)
5685 {
5686 	struct adapter *sc;
5687 	uint32_t tstamp;
5688 
5689 	sc = arg;
5690 	tstamp = tcp_ts_getticks();
5691 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5692 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5693 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5694 }
5695 
5696 static int
5697 t6_config_kern_tls(struct adapter *sc, bool enable)
5698 {
5699 	int rc;
5700 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5701 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5702 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5703 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5704 
5705 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5706 	if (rc != 0) {
5707 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5708 		    enable ?  "enable" : "disable", rc);
5709 		return (rc);
5710 	}
5711 
5712 	if (enable) {
5713 		sc->flags |= KERN_TLS_ON;
5714 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5715 		    C_HARDCLOCK);
5716 	} else {
5717 		sc->flags &= ~KERN_TLS_ON;
5718 		callout_stop(&sc->ktls_tick);
5719 	}
5720 
5721 	return (rc);
5722 }
5723 #endif
5724 
5725 static int
5726 set_params__post_init(struct adapter *sc)
5727 {
5728 	uint32_t mask, param, val;
5729 #ifdef TCP_OFFLOAD
5730 	int i, v, shift;
5731 #endif
5732 
5733 	/* ask for encapsulated CPLs */
5734 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5735 	val = 1;
5736 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5737 
5738 	/* Enable 32b port caps if the firmware supports it. */
5739 	param = FW_PARAM_PFVF(PORT_CAPS32);
5740 	val = 1;
5741 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5742 		sc->params.port_caps32 = 1;
5743 
5744 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5745 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5746 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5747 	    V_MASKFILTER(val - 1));
5748 
5749 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5750 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5751 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5752 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5753 	val = 0;
5754 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5755 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5756 		    F_ATTACKFILTERENABLE);
5757 		val |= F_DROPERRORATTACK;
5758 	}
5759 	if (t4_drop_ip_fragments != 0) {
5760 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5761 		    F_FRAGMENTDROP);
5762 		val |= F_DROPERRORFRAG;
5763 	}
5764 	if (t4_drop_pkts_with_l2_errors != 0)
5765 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5766 	if (t4_drop_pkts_with_l3_errors != 0) {
5767 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5768 		    F_DROPERRORCSUMIP;
5769 	}
5770 	if (t4_drop_pkts_with_l4_errors != 0) {
5771 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5772 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5773 	}
5774 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5775 
5776 #ifdef TCP_OFFLOAD
5777 	/*
5778 	 * Override the TOE timers with user provided tunables.  This is not the
5779 	 * recommended way to change the timers (the firmware config file is) so
5780 	 * these tunables are not documented.
5781 	 *
5782 	 * All the timer tunables are in microseconds.
5783 	 */
5784 	if (t4_toe_keepalive_idle != 0) {
5785 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5786 		v &= M_KEEPALIVEIDLE;
5787 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5788 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5789 	}
5790 	if (t4_toe_keepalive_interval != 0) {
5791 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5792 		v &= M_KEEPALIVEINTVL;
5793 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5794 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5795 	}
5796 	if (t4_toe_keepalive_count != 0) {
5797 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5798 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5799 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5800 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5801 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5802 	}
5803 	if (t4_toe_rexmt_min != 0) {
5804 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5805 		v &= M_RXTMIN;
5806 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5807 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5808 	}
5809 	if (t4_toe_rexmt_max != 0) {
5810 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5811 		v &= M_RXTMAX;
5812 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5813 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5814 	}
5815 	if (t4_toe_rexmt_count != 0) {
5816 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5817 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5818 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5819 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5820 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5821 	}
5822 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5823 		if (t4_toe_rexmt_backoff[i] != -1) {
5824 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5825 			shift = (i & 3) << 3;
5826 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5827 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5828 		}
5829 	}
5830 #endif
5831 
5832 	/*
5833 	 * Limit TOE connections to 2 reassembly "islands".  This is
5834 	 * required to permit migrating TOE connections to either
5835 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5836 	 */
5837 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5838 	    V_PASSMODE(2));
5839 
5840 #ifdef KERN_TLS
5841 	if (is_ktls(sc)) {
5842 		sc->tlst.inline_keys = t4_tls_inline_keys;
5843 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5844 		if (t4_kern_tls != 0 && is_t6(sc))
5845 			t6_config_kern_tls(sc, true);
5846 	}
5847 #endif
5848 	return (0);
5849 }
5850 
5851 #undef FW_PARAM_PFVF
5852 #undef FW_PARAM_DEV
5853 
5854 static void
5855 t4_set_desc(struct adapter *sc)
5856 {
5857 	struct adapter_params *p = &sc->params;
5858 
5859 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5860 }
5861 
5862 static inline void
5863 ifmedia_add4(struct ifmedia *ifm, int m)
5864 {
5865 
5866 	ifmedia_add(ifm, m, 0, NULL);
5867 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5868 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5869 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5870 }
5871 
5872 /*
5873  * This is the selected media, which is not quite the same as the active media.
5874  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5875  * and active are not the same, and "media: Ethernet selected" otherwise.
5876  */
5877 static void
5878 set_current_media(struct port_info *pi)
5879 {
5880 	struct link_config *lc;
5881 	struct ifmedia *ifm;
5882 	int mword;
5883 	u_int speed;
5884 
5885 	PORT_LOCK_ASSERT_OWNED(pi);
5886 
5887 	/* Leave current media alone if it's already set to IFM_NONE. */
5888 	ifm = &pi->media;
5889 	if (ifm->ifm_cur != NULL &&
5890 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5891 		return;
5892 
5893 	lc = &pi->link_cfg;
5894 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5895 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5896 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5897 		return;
5898 	}
5899 	mword = IFM_ETHER | IFM_FDX;
5900 	if (lc->requested_fc & PAUSE_TX)
5901 		mword |= IFM_ETH_TXPAUSE;
5902 	if (lc->requested_fc & PAUSE_RX)
5903 		mword |= IFM_ETH_RXPAUSE;
5904 	if (lc->requested_speed == 0)
5905 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5906 	else
5907 		speed = lc->requested_speed;
5908 	mword |= port_mword(pi, speed_to_fwcap(speed));
5909 	ifmedia_set(ifm, mword);
5910 }
5911 
5912 /*
5913  * Returns true if the ifmedia list for the port cannot change.
5914  */
5915 static bool
5916 fixed_ifmedia(struct port_info *pi)
5917 {
5918 
5919 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5920 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5921 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5922 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5923 	    pi->port_type == FW_PORT_TYPE_KX ||
5924 	    pi->port_type == FW_PORT_TYPE_KR ||
5925 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5926 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5927 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5928 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5929 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5930 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5931 }
5932 
5933 static void
5934 build_medialist(struct port_info *pi)
5935 {
5936 	uint32_t ss, speed;
5937 	int unknown, mword, bit;
5938 	struct link_config *lc;
5939 	struct ifmedia *ifm;
5940 
5941 	PORT_LOCK_ASSERT_OWNED(pi);
5942 
5943 	if (pi->flags & FIXED_IFMEDIA)
5944 		return;
5945 
5946 	/*
5947 	 * Rebuild the ifmedia list.
5948 	 */
5949 	ifm = &pi->media;
5950 	ifmedia_removeall(ifm);
5951 	lc = &pi->link_cfg;
5952 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5953 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5954 		MPASS(ss != 0);
5955 no_media:
5956 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5957 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5958 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5959 		return;
5960 	}
5961 
5962 	unknown = 0;
5963 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5964 		speed = 1 << bit;
5965 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5966 		if (ss & speed) {
5967 			mword = port_mword(pi, speed);
5968 			if (mword == IFM_NONE) {
5969 				goto no_media;
5970 			} else if (mword == IFM_UNKNOWN)
5971 				unknown++;
5972 			else
5973 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5974 		}
5975 	}
5976 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5977 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5978 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5979 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5980 
5981 	set_current_media(pi);
5982 }
5983 
5984 /*
5985  * Initialize the requested fields in the link config based on driver tunables.
5986  */
5987 static void
5988 init_link_config(struct port_info *pi)
5989 {
5990 	struct link_config *lc = &pi->link_cfg;
5991 
5992 	PORT_LOCK_ASSERT_OWNED(pi);
5993 
5994 	lc->requested_caps = 0;
5995 	lc->requested_speed = 0;
5996 
5997 	if (t4_autoneg == 0)
5998 		lc->requested_aneg = AUTONEG_DISABLE;
5999 	else if (t4_autoneg == 1)
6000 		lc->requested_aneg = AUTONEG_ENABLE;
6001 	else
6002 		lc->requested_aneg = AUTONEG_AUTO;
6003 
6004 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
6005 	    PAUSE_AUTONEG);
6006 
6007 	if (t4_fec & FEC_AUTO)
6008 		lc->requested_fec = FEC_AUTO;
6009 	else if (t4_fec == 0)
6010 		lc->requested_fec = FEC_NONE;
6011 	else {
6012 		/* -1 is handled by the FEC_AUTO block above and not here. */
6013 		lc->requested_fec = t4_fec &
6014 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
6015 		if (lc->requested_fec == 0)
6016 			lc->requested_fec = FEC_AUTO;
6017 	}
6018 	if (t4_force_fec < 0)
6019 		lc->force_fec = -1;
6020 	else if (t4_force_fec > 0)
6021 		lc->force_fec = 1;
6022 	else
6023 		lc->force_fec = 0;
6024 }
6025 
6026 /*
6027  * Makes sure that all requested settings comply with what's supported by the
6028  * port.  Returns the number of settings that were invalid and had to be fixed.
6029  */
6030 static int
6031 fixup_link_config(struct port_info *pi)
6032 {
6033 	int n = 0;
6034 	struct link_config *lc = &pi->link_cfg;
6035 	uint32_t fwspeed;
6036 
6037 	PORT_LOCK_ASSERT_OWNED(pi);
6038 
6039 	/* Speed (when not autonegotiating) */
6040 	if (lc->requested_speed != 0) {
6041 		fwspeed = speed_to_fwcap(lc->requested_speed);
6042 		if ((fwspeed & lc->pcaps) == 0) {
6043 			n++;
6044 			lc->requested_speed = 0;
6045 		}
6046 	}
6047 
6048 	/* Link autonegotiation */
6049 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6050 	    lc->requested_aneg == AUTONEG_DISABLE ||
6051 	    lc->requested_aneg == AUTONEG_AUTO);
6052 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6053 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6054 		n++;
6055 		lc->requested_aneg = AUTONEG_AUTO;
6056 	}
6057 
6058 	/* Flow control */
6059 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6060 	if (lc->requested_fc & PAUSE_TX &&
6061 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6062 		n++;
6063 		lc->requested_fc &= ~PAUSE_TX;
6064 	}
6065 	if (lc->requested_fc & PAUSE_RX &&
6066 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6067 		n++;
6068 		lc->requested_fc &= ~PAUSE_RX;
6069 	}
6070 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6071 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6072 		n++;
6073 		lc->requested_fc |= PAUSE_AUTONEG;
6074 	}
6075 
6076 	/* FEC */
6077 	if ((lc->requested_fec & FEC_RS &&
6078 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6079 	    (lc->requested_fec & FEC_BASER_RS &&
6080 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6081 		n++;
6082 		lc->requested_fec = FEC_AUTO;
6083 	}
6084 
6085 	return (n);
6086 }
6087 
6088 /*
6089  * Apply the requested L1 settings, which are expected to be valid, to the
6090  * hardware.
6091  */
6092 static int
6093 apply_link_config(struct port_info *pi)
6094 {
6095 	struct adapter *sc = pi->adapter;
6096 	struct link_config *lc = &pi->link_cfg;
6097 	int rc;
6098 
6099 #ifdef INVARIANTS
6100 	ASSERT_SYNCHRONIZED_OP(sc);
6101 	PORT_LOCK_ASSERT_OWNED(pi);
6102 
6103 	if (lc->requested_aneg == AUTONEG_ENABLE)
6104 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6105 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6106 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6107 	if (lc->requested_fc & PAUSE_TX)
6108 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6109 	if (lc->requested_fc & PAUSE_RX)
6110 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6111 	if (lc->requested_fec & FEC_RS)
6112 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6113 	if (lc->requested_fec & FEC_BASER_RS)
6114 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6115 #endif
6116 	if (!(sc->flags & IS_VF)) {
6117 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6118 		if (rc != 0) {
6119 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6120 			return (rc);
6121 		}
6122 	}
6123 
6124 	/*
6125 	 * An L1_CFG will almost always result in a link-change event if the
6126 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6127 	 * the notification is processed.  If the link is down then the actual
6128 	 * settings are meaningless.
6129 	 *
6130 	 * This takes care of the case where a change in the L1 settings may not
6131 	 * result in a notification.
6132 	 */
6133 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6134 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6135 
6136 	return (0);
6137 }
6138 
6139 #define FW_MAC_EXACT_CHUNK	7
6140 struct mcaddr_ctx {
6141 	if_t ifp;
6142 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6143 	uint64_t hash;
6144 	int i;
6145 	int del;
6146 	int rc;
6147 };
6148 
6149 static u_int
6150 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6151 {
6152 	struct mcaddr_ctx *ctx = arg;
6153 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6154 	struct port_info *pi = vi->pi;
6155 	struct adapter *sc = pi->adapter;
6156 
6157 	if (ctx->rc < 0)
6158 		return (0);
6159 
6160 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6161 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6162 	ctx->i++;
6163 
6164 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6165 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6166 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6167 		if (ctx->rc < 0) {
6168 			int j;
6169 
6170 			for (j = 0; j < ctx->i; j++) {
6171 				if_printf(ctx->ifp,
6172 				    "failed to add mc address"
6173 				    " %02x:%02x:%02x:"
6174 				    "%02x:%02x:%02x rc=%d\n",
6175 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6176 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6177 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6178 				    -ctx->rc);
6179 			}
6180 			return (0);
6181 		}
6182 		ctx->del = 0;
6183 		ctx->i = 0;
6184 	}
6185 
6186 	return (1);
6187 }
6188 
6189 /*
6190  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6191  * indicates which parameters should be programmed (the rest are left alone).
6192  */
6193 int
6194 update_mac_settings(if_t ifp, int flags)
6195 {
6196 	int rc = 0;
6197 	struct vi_info *vi = if_getsoftc(ifp);
6198 	struct port_info *pi = vi->pi;
6199 	struct adapter *sc = pi->adapter;
6200 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6201 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6202 
6203 	ASSERT_SYNCHRONIZED_OP(sc);
6204 	KASSERT(flags, ("%s: not told what to update.", __func__));
6205 
6206 	if (flags & XGMAC_MTU)
6207 		mtu = if_getmtu(ifp);
6208 
6209 	if (flags & XGMAC_PROMISC)
6210 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6211 
6212 	if (flags & XGMAC_ALLMULTI)
6213 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6214 
6215 	if (flags & XGMAC_VLANEX)
6216 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6217 
6218 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6219 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6220 		    allmulti, 1, vlanex, false);
6221 		if (rc) {
6222 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6223 			    rc);
6224 			return (rc);
6225 		}
6226 	}
6227 
6228 	if (flags & XGMAC_UCADDR) {
6229 		uint8_t ucaddr[ETHER_ADDR_LEN];
6230 
6231 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6232 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6233 		    ucaddr, true, &vi->smt_idx);
6234 		if (rc < 0) {
6235 			rc = -rc;
6236 			if_printf(ifp, "change_mac failed: %d\n", rc);
6237 			return (rc);
6238 		} else {
6239 			vi->xact_addr_filt = rc;
6240 			rc = 0;
6241 		}
6242 	}
6243 
6244 	if (flags & XGMAC_MCADDRS) {
6245 		struct epoch_tracker et;
6246 		struct mcaddr_ctx ctx;
6247 		int j;
6248 
6249 		ctx.ifp = ifp;
6250 		ctx.hash = 0;
6251 		ctx.i = 0;
6252 		ctx.del = 1;
6253 		ctx.rc = 0;
6254 		/*
6255 		 * Unlike other drivers, we accumulate list of pointers into
6256 		 * interface address lists and we need to keep it safe even
6257 		 * after if_foreach_llmaddr() returns, thus we must enter the
6258 		 * network epoch.
6259 		 */
6260 		NET_EPOCH_ENTER(et);
6261 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6262 		if (ctx.rc < 0) {
6263 			NET_EPOCH_EXIT(et);
6264 			rc = -ctx.rc;
6265 			return (rc);
6266 		}
6267 		if (ctx.i > 0) {
6268 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6269 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6270 			NET_EPOCH_EXIT(et);
6271 			if (rc < 0) {
6272 				rc = -rc;
6273 				for (j = 0; j < ctx.i; j++) {
6274 					if_printf(ifp,
6275 					    "failed to add mcast address"
6276 					    " %02x:%02x:%02x:"
6277 					    "%02x:%02x:%02x rc=%d\n",
6278 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6279 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6280 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6281 					    rc);
6282 				}
6283 				return (rc);
6284 			}
6285 			ctx.del = 0;
6286 		} else
6287 			NET_EPOCH_EXIT(et);
6288 
6289 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6290 		if (rc != 0)
6291 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6292 			    rc);
6293 		if (ctx.del == 0) {
6294 			/* We clobbered the VXLAN entry if there was one. */
6295 			pi->vxlan_tcam_entry = false;
6296 		}
6297 	}
6298 
6299 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6300 	    pi->vxlan_tcam_entry == false) {
6301 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6302 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6303 		    true);
6304 		if (rc < 0) {
6305 			rc = -rc;
6306 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6307 			    rc);
6308 		} else {
6309 			MPASS(rc == sc->rawf_base + pi->port_id);
6310 			rc = 0;
6311 			pi->vxlan_tcam_entry = true;
6312 		}
6313 	}
6314 
6315 	return (rc);
6316 }
6317 
6318 /*
6319  * {begin|end}_synchronized_op must be called from the same thread.
6320  */
6321 int
6322 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6323     char *wmesg)
6324 {
6325 	int rc, pri;
6326 
6327 #ifdef WITNESS
6328 	/* the caller thinks it's ok to sleep, but is it really? */
6329 	if (flags & SLEEP_OK)
6330 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6331 		    "begin_synchronized_op");
6332 #endif
6333 
6334 	if (INTR_OK)
6335 		pri = PCATCH;
6336 	else
6337 		pri = 0;
6338 
6339 	ADAPTER_LOCK(sc);
6340 	for (;;) {
6341 
6342 		if (vi && IS_DETACHING(vi)) {
6343 			rc = ENXIO;
6344 			goto done;
6345 		}
6346 
6347 		if (!IS_BUSY(sc)) {
6348 			rc = 0;
6349 			break;
6350 		}
6351 
6352 		if (!(flags & SLEEP_OK)) {
6353 			rc = EBUSY;
6354 			goto done;
6355 		}
6356 
6357 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6358 			rc = EINTR;
6359 			goto done;
6360 		}
6361 	}
6362 
6363 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6364 	SET_BUSY(sc);
6365 #ifdef INVARIANTS
6366 	sc->last_op = wmesg;
6367 	sc->last_op_thr = curthread;
6368 	sc->last_op_flags = flags;
6369 #endif
6370 
6371 done:
6372 	if (!(flags & HOLD_LOCK) || rc)
6373 		ADAPTER_UNLOCK(sc);
6374 
6375 	return (rc);
6376 }
6377 
6378 /*
6379  * Tell if_ioctl and if_init that the VI is going away.  This is
6380  * special variant of begin_synchronized_op and must be paired with a
6381  * call to end_vi_detach.
6382  */
6383 void
6384 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6385 {
6386 	ADAPTER_LOCK(sc);
6387 	SET_DETACHING(vi);
6388 	wakeup(&sc->flags);
6389 	while (IS_BUSY(sc))
6390 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6391 	SET_BUSY(sc);
6392 #ifdef INVARIANTS
6393 	sc->last_op = "t4detach";
6394 	sc->last_op_thr = curthread;
6395 	sc->last_op_flags = 0;
6396 #endif
6397 	ADAPTER_UNLOCK(sc);
6398 }
6399 
6400 void
6401 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6402 {
6403 	ADAPTER_LOCK(sc);
6404 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6405 	CLR_BUSY(sc);
6406 	CLR_DETACHING(vi);
6407 	wakeup(&sc->flags);
6408 	ADAPTER_UNLOCK(sc);
6409 }
6410 
6411 /*
6412  * {begin|end}_synchronized_op must be called from the same thread.
6413  */
6414 void
6415 end_synchronized_op(struct adapter *sc, int flags)
6416 {
6417 
6418 	if (flags & LOCK_HELD)
6419 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6420 	else
6421 		ADAPTER_LOCK(sc);
6422 
6423 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6424 	CLR_BUSY(sc);
6425 	wakeup(&sc->flags);
6426 	ADAPTER_UNLOCK(sc);
6427 }
6428 
6429 static int
6430 cxgbe_init_synchronized(struct vi_info *vi)
6431 {
6432 	struct port_info *pi = vi->pi;
6433 	struct adapter *sc = pi->adapter;
6434 	if_t ifp = vi->ifp;
6435 	int rc = 0, i;
6436 	struct sge_txq *txq;
6437 
6438 	ASSERT_SYNCHRONIZED_OP(sc);
6439 
6440 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6441 		return (0);	/* already running */
6442 
6443 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6444 		return (rc);	/* error message displayed already */
6445 
6446 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6447 		return (rc); /* error message displayed already */
6448 
6449 	rc = update_mac_settings(ifp, XGMAC_ALL);
6450 	if (rc)
6451 		goto done;	/* error message displayed already */
6452 
6453 	PORT_LOCK(pi);
6454 	if (pi->up_vis == 0) {
6455 		t4_update_port_info(pi);
6456 		fixup_link_config(pi);
6457 		build_medialist(pi);
6458 		apply_link_config(pi);
6459 	}
6460 
6461 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6462 	if (rc != 0) {
6463 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6464 		PORT_UNLOCK(pi);
6465 		goto done;
6466 	}
6467 
6468 	/*
6469 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6470 	 * if this changes.
6471 	 */
6472 
6473 	for_each_txq(vi, i, txq) {
6474 		TXQ_LOCK(txq);
6475 		txq->eq.flags |= EQ_ENABLED;
6476 		TXQ_UNLOCK(txq);
6477 	}
6478 
6479 	/*
6480 	 * The first iq of the first port to come up is used for tracing.
6481 	 */
6482 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6483 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6484 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6485 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6486 		    V_QUEUENUMBER(sc->traceq));
6487 		pi->flags |= HAS_TRACEQ;
6488 	}
6489 
6490 	/* all ok */
6491 	pi->up_vis++;
6492 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6493 	if (pi->link_cfg.link_ok)
6494 		t4_os_link_changed(pi);
6495 	PORT_UNLOCK(pi);
6496 
6497 	mtx_lock(&vi->tick_mtx);
6498 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6499 		callout_reset(&vi->tick, hz, vi_tick, vi);
6500 	else
6501 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6502 	mtx_unlock(&vi->tick_mtx);
6503 done:
6504 	if (rc != 0)
6505 		cxgbe_uninit_synchronized(vi);
6506 
6507 	return (rc);
6508 }
6509 
6510 /*
6511  * Idempotent.
6512  */
6513 static int
6514 cxgbe_uninit_synchronized(struct vi_info *vi)
6515 {
6516 	struct port_info *pi = vi->pi;
6517 	struct adapter *sc = pi->adapter;
6518 	if_t ifp = vi->ifp;
6519 	int rc, i;
6520 	struct sge_txq *txq;
6521 
6522 	ASSERT_SYNCHRONIZED_OP(sc);
6523 
6524 	if (!(vi->flags & VI_INIT_DONE)) {
6525 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6526 			KASSERT(0, ("uninited VI is running"));
6527 			if_printf(ifp, "uninited VI with running ifnet.  "
6528 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6529 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6530 			    if_getdrvflags(ifp));
6531 		}
6532 		return (0);
6533 	}
6534 
6535 	/*
6536 	 * Disable the VI so that all its data in either direction is discarded
6537 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6538 	 * tick) intact as the TP can deliver negative advice or data that it's
6539 	 * holding in its RAM (for an offloaded connection) even after the VI is
6540 	 * disabled.
6541 	 */
6542 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6543 	if (rc) {
6544 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6545 		return (rc);
6546 	}
6547 
6548 	for_each_txq(vi, i, txq) {
6549 		TXQ_LOCK(txq);
6550 		txq->eq.flags &= ~EQ_ENABLED;
6551 		TXQ_UNLOCK(txq);
6552 	}
6553 
6554 	mtx_lock(&vi->tick_mtx);
6555 	callout_stop(&vi->tick);
6556 	mtx_unlock(&vi->tick_mtx);
6557 
6558 	PORT_LOCK(pi);
6559 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6560 		PORT_UNLOCK(pi);
6561 		return (0);
6562 	}
6563 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6564 	pi->up_vis--;
6565 	if (pi->up_vis > 0) {
6566 		PORT_UNLOCK(pi);
6567 		return (0);
6568 	}
6569 
6570 	pi->link_cfg.link_ok = false;
6571 	pi->link_cfg.speed = 0;
6572 	pi->link_cfg.link_down_rc = 255;
6573 	t4_os_link_changed(pi);
6574 	PORT_UNLOCK(pi);
6575 
6576 	return (0);
6577 }
6578 
6579 /*
6580  * It is ok for this function to fail midway and return right away.  t4_detach
6581  * will walk the entire sc->irq list and clean up whatever is valid.
6582  */
6583 int
6584 t4_setup_intr_handlers(struct adapter *sc)
6585 {
6586 	int rc, rid, p, q, v;
6587 	char s[8];
6588 	struct irq *irq;
6589 	struct port_info *pi;
6590 	struct vi_info *vi;
6591 	struct sge *sge = &sc->sge;
6592 	struct sge_rxq *rxq;
6593 #ifdef TCP_OFFLOAD
6594 	struct sge_ofld_rxq *ofld_rxq;
6595 #endif
6596 #ifdef DEV_NETMAP
6597 	struct sge_nm_rxq *nm_rxq;
6598 #endif
6599 #ifdef RSS
6600 	int nbuckets = rss_getnumbuckets();
6601 #endif
6602 
6603 	/*
6604 	 * Setup interrupts.
6605 	 */
6606 	irq = &sc->irq[0];
6607 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6608 	if (forwarding_intr_to_fwq(sc))
6609 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6610 
6611 	/* Multiple interrupts. */
6612 	if (sc->flags & IS_VF)
6613 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6614 		    ("%s: too few intr.", __func__));
6615 	else
6616 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6617 		    ("%s: too few intr.", __func__));
6618 
6619 	/* The first one is always error intr on PFs */
6620 	if (!(sc->flags & IS_VF)) {
6621 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6622 		if (rc != 0)
6623 			return (rc);
6624 		irq++;
6625 		rid++;
6626 	}
6627 
6628 	/* The second one is always the firmware event queue (first on VFs) */
6629 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6630 	if (rc != 0)
6631 		return (rc);
6632 	irq++;
6633 	rid++;
6634 
6635 	for_each_port(sc, p) {
6636 		pi = sc->port[p];
6637 		for_each_vi(pi, v, vi) {
6638 			vi->first_intr = rid - 1;
6639 
6640 			if (vi->nnmrxq > 0) {
6641 				int n = max(vi->nrxq, vi->nnmrxq);
6642 
6643 				rxq = &sge->rxq[vi->first_rxq];
6644 #ifdef DEV_NETMAP
6645 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6646 #endif
6647 				for (q = 0; q < n; q++) {
6648 					snprintf(s, sizeof(s), "%x%c%x", p,
6649 					    'a' + v, q);
6650 					if (q < vi->nrxq)
6651 						irq->rxq = rxq++;
6652 #ifdef DEV_NETMAP
6653 					if (q < vi->nnmrxq)
6654 						irq->nm_rxq = nm_rxq++;
6655 
6656 					if (irq->nm_rxq != NULL &&
6657 					    irq->rxq == NULL) {
6658 						/* Netmap rx only */
6659 						rc = t4_alloc_irq(sc, irq, rid,
6660 						    t4_nm_intr, irq->nm_rxq, s);
6661 					}
6662 					if (irq->nm_rxq != NULL &&
6663 					    irq->rxq != NULL) {
6664 						/* NIC and Netmap rx */
6665 						rc = t4_alloc_irq(sc, irq, rid,
6666 						    t4_vi_intr, irq, s);
6667 					}
6668 #endif
6669 					if (irq->rxq != NULL &&
6670 					    irq->nm_rxq == NULL) {
6671 						/* NIC rx only */
6672 						rc = t4_alloc_irq(sc, irq, rid,
6673 						    t4_intr, irq->rxq, s);
6674 					}
6675 					if (rc != 0)
6676 						return (rc);
6677 #ifdef RSS
6678 					if (q < vi->nrxq) {
6679 						bus_bind_intr(sc->dev, irq->res,
6680 						    rss_getcpu(q % nbuckets));
6681 					}
6682 #endif
6683 					irq++;
6684 					rid++;
6685 					vi->nintr++;
6686 				}
6687 			} else {
6688 				for_each_rxq(vi, q, rxq) {
6689 					snprintf(s, sizeof(s), "%x%c%x", p,
6690 					    'a' + v, q);
6691 					rc = t4_alloc_irq(sc, irq, rid,
6692 					    t4_intr, rxq, s);
6693 					if (rc != 0)
6694 						return (rc);
6695 #ifdef RSS
6696 					bus_bind_intr(sc->dev, irq->res,
6697 					    rss_getcpu(q % nbuckets));
6698 #endif
6699 					irq++;
6700 					rid++;
6701 					vi->nintr++;
6702 				}
6703 			}
6704 #ifdef TCP_OFFLOAD
6705 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6706 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6707 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6708 				    ofld_rxq, s);
6709 				if (rc != 0)
6710 					return (rc);
6711 				irq++;
6712 				rid++;
6713 				vi->nintr++;
6714 			}
6715 #endif
6716 		}
6717 	}
6718 	MPASS(irq == &sc->irq[sc->intr_count]);
6719 
6720 	return (0);
6721 }
6722 
6723 static void
6724 write_global_rss_key(struct adapter *sc)
6725 {
6726 #ifdef RSS
6727 	int i;
6728 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6729 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6730 
6731 	CTASSERT(RSS_KEYSIZE == 40);
6732 
6733 	rss_getkey((void *)&raw_rss_key[0]);
6734 	for (i = 0; i < nitems(rss_key); i++) {
6735 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6736 	}
6737 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6738 #endif
6739 }
6740 
6741 /*
6742  * Idempotent.
6743  */
6744 static int
6745 adapter_full_init(struct adapter *sc)
6746 {
6747 	int rc, i;
6748 
6749 	ASSERT_SYNCHRONIZED_OP(sc);
6750 
6751 	/*
6752 	 * queues that belong to the adapter (not any particular port).
6753 	 */
6754 	rc = t4_setup_adapter_queues(sc);
6755 	if (rc != 0)
6756 		return (rc);
6757 
6758 	MPASS(sc->params.nports <= nitems(sc->tq));
6759 	for (i = 0; i < sc->params.nports; i++) {
6760 		if (sc->tq[i] != NULL)
6761 			continue;
6762 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6763 		    taskqueue_thread_enqueue, &sc->tq[i]);
6764 		if (sc->tq[i] == NULL) {
6765 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6766 			return (ENOMEM);
6767 		}
6768 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6769 		    device_get_nameunit(sc->dev), i);
6770 	}
6771 
6772 	if (!(sc->flags & IS_VF)) {
6773 		write_global_rss_key(sc);
6774 		t4_intr_enable(sc);
6775 	}
6776 	return (0);
6777 }
6778 
6779 int
6780 adapter_init(struct adapter *sc)
6781 {
6782 	int rc;
6783 
6784 	ASSERT_SYNCHRONIZED_OP(sc);
6785 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6786 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6787 	    ("%s: FULL_INIT_DONE already", __func__));
6788 
6789 	rc = adapter_full_init(sc);
6790 	if (rc != 0)
6791 		adapter_full_uninit(sc);
6792 	else
6793 		sc->flags |= FULL_INIT_DONE;
6794 
6795 	return (rc);
6796 }
6797 
6798 /*
6799  * Idempotent.
6800  */
6801 static void
6802 adapter_full_uninit(struct adapter *sc)
6803 {
6804 	int i;
6805 
6806 	t4_teardown_adapter_queues(sc);
6807 
6808 	for (i = 0; i < nitems(sc->tq); i++) {
6809 		if (sc->tq[i] == NULL)
6810 			continue;
6811 		taskqueue_free(sc->tq[i]);
6812 		sc->tq[i] = NULL;
6813 	}
6814 
6815 	sc->flags &= ~FULL_INIT_DONE;
6816 }
6817 
6818 #ifdef RSS
6819 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6820     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6821     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6822     RSS_HASHTYPE_RSS_UDP_IPV6)
6823 
6824 /* Translates kernel hash types to hardware. */
6825 static int
6826 hashconfig_to_hashen(int hashconfig)
6827 {
6828 	int hashen = 0;
6829 
6830 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6831 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6832 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6833 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6834 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6835 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6836 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6837 	}
6838 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6839 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6840 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6841 	}
6842 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6843 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6844 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6845 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6846 
6847 	return (hashen);
6848 }
6849 
6850 /* Translates hardware hash types to kernel. */
6851 static int
6852 hashen_to_hashconfig(int hashen)
6853 {
6854 	int hashconfig = 0;
6855 
6856 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6857 		/*
6858 		 * If UDP hashing was enabled it must have been enabled for
6859 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6860 		 * enabling any 4-tuple hash is nonsense configuration.
6861 		 */
6862 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6863 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6864 
6865 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6866 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6867 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6868 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6869 	}
6870 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6871 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6872 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6873 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6874 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6875 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6876 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6877 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6878 
6879 	return (hashconfig);
6880 }
6881 #endif
6882 
6883 /*
6884  * Idempotent.
6885  */
6886 static int
6887 vi_full_init(struct vi_info *vi)
6888 {
6889 	struct adapter *sc = vi->adapter;
6890 	struct sge_rxq *rxq;
6891 	int rc, i, j;
6892 #ifdef RSS
6893 	int nbuckets = rss_getnumbuckets();
6894 	int hashconfig = rss_gethashconfig();
6895 	int extra;
6896 #endif
6897 
6898 	ASSERT_SYNCHRONIZED_OP(sc);
6899 
6900 	/*
6901 	 * Allocate tx/rx/fl queues for this VI.
6902 	 */
6903 	rc = t4_setup_vi_queues(vi);
6904 	if (rc != 0)
6905 		return (rc);
6906 
6907 	/*
6908 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6909 	 */
6910 	if (vi->nrxq > vi->rss_size) {
6911 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6912 		    "some queues will never receive traffic.\n", vi->nrxq,
6913 		    vi->rss_size);
6914 	} else if (vi->rss_size % vi->nrxq) {
6915 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6916 		    "expect uneven traffic distribution.\n", vi->nrxq,
6917 		    vi->rss_size);
6918 	}
6919 #ifdef RSS
6920 	if (vi->nrxq != nbuckets) {
6921 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6922 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6923 	}
6924 #endif
6925 	if (vi->rss == NULL)
6926 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6927 		    M_ZERO | M_WAITOK);
6928 	for (i = 0; i < vi->rss_size;) {
6929 #ifdef RSS
6930 		j = rss_get_indirection_to_bucket(i);
6931 		j %= vi->nrxq;
6932 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6933 		vi->rss[i++] = rxq->iq.abs_id;
6934 #else
6935 		for_each_rxq(vi, j, rxq) {
6936 			vi->rss[i++] = rxq->iq.abs_id;
6937 			if (i == vi->rss_size)
6938 				break;
6939 		}
6940 #endif
6941 	}
6942 
6943 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6944 	    vi->rss, vi->rss_size);
6945 	if (rc != 0) {
6946 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6947 		return (rc);
6948 	}
6949 
6950 #ifdef RSS
6951 	vi->hashen = hashconfig_to_hashen(hashconfig);
6952 
6953 	/*
6954 	 * We may have had to enable some hashes even though the global config
6955 	 * wants them disabled.  This is a potential problem that must be
6956 	 * reported to the user.
6957 	 */
6958 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6959 
6960 	/*
6961 	 * If we consider only the supported hash types, then the enabled hashes
6962 	 * are a superset of the requested hashes.  In other words, there cannot
6963 	 * be any supported hash that was requested but not enabled, but there
6964 	 * can be hashes that were not requested but had to be enabled.
6965 	 */
6966 	extra &= SUPPORTED_RSS_HASHTYPES;
6967 	MPASS((extra & hashconfig) == 0);
6968 
6969 	if (extra) {
6970 		CH_ALERT(vi,
6971 		    "global RSS config (0x%x) cannot be accommodated.\n",
6972 		    hashconfig);
6973 	}
6974 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6975 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6976 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6977 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6978 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6979 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6980 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6981 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6982 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6983 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6984 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6985 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6986 #else
6987 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6988 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6989 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6990 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6991 #endif
6992 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6993 	    0, 0);
6994 	if (rc != 0) {
6995 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6996 		return (rc);
6997 	}
6998 
6999 	return (0);
7000 }
7001 
7002 int
7003 vi_init(struct vi_info *vi)
7004 {
7005 	int rc;
7006 
7007 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
7008 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
7009 	    ("%s: VI_INIT_DONE already", __func__));
7010 
7011 	rc = vi_full_init(vi);
7012 	if (rc != 0)
7013 		vi_full_uninit(vi);
7014 	else
7015 		vi->flags |= VI_INIT_DONE;
7016 
7017 	return (rc);
7018 }
7019 
7020 /*
7021  * Idempotent.
7022  */
7023 static void
7024 vi_full_uninit(struct vi_info *vi)
7025 {
7026 
7027 	if (vi->flags & VI_INIT_DONE) {
7028 		quiesce_vi(vi);
7029 		free(vi->rss, M_CXGBE);
7030 		free(vi->nm_rss, M_CXGBE);
7031 	}
7032 
7033 	t4_teardown_vi_queues(vi);
7034 	vi->flags &= ~VI_INIT_DONE;
7035 }
7036 
7037 static void
7038 quiesce_txq(struct sge_txq *txq)
7039 {
7040 	struct sge_eq *eq = &txq->eq;
7041 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7042 
7043 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7044 	MPASS(!(eq->flags & EQ_ENABLED));
7045 
7046 	/* Wait for the mp_ring to empty. */
7047 	while (!mp_ring_is_idle(txq->r)) {
7048 		mp_ring_check_drainage(txq->r, 4096);
7049 		pause("rquiesce", 1);
7050 	}
7051 	MPASS(txq->txp.npkt == 0);
7052 
7053 	if (eq->flags & EQ_HW_ALLOCATED) {
7054 		/*
7055 		 * Hardware is alive and working normally.  Wait for it to
7056 		 * finish and then wait for the driver to catch up and reclaim
7057 		 * all descriptors.
7058 		 */
7059 		while (spg->cidx != htobe16(eq->pidx))
7060 			pause("equiesce", 1);
7061 		while (eq->cidx != eq->pidx)
7062 			pause("dquiesce", 1);
7063 	} else {
7064 		/*
7065 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7066 		 * descriptors directly.
7067 		 */
7068 		TXQ_LOCK(txq);
7069 		while (eq->cidx != eq->pidx) {
7070 			struct mbuf *m, *nextpkt;
7071 			struct tx_sdesc *txsd;
7072 
7073 			txsd = &txq->sdesc[eq->cidx];
7074 			for (m = txsd->m; m != NULL; m = nextpkt) {
7075 				nextpkt = m->m_nextpkt;
7076 				m->m_nextpkt = NULL;
7077 				m_freem(m);
7078 			}
7079 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7080 		}
7081 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7082 		TXQ_UNLOCK(txq);
7083 	}
7084 }
7085 
7086 static void
7087 quiesce_wrq(struct sge_wrq *wrq)
7088 {
7089 	struct wrqe *wr;
7090 
7091 	TXQ_LOCK(wrq);
7092 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7093 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7094 #ifdef INVARIANTS
7095 		wrq->nwr_pending--;
7096 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7097 #endif
7098 		free(wr, M_CXGBE);
7099 	}
7100 	MPASS(wrq->nwr_pending == 0);
7101 	MPASS(wrq->ndesc_needed == 0);
7102 	wrq->nwr_pending = 0;
7103 	wrq->ndesc_needed = 0;
7104 	TXQ_UNLOCK(wrq);
7105 }
7106 
7107 static void
7108 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7109 {
7110 	/* Synchronize with the interrupt handler */
7111 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7112 		pause("iqfree", 1);
7113 
7114 	if (fl != NULL) {
7115 		MPASS(iq->flags & IQ_HAS_FL);
7116 
7117 		mtx_lock(&sc->sfl_lock);
7118 		FL_LOCK(fl);
7119 		fl->flags |= FL_DOOMED;
7120 		FL_UNLOCK(fl);
7121 		callout_stop(&sc->sfl_callout);
7122 		mtx_unlock(&sc->sfl_lock);
7123 
7124 		KASSERT((fl->flags & FL_STARVING) == 0,
7125 		    ("%s: still starving", __func__));
7126 
7127 		/* Release all buffers if hardware is no longer available. */
7128 		if (!(iq->flags & IQ_HW_ALLOCATED))
7129 			free_fl_buffers(sc, fl);
7130 	}
7131 }
7132 
7133 /*
7134  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7135  * that no new work is being enqueued by the hardware or the driver.  That part
7136  * should be arranged before calling this function.
7137  */
7138 static void
7139 quiesce_vi(struct vi_info *vi)
7140 {
7141 	int i;
7142 	struct adapter *sc = vi->adapter;
7143 	struct sge_rxq *rxq;
7144 	struct sge_txq *txq;
7145 #ifdef TCP_OFFLOAD
7146 	struct sge_ofld_rxq *ofld_rxq;
7147 #endif
7148 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7149 	struct sge_ofld_txq *ofld_txq;
7150 #endif
7151 
7152 	if (!(vi->flags & VI_INIT_DONE))
7153 		return;
7154 
7155 	for_each_txq(vi, i, txq) {
7156 		quiesce_txq(txq);
7157 	}
7158 
7159 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7160 	for_each_ofld_txq(vi, i, ofld_txq) {
7161 		quiesce_wrq(&ofld_txq->wrq);
7162 	}
7163 #endif
7164 
7165 	for_each_rxq(vi, i, rxq) {
7166 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7167 	}
7168 
7169 #ifdef TCP_OFFLOAD
7170 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7171 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7172 	}
7173 #endif
7174 }
7175 
7176 static int
7177 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7178     driver_intr_t *handler, void *arg, char *name)
7179 {
7180 	int rc;
7181 
7182 	irq->rid = rid;
7183 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7184 	    RF_SHAREABLE | RF_ACTIVE);
7185 	if (irq->res == NULL) {
7186 		device_printf(sc->dev,
7187 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7188 		return (ENOMEM);
7189 	}
7190 
7191 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7192 	    NULL, handler, arg, &irq->tag);
7193 	if (rc != 0) {
7194 		device_printf(sc->dev,
7195 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7196 		    rid, name, rc);
7197 	} else if (name)
7198 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7199 
7200 	return (rc);
7201 }
7202 
7203 static int
7204 t4_free_irq(struct adapter *sc, struct irq *irq)
7205 {
7206 	if (irq->tag)
7207 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7208 	if (irq->res)
7209 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7210 
7211 	bzero(irq, sizeof(*irq));
7212 
7213 	return (0);
7214 }
7215 
7216 static void
7217 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7218 {
7219 
7220 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7221 	t4_get_regs(sc, buf, regs->len);
7222 }
7223 
7224 #define	A_PL_INDIR_CMD	0x1f8
7225 
7226 #define	S_PL_AUTOINC	31
7227 #define	M_PL_AUTOINC	0x1U
7228 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7229 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7230 
7231 #define	S_PL_VFID	20
7232 #define	M_PL_VFID	0xffU
7233 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7234 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7235 
7236 #define	S_PL_ADDR	0
7237 #define	M_PL_ADDR	0xfffffU
7238 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7239 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7240 
7241 #define	A_PL_INDIR_DATA	0x1fc
7242 
7243 static uint64_t
7244 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7245 {
7246 	u32 stats[2];
7247 
7248 	if (sc->flags & IS_VF) {
7249 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7250 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7251 	} else {
7252 		mtx_assert(&sc->reg_lock, MA_OWNED);
7253 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7254 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7255 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7256 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7257 	}
7258 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7259 }
7260 
7261 static void
7262 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7263 {
7264 
7265 #define GET_STAT(name) \
7266 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7267 
7268 	if (!(sc->flags & IS_VF))
7269 		mtx_lock(&sc->reg_lock);
7270 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7271 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7272 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7273 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7274 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7275 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7276 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7277 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7278 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7279 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7280 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7281 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7282 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7283 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7284 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7285 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7286 	if (!(sc->flags & IS_VF))
7287 		mtx_unlock(&sc->reg_lock);
7288 
7289 #undef GET_STAT
7290 }
7291 
7292 static void
7293 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7294 {
7295 	int reg;
7296 
7297 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7298 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7299 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7300 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7301 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7302 }
7303 
7304 static void
7305 vi_refresh_stats(struct vi_info *vi)
7306 {
7307 	struct timeval tv;
7308 	const struct timeval interval = {0, 250000};	/* 250ms */
7309 
7310 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7311 
7312 	if (vi->flags & VI_SKIP_STATS)
7313 		return;
7314 
7315 	getmicrotime(&tv);
7316 	timevalsub(&tv, &interval);
7317 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7318 		return;
7319 
7320 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7321 	getmicrotime(&vi->last_refreshed);
7322 }
7323 
7324 static void
7325 cxgbe_refresh_stats(struct vi_info *vi)
7326 {
7327 	u_int i, v, tnl_cong_drops, chan_map;
7328 	struct timeval tv;
7329 	const struct timeval interval = {0, 250000};	/* 250ms */
7330 	struct port_info *pi;
7331 	struct adapter *sc;
7332 
7333 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7334 
7335 	if (vi->flags & VI_SKIP_STATS)
7336 		return;
7337 
7338 	getmicrotime(&tv);
7339 	timevalsub(&tv, &interval);
7340 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7341 		return;
7342 
7343 	pi = vi->pi;
7344 	sc = vi->adapter;
7345 	tnl_cong_drops = 0;
7346 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7347 	chan_map = pi->rx_e_chan_map;
7348 	while (chan_map) {
7349 		i = ffs(chan_map) - 1;
7350 		mtx_lock(&sc->reg_lock);
7351 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7352 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7353 		mtx_unlock(&sc->reg_lock);
7354 		tnl_cong_drops += v;
7355 		chan_map &= ~(1 << i);
7356 	}
7357 	pi->tnl_cong_drops = tnl_cong_drops;
7358 	getmicrotime(&vi->last_refreshed);
7359 }
7360 
7361 static void
7362 cxgbe_tick(void *arg)
7363 {
7364 	struct vi_info *vi = arg;
7365 
7366 	MPASS(IS_MAIN_VI(vi));
7367 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7368 
7369 	cxgbe_refresh_stats(vi);
7370 	callout_schedule(&vi->tick, hz);
7371 }
7372 
7373 static void
7374 vi_tick(void *arg)
7375 {
7376 	struct vi_info *vi = arg;
7377 
7378 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7379 
7380 	vi_refresh_stats(vi);
7381 	callout_schedule(&vi->tick, hz);
7382 }
7383 
7384 /*
7385  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7386  */
7387 static char *caps_decoder[] = {
7388 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7389 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7390 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7391 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7392 	    "\006HASHFILTER\007ETHOFLD",
7393 	"\20\001TOE",					/* 4: TOE */
7394 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7395 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7396 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7397 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7398 	    "\007T10DIF"
7399 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7400 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7401 	    "\004TLS_HW",
7402 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7403 		    "\004PO_INITIATOR\005PO_TARGET",
7404 };
7405 
7406 void
7407 t4_sysctls(struct adapter *sc)
7408 {
7409 	struct sysctl_ctx_list *ctx = &sc->ctx;
7410 	struct sysctl_oid *oid;
7411 	struct sysctl_oid_list *children, *c0;
7412 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7413 
7414 	/*
7415 	 * dev.t4nex.X.
7416 	 */
7417 	oid = device_get_sysctl_tree(sc->dev);
7418 	c0 = children = SYSCTL_CHILDREN(oid);
7419 
7420 	sc->sc_do_rxcopy = 1;
7421 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7422 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7423 
7424 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7425 	    sc->params.nports, "# of ports");
7426 
7427 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7428 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7429 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7430 	    "available doorbells");
7431 
7432 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7433 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7434 
7435 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7436 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7437 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7438 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7439 
7440 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7441 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7442 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7443 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7444 
7445 	t4_sge_sysctls(sc, ctx, children);
7446 
7447 	sc->lro_timeout = 100;
7448 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7449 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7450 
7451 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7452 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7453 
7454 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7455 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7456 
7457 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7458 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7459 
7460 	if (sc->flags & IS_VF)
7461 		return;
7462 
7463 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7464 	    NULL, chip_rev(sc), "chip hardware revision");
7465 
7466 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7467 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7468 
7469 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7470 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7471 
7472 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7473 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7474 
7475 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7476 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7477 
7478 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7479 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7480 
7481 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7482 	    sc->er_version, 0, "expansion ROM version");
7483 
7484 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7485 	    sc->bs_version, 0, "bootstrap firmware version");
7486 
7487 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7488 	    NULL, sc->params.scfg_vers, "serial config version");
7489 
7490 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7491 	    NULL, sc->params.vpd_vers, "VPD version");
7492 
7493 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7494 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7495 
7496 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7497 	    sc->cfcsum, "config file checksum");
7498 
7499 #define SYSCTL_CAP(name, n, text) \
7500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7501 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7502 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7503 	    "available " text " capabilities")
7504 
7505 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7506 	SYSCTL_CAP(linkcaps, 1, "link");
7507 	SYSCTL_CAP(switchcaps, 2, "switch");
7508 	SYSCTL_CAP(niccaps, 3, "NIC");
7509 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7510 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7511 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7512 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7513 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7514 #undef SYSCTL_CAP
7515 
7516 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7517 	    NULL, sc->tids.nftids, "number of filters");
7518 
7519 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7520 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7521 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7522 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7523 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7524 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7525 
7526 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7527 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7528 	    sysctl_loadavg, "A",
7529 	    "microprocessor load averages (debug firmwares only)");
7530 
7531 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7532 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7533 	    "I", "core Vdd (in mV)");
7534 
7535 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7536 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7537 	    sysctl_cpus, "A", "local CPUs");
7538 
7539 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7540 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7541 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7542 
7543 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7544 	    &sc->swintr, 0, "software triggered interrupts");
7545 
7546 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7547 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7548 	    "1 = reset adapter, 0 = zero reset counter");
7549 
7550 	/*
7551 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7552 	 */
7553 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7554 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7555 	    "logs and miscellaneous information");
7556 	children = SYSCTL_CHILDREN(oid);
7557 
7558 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7559 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7560 	    sysctl_cctrl, "A", "congestion control");
7561 
7562 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7563 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7564 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7565 
7566 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7567 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7568 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7569 
7570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7571 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7572 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7573 
7574 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7575 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7576 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7577 
7578 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7579 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7580 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7581 
7582 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7583 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7584 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7585 
7586 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7587 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7588 	    sysctl_cim_la, "A", "CIM logic analyzer");
7589 
7590 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7591 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7592 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7593 
7594 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7595 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7596 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7597 
7598 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7599 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7600 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7601 
7602 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7603 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7604 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7605 
7606 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7607 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7608 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7609 
7610 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7611 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7612 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7613 
7614 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7615 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7616 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7617 
7618 	if (chip_id(sc) > CHELSIO_T4) {
7619 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7620 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7621 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7622 		    "CIM OBQ 6 (SGE0-RX)");
7623 
7624 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7625 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7626 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7627 		    "CIM OBQ 7 (SGE1-RX)");
7628 	}
7629 
7630 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7631 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7632 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7633 
7634 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7635 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7636 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7637 
7638 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7639 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7640 	    sysctl_cpl_stats, "A", "CPL statistics");
7641 
7642 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7643 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7644 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7645 
7646 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7647 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7648 	    sysctl_tid_stats, "A", "tid stats");
7649 
7650 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7651 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7652 	    sysctl_devlog, "A", "firmware's device log");
7653 
7654 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7655 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7656 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7657 
7658 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7659 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7660 	    sysctl_hw_sched, "A", "hardware scheduler ");
7661 
7662 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7663 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7664 	    sysctl_l2t, "A", "hardware L2 table");
7665 
7666 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7667 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7668 	    sysctl_smt, "A", "hardware source MAC table");
7669 
7670 #ifdef INET6
7671 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7672 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7673 	    sysctl_clip, "A", "active CLIP table entries");
7674 #endif
7675 
7676 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7677 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7678 	    sysctl_lb_stats, "A", "loopback statistics");
7679 
7680 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7681 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7682 	    sysctl_meminfo, "A", "memory regions");
7683 
7684 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7685 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7686 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7687 	    "A", "MPS TCAM entries");
7688 
7689 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7690 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7691 	    sysctl_path_mtus, "A", "path MTUs");
7692 
7693 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7694 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7695 	    sysctl_pm_stats, "A", "PM statistics");
7696 
7697 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7698 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7699 	    sysctl_rdma_stats, "A", "RDMA statistics");
7700 
7701 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7702 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7703 	    sysctl_tcp_stats, "A", "TCP statistics");
7704 
7705 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7706 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7707 	    sysctl_tids, "A", "TID information");
7708 
7709 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7710 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7711 	    sysctl_tp_err_stats, "A", "TP error statistics");
7712 
7713 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7714 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7715 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7716 
7717 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7718 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7719 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7720 
7721 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7722 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7723 	    sysctl_tp_la, "A", "TP logic analyzer");
7724 
7725 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7726 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7727 	    sysctl_tx_rate, "A", "Tx rate");
7728 
7729 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7730 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7731 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7732 
7733 	if (chip_id(sc) >= CHELSIO_T5) {
7734 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7735 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7736 		    sysctl_wcwr_stats, "A", "write combined work requests");
7737 	}
7738 
7739 #ifdef KERN_TLS
7740 	if (is_ktls(sc)) {
7741 		/*
7742 		 * dev.t4nex.0.tls.
7743 		 */
7744 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7745 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7746 		children = SYSCTL_CHILDREN(oid);
7747 
7748 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7749 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7750 		    "keys in work requests (1) or attempt to store TLS keys "
7751 		    "in card memory.");
7752 
7753 		if (is_t6(sc))
7754 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7755 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7756 			    "combine TCB field updates with TLS record work "
7757 			    "requests.");
7758 	}
7759 #endif
7760 
7761 #ifdef TCP_OFFLOAD
7762 	if (is_offload(sc)) {
7763 		int i;
7764 		char s[4];
7765 
7766 		/*
7767 		 * dev.t4nex.X.toe.
7768 		 */
7769 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7770 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7771 		children = SYSCTL_CHILDREN(oid);
7772 
7773 		sc->tt.cong_algorithm = -1;
7774 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7775 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7776 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7777 		    "3 = highspeed)");
7778 
7779 		sc->tt.sndbuf = -1;
7780 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7781 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7782 
7783 		sc->tt.ddp = 0;
7784 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7785 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7786 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7787 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7788 
7789 		sc->tt.rx_coalesce = -1;
7790 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7791 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7792 
7793 		sc->tt.tls = 0;
7794 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7795 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7796 		    "Inline TLS allowed");
7797 
7798 		sc->tt.tx_align = -1;
7799 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7800 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7801 
7802 		sc->tt.tx_zcopy = 0;
7803 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7804 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7805 		    "Enable zero-copy aio_write(2)");
7806 
7807 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7808 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7809 		    "cop_managed_offloading", CTLFLAG_RW,
7810 		    &sc->tt.cop_managed_offloading, 0,
7811 		    "COP (Connection Offload Policy) controls all TOE offload");
7812 
7813 		sc->tt.autorcvbuf_inc = 16 * 1024;
7814 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7815 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7816 		    "autorcvbuf increment");
7817 
7818 		sc->tt.update_hc_on_pmtu_change = 1;
7819 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7820 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7821 		    &sc->tt.update_hc_on_pmtu_change, 0,
7822 		    "Update hostcache entry if the PMTU changes");
7823 
7824 		sc->tt.iso = 1;
7825 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7826 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7827 
7828 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7829 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7830 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7831 
7832 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7833 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7834 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7835 
7836 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7837 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7838 		    sysctl_tp_tick, "A", "DACK tick (us)");
7839 
7840 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7841 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7842 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7843 
7844 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7845 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7846 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7847 		    "Minimum retransmit interval (us)");
7848 
7849 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7850 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7851 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7852 		    "Maximum retransmit interval (us)");
7853 
7854 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7855 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7856 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7857 		    "Persist timer min (us)");
7858 
7859 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7860 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7861 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7862 		    "Persist timer max (us)");
7863 
7864 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7865 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7866 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7867 		    "Keepalive idle timer (us)");
7868 
7869 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7870 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7871 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7872 		    "Keepalive interval timer (us)");
7873 
7874 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7875 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7876 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7877 
7878 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7879 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7880 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7881 		    "FINWAIT2 timer (us)");
7882 
7883 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7884 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7885 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7886 		    "Number of SYN retransmissions before abort");
7887 
7888 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7889 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7890 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7891 		    "Number of retransmissions before abort");
7892 
7893 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7894 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7895 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7896 		    "Number of keepalive probes before abort");
7897 
7898 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7899 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7900 		    "TOE retransmit backoffs");
7901 		children = SYSCTL_CHILDREN(oid);
7902 		for (i = 0; i < 16; i++) {
7903 			snprintf(s, sizeof(s), "%u", i);
7904 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7905 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7906 			    i, sysctl_tp_backoff, "IU",
7907 			    "TOE retransmit backoff");
7908 		}
7909 	}
7910 #endif
7911 }
7912 
7913 void
7914 vi_sysctls(struct vi_info *vi)
7915 {
7916 	struct sysctl_ctx_list *ctx = &vi->ctx;
7917 	struct sysctl_oid *oid;
7918 	struct sysctl_oid_list *children;
7919 
7920 	/*
7921 	 * dev.v?(cxgbe|cxl).X.
7922 	 */
7923 	oid = device_get_sysctl_tree(vi->dev);
7924 	children = SYSCTL_CHILDREN(oid);
7925 
7926 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7927 	    vi->viid, "VI identifer");
7928 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7929 	    &vi->nrxq, 0, "# of rx queues");
7930 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7931 	    &vi->ntxq, 0, "# of tx queues");
7932 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7933 	    &vi->first_rxq, 0, "index of first rx queue");
7934 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7935 	    &vi->first_txq, 0, "index of first tx queue");
7936 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7937 	    vi->rss_base, "start of RSS indirection table");
7938 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7939 	    vi->rss_size, "size of RSS indirection table");
7940 
7941 	if (IS_MAIN_VI(vi)) {
7942 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7943 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7944 		    sysctl_noflowq, "IU",
7945 		    "Reserve queue 0 for non-flowid packets");
7946 	}
7947 
7948 	if (vi->adapter->flags & IS_VF) {
7949 		MPASS(vi->flags & TX_USES_VM_WR);
7950 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7951 		    NULL, 1, "use VM work requests for transmit");
7952 	} else {
7953 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7954 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7955 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7956 	}
7957 
7958 #ifdef TCP_OFFLOAD
7959 	if (vi->nofldrxq != 0) {
7960 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7961 		    &vi->nofldrxq, 0,
7962 		    "# of rx queues for offloaded TCP connections");
7963 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7964 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7965 		    "index of first TOE rx queue");
7966 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7967 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7968 		    sysctl_holdoff_tmr_idx_ofld, "I",
7969 		    "holdoff timer index for TOE queues");
7970 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7971 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7972 		    sysctl_holdoff_pktc_idx_ofld, "I",
7973 		    "holdoff packet counter index for TOE queues");
7974 	}
7975 #endif
7976 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7977 	if (vi->nofldtxq != 0) {
7978 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7979 		    &vi->nofldtxq, 0,
7980 		    "# of tx queues for TOE/ETHOFLD");
7981 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7982 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7983 		    "index of first TOE/ETHOFLD tx queue");
7984 	}
7985 #endif
7986 #ifdef DEV_NETMAP
7987 	if (vi->nnmrxq != 0) {
7988 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7989 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7990 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7991 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7992 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7993 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7994 		    "index of first netmap rx queue");
7995 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7996 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7997 		    "index of first netmap tx queue");
7998 	}
7999 #endif
8000 
8001 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
8002 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8003 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
8004 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
8005 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8006 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
8007 
8008 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
8009 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8010 	    sysctl_qsize_rxq, "I", "rx queue size");
8011 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
8012 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
8013 	    sysctl_qsize_txq, "I", "tx queue size");
8014 }
8015 
8016 static void
8017 cxgbe_sysctls(struct port_info *pi)
8018 {
8019 	struct sysctl_ctx_list *ctx = &pi->ctx;
8020 	struct sysctl_oid *oid;
8021 	struct sysctl_oid_list *children, *children2;
8022 	struct adapter *sc = pi->adapter;
8023 	int i;
8024 	char name[16];
8025 	static char *tc_flags = {"\20\1USER"};
8026 
8027 	/*
8028 	 * dev.cxgbe.X.
8029 	 */
8030 	oid = device_get_sysctl_tree(pi->dev);
8031 	children = SYSCTL_CHILDREN(oid);
8032 
8033 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8034 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8035 	    sysctl_linkdnrc, "A", "reason why link is down");
8036 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8037 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8038 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8039 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8040 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8041 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8042 		    sysctl_btphy, "I", "PHY firmware version");
8043 	}
8044 
8045 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8046 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8047 	    sysctl_pause_settings, "A",
8048 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8049 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8050 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8051 	    "FEC in use on the link");
8052 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8053 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8054 	    sysctl_requested_fec, "A",
8055 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8056 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8057 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8058 	    "FEC recommended by the cable/transceiver");
8059 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8060 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8061 	    sysctl_autoneg, "I",
8062 	    "autonegotiation (-1 = not supported)");
8063 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8064 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8065 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8066 
8067 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8068 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8069 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8070 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8071 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8072 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8073 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8074 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8075 
8076 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8077 	    port_top_speed(pi), "max speed (in Gbps)");
8078 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8079 	    pi->mps_bg_map, "MPS buffer group map");
8080 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8081 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8082 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8083 	    pi->tx_chan, "TP tx c-channel");
8084 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8085 	    pi->rx_chan, "TP rx c-channel");
8086 
8087 	if (sc->flags & IS_VF)
8088 		return;
8089 
8090 	/*
8091 	 * dev.(cxgbe|cxl).X.tc.
8092 	 */
8093 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8094 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8095 	    "Tx scheduler traffic classes (cl_rl)");
8096 	children2 = SYSCTL_CHILDREN(oid);
8097 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8098 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8099 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8100 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8101 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8102 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8103 	for (i = 0; i < sc->params.nsched_cls; i++) {
8104 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8105 
8106 		snprintf(name, sizeof(name), "%d", i);
8107 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8108 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8109 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8110 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8111 		    CTLFLAG_RD, &tc->state, 0, "current state");
8112 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8113 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8114 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8115 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8116 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8117 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8118 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8119 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8120 		    "traffic class parameters");
8121 	}
8122 
8123 	/*
8124 	 * dev.cxgbe.X.stats.
8125 	 */
8126 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8127 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8128 	children = SYSCTL_CHILDREN(oid);
8129 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8130 	    &pi->tx_parse_error, 0,
8131 	    "# of tx packets with invalid length or # of segments");
8132 
8133 #define T4_REGSTAT(name, stat, desc) \
8134     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8135 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8136 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8137         sysctl_handle_t4_reg64, "QU", desc)
8138 
8139 /* We get these from port_stats and they may be stale by up to 1s */
8140 #define T4_PORTSTAT(name, desc) \
8141 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8142 	    &pi->stats.name, desc)
8143 
8144 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8145 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8146 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8147 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8148 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8149 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8150 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8151 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8152 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8153 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8154 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8155 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8156 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8157 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8158 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8159 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8160 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8161 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8162 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8163 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8164 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8165 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8166 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8167 
8168 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8169 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8170 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8171 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8172 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8173 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8174 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8175 	if (is_t6(sc)) {
8176 		T4_PORTSTAT(rx_fcs_err,
8177 		    "# of frames received with bad FCS since last link up");
8178 	} else {
8179 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8180 		    "# of frames received with bad FCS");
8181 	}
8182 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8183 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8184 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8185 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8186 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8187 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8188 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8189 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8190 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8191 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8192 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8193 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8194 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8195 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8196 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8197 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8198 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8199 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8200 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8201 
8202 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8203 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8204 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8205 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8206 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8207 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8208 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8209 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8210 
8211 #undef T4_REGSTAT
8212 #undef T4_PORTSTAT
8213 }
8214 
8215 static int
8216 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8217 {
8218 	int rc, *i, space = 0;
8219 	struct sbuf sb;
8220 
8221 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8222 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8223 		if (space)
8224 			sbuf_printf(&sb, " ");
8225 		sbuf_printf(&sb, "%d", *i);
8226 		space = 1;
8227 	}
8228 	rc = sbuf_finish(&sb);
8229 	sbuf_delete(&sb);
8230 	return (rc);
8231 }
8232 
8233 static int
8234 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8235 {
8236 	int rc;
8237 	struct sbuf *sb;
8238 
8239 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8240 	if (sb == NULL)
8241 		return (ENOMEM);
8242 
8243 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8244 	rc = sbuf_finish(sb);
8245 	sbuf_delete(sb);
8246 
8247 	return (rc);
8248 }
8249 
8250 static int
8251 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8252 {
8253 	int rc;
8254 	struct sbuf *sb;
8255 
8256 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8257 	if (sb == NULL)
8258 		return (ENOMEM);
8259 
8260 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8261 	rc = sbuf_finish(sb);
8262 	sbuf_delete(sb);
8263 
8264 	return (rc);
8265 }
8266 
8267 static int
8268 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8269 {
8270 	struct port_info *pi = arg1;
8271 	int op = arg2;
8272 	struct adapter *sc = pi->adapter;
8273 	u_int v;
8274 	int rc;
8275 
8276 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8277 	if (rc)
8278 		return (rc);
8279 	if (hw_off_limits(sc))
8280 		rc = ENXIO;
8281 	else {
8282 		/* XXX: magic numbers */
8283 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8284 		    op ? 0x20 : 0xc820, &v);
8285 	}
8286 	end_synchronized_op(sc, 0);
8287 	if (rc)
8288 		return (rc);
8289 	if (op == 0)
8290 		v /= 256;
8291 
8292 	rc = sysctl_handle_int(oidp, &v, 0, req);
8293 	return (rc);
8294 }
8295 
8296 static int
8297 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8298 {
8299 	struct vi_info *vi = arg1;
8300 	int rc, val;
8301 
8302 	val = vi->rsrv_noflowq;
8303 	rc = sysctl_handle_int(oidp, &val, 0, req);
8304 	if (rc != 0 || req->newptr == NULL)
8305 		return (rc);
8306 
8307 	if ((val >= 1) && (vi->ntxq > 1))
8308 		vi->rsrv_noflowq = 1;
8309 	else
8310 		vi->rsrv_noflowq = 0;
8311 
8312 	return (rc);
8313 }
8314 
8315 static int
8316 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8317 {
8318 	struct vi_info *vi = arg1;
8319 	struct adapter *sc = vi->adapter;
8320 	int rc, val, i;
8321 
8322 	MPASS(!(sc->flags & IS_VF));
8323 
8324 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8325 	rc = sysctl_handle_int(oidp, &val, 0, req);
8326 	if (rc != 0 || req->newptr == NULL)
8327 		return (rc);
8328 
8329 	if (val != 0 && val != 1)
8330 		return (EINVAL);
8331 
8332 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8333 	    "t4txvm");
8334 	if (rc)
8335 		return (rc);
8336 	if (hw_off_limits(sc))
8337 		rc = ENXIO;
8338 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8339 		/*
8340 		 * We don't want parse_pkt to run with one setting (VF or PF)
8341 		 * and then eth_tx to see a different setting but still use
8342 		 * stale information calculated by parse_pkt.
8343 		 */
8344 		rc = EBUSY;
8345 	} else {
8346 		struct port_info *pi = vi->pi;
8347 		struct sge_txq *txq;
8348 		uint32_t ctrl0;
8349 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8350 
8351 		if (val) {
8352 			vi->flags |= TX_USES_VM_WR;
8353 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8354 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8355 			    V_TXPKT_INTF(pi->tx_chan));
8356 			if (!(sc->flags & IS_VF))
8357 				npkt--;
8358 		} else {
8359 			vi->flags &= ~TX_USES_VM_WR;
8360 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8361 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8362 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8363 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8364 		}
8365 		for_each_txq(vi, i, txq) {
8366 			txq->cpl_ctrl0 = ctrl0;
8367 			txq->txp.max_npkt = npkt;
8368 		}
8369 	}
8370 	end_synchronized_op(sc, LOCK_HELD);
8371 	return (rc);
8372 }
8373 
8374 static int
8375 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8376 {
8377 	struct vi_info *vi = arg1;
8378 	struct adapter *sc = vi->adapter;
8379 	int idx, rc, i;
8380 	struct sge_rxq *rxq;
8381 	uint8_t v;
8382 
8383 	idx = vi->tmr_idx;
8384 
8385 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8386 	if (rc != 0 || req->newptr == NULL)
8387 		return (rc);
8388 
8389 	if (idx < 0 || idx >= SGE_NTIMERS)
8390 		return (EINVAL);
8391 
8392 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8393 	    "t4tmr");
8394 	if (rc)
8395 		return (rc);
8396 
8397 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8398 	for_each_rxq(vi, i, rxq) {
8399 #ifdef atomic_store_rel_8
8400 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8401 #else
8402 		rxq->iq.intr_params = v;
8403 #endif
8404 	}
8405 	vi->tmr_idx = idx;
8406 
8407 	end_synchronized_op(sc, LOCK_HELD);
8408 	return (0);
8409 }
8410 
8411 static int
8412 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8413 {
8414 	struct vi_info *vi = arg1;
8415 	struct adapter *sc = vi->adapter;
8416 	int idx, rc;
8417 
8418 	idx = vi->pktc_idx;
8419 
8420 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8421 	if (rc != 0 || req->newptr == NULL)
8422 		return (rc);
8423 
8424 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8425 		return (EINVAL);
8426 
8427 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8428 	    "t4pktc");
8429 	if (rc)
8430 		return (rc);
8431 
8432 	if (vi->flags & VI_INIT_DONE)
8433 		rc = EBUSY; /* cannot be changed once the queues are created */
8434 	else
8435 		vi->pktc_idx = idx;
8436 
8437 	end_synchronized_op(sc, LOCK_HELD);
8438 	return (rc);
8439 }
8440 
8441 static int
8442 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8443 {
8444 	struct vi_info *vi = arg1;
8445 	struct adapter *sc = vi->adapter;
8446 	int qsize, rc;
8447 
8448 	qsize = vi->qsize_rxq;
8449 
8450 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8451 	if (rc != 0 || req->newptr == NULL)
8452 		return (rc);
8453 
8454 	if (qsize < 128 || (qsize & 7))
8455 		return (EINVAL);
8456 
8457 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8458 	    "t4rxqs");
8459 	if (rc)
8460 		return (rc);
8461 
8462 	if (vi->flags & VI_INIT_DONE)
8463 		rc = EBUSY; /* cannot be changed once the queues are created */
8464 	else
8465 		vi->qsize_rxq = qsize;
8466 
8467 	end_synchronized_op(sc, LOCK_HELD);
8468 	return (rc);
8469 }
8470 
8471 static int
8472 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8473 {
8474 	struct vi_info *vi = arg1;
8475 	struct adapter *sc = vi->adapter;
8476 	int qsize, rc;
8477 
8478 	qsize = vi->qsize_txq;
8479 
8480 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8481 	if (rc != 0 || req->newptr == NULL)
8482 		return (rc);
8483 
8484 	if (qsize < 128 || qsize > 65536)
8485 		return (EINVAL);
8486 
8487 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8488 	    "t4txqs");
8489 	if (rc)
8490 		return (rc);
8491 
8492 	if (vi->flags & VI_INIT_DONE)
8493 		rc = EBUSY; /* cannot be changed once the queues are created */
8494 	else
8495 		vi->qsize_txq = qsize;
8496 
8497 	end_synchronized_op(sc, LOCK_HELD);
8498 	return (rc);
8499 }
8500 
8501 static int
8502 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8503 {
8504 	struct port_info *pi = arg1;
8505 	struct adapter *sc = pi->adapter;
8506 	struct link_config *lc = &pi->link_cfg;
8507 	int rc;
8508 
8509 	if (req->newptr == NULL) {
8510 		struct sbuf *sb;
8511 		static char *bits = "\20\1RX\2TX\3AUTO";
8512 
8513 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8514 		if (sb == NULL)
8515 			return (ENOMEM);
8516 
8517 		if (lc->link_ok) {
8518 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8519 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8520 		} else {
8521 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8522 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8523 		}
8524 		rc = sbuf_finish(sb);
8525 		sbuf_delete(sb);
8526 	} else {
8527 		char s[2];
8528 		int n;
8529 
8530 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8531 		    PAUSE_AUTONEG));
8532 		s[1] = 0;
8533 
8534 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8535 		if (rc != 0)
8536 			return(rc);
8537 
8538 		if (s[1] != 0)
8539 			return (EINVAL);
8540 		if (s[0] < '0' || s[0] > '9')
8541 			return (EINVAL);	/* not a number */
8542 		n = s[0] - '0';
8543 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8544 			return (EINVAL);	/* some other bit is set too */
8545 
8546 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8547 		    "t4PAUSE");
8548 		if (rc)
8549 			return (rc);
8550 		if (!hw_off_limits(sc)) {
8551 			PORT_LOCK(pi);
8552 			lc->requested_fc = n;
8553 			fixup_link_config(pi);
8554 			if (pi->up_vis > 0)
8555 				rc = apply_link_config(pi);
8556 			set_current_media(pi);
8557 			PORT_UNLOCK(pi);
8558 		}
8559 		end_synchronized_op(sc, 0);
8560 	}
8561 
8562 	return (rc);
8563 }
8564 
8565 static int
8566 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8567 {
8568 	struct port_info *pi = arg1;
8569 	struct link_config *lc = &pi->link_cfg;
8570 	int rc;
8571 	struct sbuf *sb;
8572 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8573 
8574 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8575 	if (sb == NULL)
8576 		return (ENOMEM);
8577 	if (lc->link_ok)
8578 		sbuf_printf(sb, "%b", lc->fec, bits);
8579 	else
8580 		sbuf_printf(sb, "no link");
8581 	rc = sbuf_finish(sb);
8582 	sbuf_delete(sb);
8583 
8584 	return (rc);
8585 }
8586 
8587 static int
8588 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8589 {
8590 	struct port_info *pi = arg1;
8591 	struct adapter *sc = pi->adapter;
8592 	struct link_config *lc = &pi->link_cfg;
8593 	int rc;
8594 	int8_t old;
8595 
8596 	if (req->newptr == NULL) {
8597 		struct sbuf *sb;
8598 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8599 		    "\5RSVD3\6auto\7module";
8600 
8601 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8602 		if (sb == NULL)
8603 			return (ENOMEM);
8604 
8605 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8606 		rc = sbuf_finish(sb);
8607 		sbuf_delete(sb);
8608 	} else {
8609 		char s[8];
8610 		int n;
8611 
8612 		snprintf(s, sizeof(s), "%d",
8613 		    lc->requested_fec == FEC_AUTO ? -1 :
8614 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8615 
8616 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8617 		if (rc != 0)
8618 			return(rc);
8619 
8620 		n = strtol(&s[0], NULL, 0);
8621 		if (n < 0 || n & FEC_AUTO)
8622 			n = FEC_AUTO;
8623 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8624 			return (EINVAL);/* some other bit is set too */
8625 
8626 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8627 		    "t4reqf");
8628 		if (rc)
8629 			return (rc);
8630 		PORT_LOCK(pi);
8631 		old = lc->requested_fec;
8632 		if (n == FEC_AUTO)
8633 			lc->requested_fec = FEC_AUTO;
8634 		else if (n == 0 || n == FEC_NONE)
8635 			lc->requested_fec = FEC_NONE;
8636 		else {
8637 			if ((lc->pcaps |
8638 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8639 			    lc->pcaps) {
8640 				rc = ENOTSUP;
8641 				goto done;
8642 			}
8643 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8644 			    FEC_MODULE);
8645 		}
8646 		if (!hw_off_limits(sc)) {
8647 			fixup_link_config(pi);
8648 			if (pi->up_vis > 0) {
8649 				rc = apply_link_config(pi);
8650 				if (rc != 0) {
8651 					lc->requested_fec = old;
8652 					if (rc == FW_EPROTO)
8653 						rc = ENOTSUP;
8654 				}
8655 			}
8656 		}
8657 done:
8658 		PORT_UNLOCK(pi);
8659 		end_synchronized_op(sc, 0);
8660 	}
8661 
8662 	return (rc);
8663 }
8664 
8665 static int
8666 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8667 {
8668 	struct port_info *pi = arg1;
8669 	struct adapter *sc = pi->adapter;
8670 	struct link_config *lc = &pi->link_cfg;
8671 	int rc;
8672 	int8_t fec;
8673 	struct sbuf *sb;
8674 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8675 
8676 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8677 	if (sb == NULL)
8678 		return (ENOMEM);
8679 
8680 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8681 		rc = EBUSY;
8682 		goto done;
8683 	}
8684 	if (hw_off_limits(sc)) {
8685 		rc = ENXIO;
8686 		goto done;
8687 	}
8688 	PORT_LOCK(pi);
8689 	if (pi->up_vis == 0) {
8690 		/*
8691 		 * If all the interfaces are administratively down the firmware
8692 		 * does not report transceiver changes.  Refresh port info here.
8693 		 * This is the only reason we have a synchronized op in this
8694 		 * function.  Just PORT_LOCK would have been enough otherwise.
8695 		 */
8696 		t4_update_port_info(pi);
8697 	}
8698 
8699 	fec = lc->fec_hint;
8700 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8701 	    !fec_supported(lc->pcaps)) {
8702 		PORT_UNLOCK(pi);
8703 		sbuf_printf(sb, "n/a");
8704 	} else {
8705 		if (fec == 0)
8706 			fec = FEC_NONE;
8707 		PORT_UNLOCK(pi);
8708 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8709 	}
8710 	rc = sbuf_finish(sb);
8711 done:
8712 	sbuf_delete(sb);
8713 	end_synchronized_op(sc, 0);
8714 
8715 	return (rc);
8716 }
8717 
8718 static int
8719 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8720 {
8721 	struct port_info *pi = arg1;
8722 	struct adapter *sc = pi->adapter;
8723 	struct link_config *lc = &pi->link_cfg;
8724 	int rc, val;
8725 
8726 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8727 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8728 	else
8729 		val = -1;
8730 	rc = sysctl_handle_int(oidp, &val, 0, req);
8731 	if (rc != 0 || req->newptr == NULL)
8732 		return (rc);
8733 	if (val == 0)
8734 		val = AUTONEG_DISABLE;
8735 	else if (val == 1)
8736 		val = AUTONEG_ENABLE;
8737 	else
8738 		val = AUTONEG_AUTO;
8739 
8740 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8741 	    "t4aneg");
8742 	if (rc)
8743 		return (rc);
8744 	PORT_LOCK(pi);
8745 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8746 		rc = ENOTSUP;
8747 		goto done;
8748 	}
8749 	lc->requested_aneg = val;
8750 	if (!hw_off_limits(sc)) {
8751 		fixup_link_config(pi);
8752 		if (pi->up_vis > 0)
8753 			rc = apply_link_config(pi);
8754 		set_current_media(pi);
8755 	}
8756 done:
8757 	PORT_UNLOCK(pi);
8758 	end_synchronized_op(sc, 0);
8759 	return (rc);
8760 }
8761 
8762 static int
8763 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8764 {
8765 	struct port_info *pi = arg1;
8766 	struct adapter *sc = pi->adapter;
8767 	struct link_config *lc = &pi->link_cfg;
8768 	int rc, val;
8769 
8770 	val = lc->force_fec;
8771 	MPASS(val >= -1 && val <= 1);
8772 	rc = sysctl_handle_int(oidp, &val, 0, req);
8773 	if (rc != 0 || req->newptr == NULL)
8774 		return (rc);
8775 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8776 		return (ENOTSUP);
8777 	if (val < -1 || val > 1)
8778 		return (EINVAL);
8779 
8780 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8781 	if (rc)
8782 		return (rc);
8783 	PORT_LOCK(pi);
8784 	lc->force_fec = val;
8785 	if (!hw_off_limits(sc)) {
8786 		fixup_link_config(pi);
8787 		if (pi->up_vis > 0)
8788 			rc = apply_link_config(pi);
8789 	}
8790 	PORT_UNLOCK(pi);
8791 	end_synchronized_op(sc, 0);
8792 	return (rc);
8793 }
8794 
8795 static int
8796 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8797 {
8798 	struct adapter *sc = arg1;
8799 	int rc, reg = arg2;
8800 	uint64_t val;
8801 
8802 	mtx_lock(&sc->reg_lock);
8803 	if (hw_off_limits(sc))
8804 		rc = ENXIO;
8805 	else {
8806 		rc = 0;
8807 		val = t4_read_reg64(sc, reg);
8808 	}
8809 	mtx_unlock(&sc->reg_lock);
8810 	if (rc == 0)
8811 		rc = sysctl_handle_64(oidp, &val, 0, req);
8812 	return (rc);
8813 }
8814 
8815 static int
8816 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8817 {
8818 	struct adapter *sc = arg1;
8819 	int rc, t;
8820 	uint32_t param, val;
8821 
8822 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8823 	if (rc)
8824 		return (rc);
8825 	if (hw_off_limits(sc))
8826 		rc = ENXIO;
8827 	else {
8828 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8829 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8830 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8831 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8832 	}
8833 	end_synchronized_op(sc, 0);
8834 	if (rc)
8835 		return (rc);
8836 
8837 	/* unknown is returned as 0 but we display -1 in that case */
8838 	t = val == 0 ? -1 : val;
8839 
8840 	rc = sysctl_handle_int(oidp, &t, 0, req);
8841 	return (rc);
8842 }
8843 
8844 static int
8845 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8846 {
8847 	struct adapter *sc = arg1;
8848 	int rc;
8849 	uint32_t param, val;
8850 
8851 	if (sc->params.core_vdd == 0) {
8852 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8853 		    "t4vdd");
8854 		if (rc)
8855 			return (rc);
8856 		if (hw_off_limits(sc))
8857 			rc = ENXIO;
8858 		else {
8859 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8860 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8861 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8862 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8863 			    &param, &val);
8864 		}
8865 		end_synchronized_op(sc, 0);
8866 		if (rc)
8867 			return (rc);
8868 		sc->params.core_vdd = val;
8869 	}
8870 
8871 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8872 }
8873 
8874 static int
8875 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8876 {
8877 	struct adapter *sc = arg1;
8878 	int rc, v;
8879 	uint32_t param, val;
8880 
8881 	v = sc->sensor_resets;
8882 	rc = sysctl_handle_int(oidp, &v, 0, req);
8883 	if (rc != 0 || req->newptr == NULL || v <= 0)
8884 		return (rc);
8885 
8886 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8887 	    chip_id(sc) < CHELSIO_T5)
8888 		return (ENOTSUP);
8889 
8890 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8891 	if (rc)
8892 		return (rc);
8893 	if (hw_off_limits(sc))
8894 		rc = ENXIO;
8895 	else {
8896 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8897 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8898 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8899 		val = 1;
8900 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8901 	}
8902 	end_synchronized_op(sc, 0);
8903 	if (rc == 0)
8904 		sc->sensor_resets++;
8905 	return (rc);
8906 }
8907 
8908 static int
8909 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8910 {
8911 	struct adapter *sc = arg1;
8912 	struct sbuf *sb;
8913 	int rc;
8914 	uint32_t param, val;
8915 
8916 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8917 	if (rc)
8918 		return (rc);
8919 	if (hw_off_limits(sc))
8920 		rc = ENXIO;
8921 	else {
8922 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8923 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8924 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8925 	}
8926 	end_synchronized_op(sc, 0);
8927 	if (rc)
8928 		return (rc);
8929 
8930 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8931 	if (sb == NULL)
8932 		return (ENOMEM);
8933 
8934 	if (val == 0xffffffff) {
8935 		/* Only debug and custom firmwares report load averages. */
8936 		sbuf_printf(sb, "not available");
8937 	} else {
8938 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8939 		    (val >> 16) & 0xff);
8940 	}
8941 	rc = sbuf_finish(sb);
8942 	sbuf_delete(sb);
8943 
8944 	return (rc);
8945 }
8946 
8947 static int
8948 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8949 {
8950 	struct adapter *sc = arg1;
8951 	struct sbuf *sb;
8952 	int rc, i;
8953 	uint16_t incr[NMTUS][NCCTRL_WIN];
8954 	static const char *dec_fac[] = {
8955 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8956 		"0.9375"
8957 	};
8958 
8959 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8960 	if (sb == NULL)
8961 		return (ENOMEM);
8962 
8963 	rc = 0;
8964 	mtx_lock(&sc->reg_lock);
8965 	if (hw_off_limits(sc))
8966 		rc = ENXIO;
8967 	else
8968 		t4_read_cong_tbl(sc, incr);
8969 	mtx_unlock(&sc->reg_lock);
8970 	if (rc)
8971 		goto done;
8972 
8973 	for (i = 0; i < NCCTRL_WIN; ++i) {
8974 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8975 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8976 		    incr[5][i], incr[6][i], incr[7][i]);
8977 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8978 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8979 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8980 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8981 	}
8982 
8983 	rc = sbuf_finish(sb);
8984 done:
8985 	sbuf_delete(sb);
8986 	return (rc);
8987 }
8988 
8989 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8990 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8991 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8992 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8993 };
8994 
8995 static int
8996 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8997 {
8998 	struct adapter *sc = arg1;
8999 	struct sbuf *sb;
9000 	int rc, i, n, qid = arg2;
9001 	uint32_t *buf, *p;
9002 	char *qtype;
9003 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
9004 
9005 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
9006 	    ("%s: bad qid %d\n", __func__, qid));
9007 
9008 	if (qid < CIM_NUM_IBQ) {
9009 		/* inbound queue */
9010 		qtype = "IBQ";
9011 		n = 4 * CIM_IBQ_SIZE;
9012 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9013 		mtx_lock(&sc->reg_lock);
9014 		if (hw_off_limits(sc))
9015 			rc = -ENXIO;
9016 		else
9017 			rc = t4_read_cim_ibq(sc, qid, buf, n);
9018 		mtx_unlock(&sc->reg_lock);
9019 	} else {
9020 		/* outbound queue */
9021 		qtype = "OBQ";
9022 		qid -= CIM_NUM_IBQ;
9023 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
9024 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
9025 		mtx_lock(&sc->reg_lock);
9026 		if (hw_off_limits(sc))
9027 			rc = -ENXIO;
9028 		else
9029 			rc = t4_read_cim_obq(sc, qid, buf, n);
9030 		mtx_unlock(&sc->reg_lock);
9031 	}
9032 
9033 	if (rc < 0) {
9034 		rc = -rc;
9035 		goto done;
9036 	}
9037 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9038 
9039 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9040 	if (sb == NULL) {
9041 		rc = ENOMEM;
9042 		goto done;
9043 	}
9044 
9045 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
9046 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9047 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9048 		    p[2], p[3]);
9049 
9050 	rc = sbuf_finish(sb);
9051 	sbuf_delete(sb);
9052 done:
9053 	free(buf, M_CXGBE);
9054 	return (rc);
9055 }
9056 
9057 static void
9058 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9059 {
9060 	uint32_t *p;
9061 
9062 	sbuf_printf(sb, "Status   Data      PC%s",
9063 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9064 	    "     LS0Stat  LS0Addr             LS0Data");
9065 
9066 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9067 		if (cfg & F_UPDBGLACAPTPCONLY) {
9068 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9069 			    p[6], p[7]);
9070 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9071 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9072 			    p[4] & 0xff, p[5] >> 8);
9073 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9074 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9075 			    p[1] & 0xf, p[2] >> 4);
9076 		} else {
9077 			sbuf_printf(sb,
9078 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9079 			    "%08x%08x%08x%08x",
9080 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9081 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9082 			    p[6], p[7]);
9083 		}
9084 	}
9085 }
9086 
9087 static void
9088 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9089 {
9090 	uint32_t *p;
9091 
9092 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9093 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9094 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9095 
9096 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9097 		if (cfg & F_UPDBGLACAPTPCONLY) {
9098 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9099 			    p[3] & 0xff, p[2], p[1], p[0]);
9100 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9101 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9102 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9103 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9104 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9105 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9106 			    p[6] >> 16);
9107 		} else {
9108 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9109 			    "%08x %08x %08x %08x %08x %08x",
9110 			    (p[9] >> 16) & 0xff,
9111 			    p[9] & 0xffff, p[8] >> 16,
9112 			    p[8] & 0xffff, p[7] >> 16,
9113 			    p[7] & 0xffff, p[6] >> 16,
9114 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9115 		}
9116 	}
9117 }
9118 
9119 static int
9120 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9121 {
9122 	uint32_t cfg, *buf;
9123 	int rc;
9124 
9125 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9126 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9127 	    M_ZERO | flags);
9128 	if (buf == NULL)
9129 		return (ENOMEM);
9130 
9131 	mtx_lock(&sc->reg_lock);
9132 	if (hw_off_limits(sc))
9133 		rc = ENXIO;
9134 	else {
9135 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9136 		if (rc == 0)
9137 			rc = -t4_cim_read_la(sc, buf, NULL);
9138 	}
9139 	mtx_unlock(&sc->reg_lock);
9140 	if (rc == 0) {
9141 		if (chip_id(sc) < CHELSIO_T6)
9142 			sbuf_cim_la4(sc, sb, buf, cfg);
9143 		else
9144 			sbuf_cim_la6(sc, sb, buf, cfg);
9145 	}
9146 	free(buf, M_CXGBE);
9147 	return (rc);
9148 }
9149 
9150 static int
9151 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9152 {
9153 	struct adapter *sc = arg1;
9154 	struct sbuf *sb;
9155 	int rc;
9156 
9157 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9158 	if (sb == NULL)
9159 		return (ENOMEM);
9160 
9161 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9162 	if (rc == 0)
9163 		rc = sbuf_finish(sb);
9164 	sbuf_delete(sb);
9165 	return (rc);
9166 }
9167 
9168 static void
9169 dump_cim_regs(struct adapter *sc)
9170 {
9171 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9172 	    device_get_nameunit(sc->dev),
9173 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9174 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9175 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9176 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9177 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9178 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9179 	    device_get_nameunit(sc->dev),
9180 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9181 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9182 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9183 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9184 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9185 }
9186 
9187 static void
9188 dump_cimla(struct adapter *sc)
9189 {
9190 	struct sbuf sb;
9191 	int rc;
9192 
9193 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9194 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9195 		    device_get_nameunit(sc->dev));
9196 		return;
9197 	}
9198 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9199 	if (rc == 0) {
9200 		rc = sbuf_finish(&sb);
9201 		if (rc == 0) {
9202 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9203 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9204 		}
9205 	}
9206 	sbuf_delete(&sb);
9207 }
9208 
9209 void
9210 t4_os_cim_err(struct adapter *sc)
9211 {
9212 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9213 }
9214 
9215 static int
9216 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9217 {
9218 	struct adapter *sc = arg1;
9219 	u_int i;
9220 	struct sbuf *sb;
9221 	uint32_t *buf, *p;
9222 	int rc;
9223 
9224 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9225 	if (sb == NULL)
9226 		return (ENOMEM);
9227 
9228 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9229 	    M_ZERO | M_WAITOK);
9230 
9231 	rc = 0;
9232 	mtx_lock(&sc->reg_lock);
9233 	if (hw_off_limits(sc))
9234 		rc = ENXIO;
9235 	else
9236 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9237 	mtx_unlock(&sc->reg_lock);
9238 	if (rc)
9239 		goto done;
9240 
9241 	p = buf;
9242 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9243 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9244 		    p[1], p[0]);
9245 	}
9246 
9247 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9248 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9249 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9250 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9251 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9252 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9253 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9254 		    p[0] & 1);
9255 	}
9256 	rc = sbuf_finish(sb);
9257 done:
9258 	sbuf_delete(sb);
9259 	free(buf, M_CXGBE);
9260 	return (rc);
9261 }
9262 
9263 static int
9264 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9265 {
9266 	struct adapter *sc = arg1;
9267 	u_int i;
9268 	struct sbuf *sb;
9269 	uint32_t *buf, *p;
9270 	int rc;
9271 
9272 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9273 	if (sb == NULL)
9274 		return (ENOMEM);
9275 
9276 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9277 	    M_ZERO | M_WAITOK);
9278 
9279 	rc = 0;
9280 	mtx_lock(&sc->reg_lock);
9281 	if (hw_off_limits(sc))
9282 		rc = ENXIO;
9283 	else
9284 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9285 	mtx_unlock(&sc->reg_lock);
9286 	if (rc)
9287 		goto done;
9288 
9289 	p = buf;
9290 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9291 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9292 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9293 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9294 		    p[4], p[3], p[2], p[1], p[0]);
9295 	}
9296 
9297 	sbuf_printf(sb, "\n\nCntl ID               Data");
9298 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9299 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9300 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9301 	}
9302 
9303 	rc = sbuf_finish(sb);
9304 done:
9305 	sbuf_delete(sb);
9306 	free(buf, M_CXGBE);
9307 	return (rc);
9308 }
9309 
9310 static int
9311 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9312 {
9313 	struct adapter *sc = arg1;
9314 	struct sbuf *sb;
9315 	int rc, i;
9316 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9317 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9318 	uint16_t thres[CIM_NUM_IBQ];
9319 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9320 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9321 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9322 
9323 	cim_num_obq = sc->chip_params->cim_num_obq;
9324 	if (is_t4(sc)) {
9325 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9326 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9327 	} else {
9328 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9329 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9330 	}
9331 	nq = CIM_NUM_IBQ + cim_num_obq;
9332 
9333 	mtx_lock(&sc->reg_lock);
9334 	if (hw_off_limits(sc))
9335 		rc = ENXIO;
9336 	else {
9337 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9338 		if (rc == 0) {
9339 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9340 			    obq_wr);
9341 			if (rc == 0)
9342 				t4_read_cimq_cfg(sc, base, size, thres);
9343 		}
9344 	}
9345 	mtx_unlock(&sc->reg_lock);
9346 	if (rc)
9347 		return (rc);
9348 
9349 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9350 	if (sb == NULL)
9351 		return (ENOMEM);
9352 
9353 	sbuf_printf(sb,
9354 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9355 
9356 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9357 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9358 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9359 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9360 		    G_QUEREMFLITS(p[2]) * 16);
9361 	for ( ; i < nq; i++, p += 4, wr += 2)
9362 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9363 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9364 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9365 		    G_QUEREMFLITS(p[2]) * 16);
9366 
9367 	rc = sbuf_finish(sb);
9368 	sbuf_delete(sb);
9369 
9370 	return (rc);
9371 }
9372 
9373 static int
9374 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9375 {
9376 	struct adapter *sc = arg1;
9377 	struct sbuf *sb;
9378 	int rc;
9379 	struct tp_cpl_stats stats;
9380 
9381 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9382 	if (sb == NULL)
9383 		return (ENOMEM);
9384 
9385 	rc = 0;
9386 	mtx_lock(&sc->reg_lock);
9387 	if (hw_off_limits(sc))
9388 		rc = ENXIO;
9389 	else
9390 		t4_tp_get_cpl_stats(sc, &stats, 0);
9391 	mtx_unlock(&sc->reg_lock);
9392 	if (rc)
9393 		goto done;
9394 
9395 	if (sc->chip_params->nchan > 2) {
9396 		sbuf_printf(sb, "                 channel 0  channel 1"
9397 		    "  channel 2  channel 3");
9398 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9399 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9400 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9401 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9402 	} else {
9403 		sbuf_printf(sb, "                 channel 0  channel 1");
9404 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9405 		    stats.req[0], stats.req[1]);
9406 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9407 		    stats.rsp[0], stats.rsp[1]);
9408 	}
9409 
9410 	rc = sbuf_finish(sb);
9411 done:
9412 	sbuf_delete(sb);
9413 	return (rc);
9414 }
9415 
9416 static int
9417 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9418 {
9419 	struct adapter *sc = arg1;
9420 	struct sbuf *sb;
9421 	int rc;
9422 	struct tp_usm_stats stats;
9423 
9424 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9425 	if (sb == NULL)
9426 		return (ENOMEM);
9427 
9428 	rc = 0;
9429 	mtx_lock(&sc->reg_lock);
9430 	if (hw_off_limits(sc))
9431 		rc = ENXIO;
9432 	else
9433 		t4_get_usm_stats(sc, &stats, 1);
9434 	mtx_unlock(&sc->reg_lock);
9435 	if (rc == 0) {
9436 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9437 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9438 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9439 		rc = sbuf_finish(sb);
9440 	}
9441 	sbuf_delete(sb);
9442 
9443 	return (rc);
9444 }
9445 
9446 static int
9447 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9448 {
9449 	struct adapter *sc = arg1;
9450 	struct sbuf *sb;
9451 	int rc;
9452 	struct tp_tid_stats stats;
9453 
9454 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9455 	if (sb == NULL)
9456 		return (ENOMEM);
9457 
9458 	rc = 0;
9459 	mtx_lock(&sc->reg_lock);
9460 	if (hw_off_limits(sc))
9461 		rc = ENXIO;
9462 	else
9463 		t4_tp_get_tid_stats(sc, &stats, 1);
9464 	mtx_unlock(&sc->reg_lock);
9465 	if (rc == 0) {
9466 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9467 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9468 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9469 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9470 		rc = sbuf_finish(sb);
9471 	}
9472 	sbuf_delete(sb);
9473 
9474 	return (rc);
9475 }
9476 
9477 static const char * const devlog_level_strings[] = {
9478 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9479 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9480 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9481 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9482 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9483 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9484 };
9485 
9486 static const char * const devlog_facility_strings[] = {
9487 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9488 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9489 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9490 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9491 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9492 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9493 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9494 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9495 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9496 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9497 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9498 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9499 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9500 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9501 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9502 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9503 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9504 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9505 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9506 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9507 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9508 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9509 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9510 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9511 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9512 };
9513 
9514 static int
9515 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9516 {
9517 	int i, j, rc, nentries, first = 0;
9518 	struct devlog_params *dparams = &sc->params.devlog;
9519 	struct fw_devlog_e *buf, *e;
9520 	uint64_t ftstamp = UINT64_MAX;
9521 
9522 	if (dparams->addr == 0)
9523 		return (ENXIO);
9524 
9525 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9526 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9527 	if (buf == NULL)
9528 		return (ENOMEM);
9529 
9530 	mtx_lock(&sc->reg_lock);
9531 	if (hw_off_limits(sc))
9532 		rc = ENXIO;
9533 	else
9534 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9535 		    dparams->size);
9536 	mtx_unlock(&sc->reg_lock);
9537 	if (rc != 0)
9538 		goto done;
9539 
9540 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9541 	for (i = 0; i < nentries; i++) {
9542 		e = &buf[i];
9543 
9544 		if (e->timestamp == 0)
9545 			break;	/* end */
9546 
9547 		e->timestamp = be64toh(e->timestamp);
9548 		e->seqno = be32toh(e->seqno);
9549 		for (j = 0; j < 8; j++)
9550 			e->params[j] = be32toh(e->params[j]);
9551 
9552 		if (e->timestamp < ftstamp) {
9553 			ftstamp = e->timestamp;
9554 			first = i;
9555 		}
9556 	}
9557 
9558 	if (buf[first].timestamp == 0)
9559 		goto done;	/* nothing in the log */
9560 
9561 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9562 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9563 
9564 	i = first;
9565 	do {
9566 		e = &buf[i];
9567 		if (e->timestamp == 0)
9568 			break;	/* end */
9569 
9570 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9571 		    e->seqno, e->timestamp,
9572 		    (e->level < nitems(devlog_level_strings) ?
9573 			devlog_level_strings[e->level] : "UNKNOWN"),
9574 		    (e->facility < nitems(devlog_facility_strings) ?
9575 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9576 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9577 		    e->params[2], e->params[3], e->params[4],
9578 		    e->params[5], e->params[6], e->params[7]);
9579 
9580 		if (++i == nentries)
9581 			i = 0;
9582 	} while (i != first);
9583 done:
9584 	free(buf, M_CXGBE);
9585 	return (rc);
9586 }
9587 
9588 static int
9589 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9590 {
9591 	struct adapter *sc = arg1;
9592 	int rc;
9593 	struct sbuf *sb;
9594 
9595 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9596 	if (sb == NULL)
9597 		return (ENOMEM);
9598 
9599 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9600 	if (rc == 0)
9601 		rc = sbuf_finish(sb);
9602 	sbuf_delete(sb);
9603 	return (rc);
9604 }
9605 
9606 static void
9607 dump_devlog(struct adapter *sc)
9608 {
9609 	int rc;
9610 	struct sbuf sb;
9611 
9612 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9613 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9614 		    device_get_nameunit(sc->dev));
9615 		return;
9616 	}
9617 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9618 	if (rc == 0) {
9619 		rc = sbuf_finish(&sb);
9620 		if (rc == 0) {
9621 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9622 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9623 		}
9624 	}
9625 	sbuf_delete(&sb);
9626 }
9627 
9628 static int
9629 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9630 {
9631 	struct adapter *sc = arg1;
9632 	struct sbuf *sb;
9633 	int rc;
9634 	struct tp_fcoe_stats stats[MAX_NCHAN];
9635 	int i, nchan = sc->chip_params->nchan;
9636 
9637 	rc = 0;
9638 	mtx_lock(&sc->reg_lock);
9639 	if (hw_off_limits(sc))
9640 		rc = ENXIO;
9641 	else {
9642 		for (i = 0; i < nchan; i++)
9643 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9644 	}
9645 	mtx_unlock(&sc->reg_lock);
9646 	if (rc != 0)
9647 		return (rc);
9648 
9649 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9650 	if (sb == NULL)
9651 		return (ENOMEM);
9652 
9653 	if (nchan > 2) {
9654 		sbuf_printf(sb, "                   channel 0        channel 1"
9655 		    "        channel 2        channel 3");
9656 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9657 		    stats[0].octets_ddp, stats[1].octets_ddp,
9658 		    stats[2].octets_ddp, stats[3].octets_ddp);
9659 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9660 		    stats[0].frames_ddp, stats[1].frames_ddp,
9661 		    stats[2].frames_ddp, stats[3].frames_ddp);
9662 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9663 		    stats[0].frames_drop, stats[1].frames_drop,
9664 		    stats[2].frames_drop, stats[3].frames_drop);
9665 	} else {
9666 		sbuf_printf(sb, "                   channel 0        channel 1");
9667 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9668 		    stats[0].octets_ddp, stats[1].octets_ddp);
9669 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9670 		    stats[0].frames_ddp, stats[1].frames_ddp);
9671 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9672 		    stats[0].frames_drop, stats[1].frames_drop);
9673 	}
9674 
9675 	rc = sbuf_finish(sb);
9676 	sbuf_delete(sb);
9677 
9678 	return (rc);
9679 }
9680 
9681 static int
9682 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9683 {
9684 	struct adapter *sc = arg1;
9685 	struct sbuf *sb;
9686 	int rc, i;
9687 	unsigned int map, kbps, ipg, mode;
9688 	unsigned int pace_tab[NTX_SCHED];
9689 
9690 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9691 	if (sb == NULL)
9692 		return (ENOMEM);
9693 
9694 	mtx_lock(&sc->reg_lock);
9695 	if (hw_off_limits(sc)) {
9696 		mtx_unlock(&sc->reg_lock);
9697 		rc = ENXIO;
9698 		goto done;
9699 	}
9700 
9701 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9702 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9703 	t4_read_pace_tbl(sc, pace_tab);
9704 	mtx_unlock(&sc->reg_lock);
9705 
9706 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9707 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9708 
9709 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9710 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9711 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9712 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9713 		if (kbps)
9714 			sbuf_printf(sb, "%9u     ", kbps);
9715 		else
9716 			sbuf_printf(sb, " disabled     ");
9717 
9718 		if (ipg)
9719 			sbuf_printf(sb, "%13u        ", ipg);
9720 		else
9721 			sbuf_printf(sb, "     disabled        ");
9722 
9723 		if (pace_tab[i])
9724 			sbuf_printf(sb, "%10u", pace_tab[i]);
9725 		else
9726 			sbuf_printf(sb, "  disabled");
9727 	}
9728 	rc = sbuf_finish(sb);
9729 done:
9730 	sbuf_delete(sb);
9731 	return (rc);
9732 }
9733 
9734 static int
9735 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9736 {
9737 	struct adapter *sc = arg1;
9738 	struct sbuf *sb;
9739 	int rc, i, j;
9740 	uint64_t *p0, *p1;
9741 	struct lb_port_stats s[2];
9742 	static const char *stat_name[] = {
9743 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9744 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9745 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9746 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9747 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9748 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9749 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9750 	};
9751 
9752 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9753 	if (sb == NULL)
9754 		return (ENOMEM);
9755 
9756 	memset(s, 0, sizeof(s));
9757 
9758 	rc = 0;
9759 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9760 		mtx_lock(&sc->reg_lock);
9761 		if (hw_off_limits(sc))
9762 			rc = ENXIO;
9763 		else {
9764 			t4_get_lb_stats(sc, i, &s[0]);
9765 			t4_get_lb_stats(sc, i + 1, &s[1]);
9766 		}
9767 		mtx_unlock(&sc->reg_lock);
9768 		if (rc != 0)
9769 			break;
9770 
9771 		p0 = &s[0].octets;
9772 		p1 = &s[1].octets;
9773 		sbuf_printf(sb, "%s                       Loopback %u"
9774 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9775 
9776 		for (j = 0; j < nitems(stat_name); j++)
9777 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9778 				   *p0++, *p1++);
9779 	}
9780 
9781 	if (rc == 0)
9782 		rc = sbuf_finish(sb);
9783 	sbuf_delete(sb);
9784 
9785 	return (rc);
9786 }
9787 
9788 static int
9789 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9790 {
9791 	int rc = 0;
9792 	struct port_info *pi = arg1;
9793 	struct link_config *lc = &pi->link_cfg;
9794 	struct sbuf *sb;
9795 
9796 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9797 	if (sb == NULL)
9798 		return (ENOMEM);
9799 
9800 	if (lc->link_ok || lc->link_down_rc == 255)
9801 		sbuf_printf(sb, "n/a");
9802 	else
9803 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9804 
9805 	rc = sbuf_finish(sb);
9806 	sbuf_delete(sb);
9807 
9808 	return (rc);
9809 }
9810 
9811 struct mem_desc {
9812 	u_int base;
9813 	u_int limit;
9814 	u_int idx;
9815 };
9816 
9817 static int
9818 mem_desc_cmp(const void *a, const void *b)
9819 {
9820 	const u_int v1 = ((const struct mem_desc *)a)->base;
9821 	const u_int v2 = ((const struct mem_desc *)b)->base;
9822 
9823 	if (v1 < v2)
9824 		return (-1);
9825 	else if (v1 > v2)
9826 		return (1);
9827 
9828 	return (0);
9829 }
9830 
9831 static void
9832 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9833     unsigned int to)
9834 {
9835 	unsigned int size;
9836 
9837 	if (from == to)
9838 		return;
9839 
9840 	size = to - from + 1;
9841 	if (size == 0)
9842 		return;
9843 
9844 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9845 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9846 }
9847 
9848 static int
9849 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9850 {
9851 	struct adapter *sc = arg1;
9852 	struct sbuf *sb;
9853 	int rc, i, n;
9854 	uint32_t lo, hi, used, free, alloc;
9855 	static const char *memory[] = {
9856 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9857 	};
9858 	static const char *region[] = {
9859 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9860 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9861 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9862 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9863 		"RQUDP region:", "PBL region:", "TXPBL region:",
9864 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9865 		"ULPTX state:", "On-chip queues:",
9866 	};
9867 	struct mem_desc avail[4];
9868 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9869 	struct mem_desc *md = mem;
9870 
9871 	rc = sysctl_wire_old_buffer(req, 0);
9872 	if (rc != 0)
9873 		return (rc);
9874 
9875 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9876 	if (sb == NULL)
9877 		return (ENOMEM);
9878 
9879 	for (i = 0; i < nitems(mem); i++) {
9880 		mem[i].limit = 0;
9881 		mem[i].idx = i;
9882 	}
9883 
9884 	mtx_lock(&sc->reg_lock);
9885 	if (hw_off_limits(sc)) {
9886 		rc = ENXIO;
9887 		goto done;
9888 	}
9889 
9890 	/* Find and sort the populated memory ranges */
9891 	i = 0;
9892 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9893 	if (lo & F_EDRAM0_ENABLE) {
9894 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9895 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9896 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9897 		avail[i].idx = 0;
9898 		i++;
9899 	}
9900 	if (lo & F_EDRAM1_ENABLE) {
9901 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9902 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9903 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9904 		avail[i].idx = 1;
9905 		i++;
9906 	}
9907 	if (lo & F_EXT_MEM_ENABLE) {
9908 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9909 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9910 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9911 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9912 		i++;
9913 	}
9914 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9915 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9916 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9917 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9918 		avail[i].idx = 4;
9919 		i++;
9920 	}
9921 	if (is_t6(sc) && lo & F_HMA_MUX) {
9922 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9923 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9924 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9925 		avail[i].idx = 5;
9926 		i++;
9927 	}
9928 	MPASS(i <= nitems(avail));
9929 	if (!i)                                    /* no memory available */
9930 		goto done;
9931 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9932 
9933 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9934 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9935 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9936 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9937 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9938 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9939 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9940 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9941 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9942 
9943 	/* the next few have explicit upper bounds */
9944 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9945 	md->limit = md->base - 1 +
9946 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9947 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9948 	md++;
9949 
9950 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9951 	md->limit = md->base - 1 +
9952 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9953 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9954 	md++;
9955 
9956 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9957 		if (chip_id(sc) <= CHELSIO_T5)
9958 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9959 		else
9960 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9961 		md->limit = 0;
9962 	} else {
9963 		md->base = 0;
9964 		md->idx = nitems(region);  /* hide it */
9965 	}
9966 	md++;
9967 
9968 #define ulp_region(reg) \
9969 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9970 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9971 
9972 	ulp_region(RX_ISCSI);
9973 	ulp_region(RX_TDDP);
9974 	ulp_region(TX_TPT);
9975 	ulp_region(RX_STAG);
9976 	ulp_region(RX_RQ);
9977 	ulp_region(RX_RQUDP);
9978 	ulp_region(RX_PBL);
9979 	ulp_region(TX_PBL);
9980 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9981 		ulp_region(RX_TLS_KEY);
9982 	}
9983 #undef ulp_region
9984 
9985 	md->base = 0;
9986 	if (is_t4(sc))
9987 		md->idx = nitems(region);
9988 	else {
9989 		uint32_t size = 0;
9990 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9991 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9992 
9993 		if (is_t5(sc)) {
9994 			if (sge_ctrl & F_VFIFO_ENABLE)
9995 				size = fifo_size << 2;
9996 		} else
9997 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9998 
9999 		if (size) {
10000 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
10001 			md->limit = md->base + size - 1;
10002 		} else
10003 			md->idx = nitems(region);
10004 	}
10005 	md++;
10006 
10007 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
10008 	md->limit = 0;
10009 	md++;
10010 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
10011 	md->limit = 0;
10012 	md++;
10013 
10014 	md->base = sc->vres.ocq.start;
10015 	if (sc->vres.ocq.size)
10016 		md->limit = md->base + sc->vres.ocq.size - 1;
10017 	else
10018 		md->idx = nitems(region);  /* hide it */
10019 	md++;
10020 
10021 	/* add any address-space holes, there can be up to 3 */
10022 	for (n = 0; n < i - 1; n++)
10023 		if (avail[n].limit < avail[n + 1].base)
10024 			(md++)->base = avail[n].limit;
10025 	if (avail[n].limit)
10026 		(md++)->base = avail[n].limit;
10027 
10028 	n = md - mem;
10029 	MPASS(n <= nitems(mem));
10030 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10031 
10032 	for (lo = 0; lo < i; lo++)
10033 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10034 				avail[lo].limit - 1);
10035 
10036 	sbuf_printf(sb, "\n");
10037 	for (i = 0; i < n; i++) {
10038 		if (mem[i].idx >= nitems(region))
10039 			continue;                        /* skip holes */
10040 		if (!mem[i].limit)
10041 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10042 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10043 				mem[i].limit);
10044 	}
10045 
10046 	sbuf_printf(sb, "\n");
10047 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10048 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10049 	mem_region_show(sb, "uP RAM:", lo, hi);
10050 
10051 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10052 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10053 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10054 
10055 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10056 	for (i = 0, free = 0; i < 2; i++)
10057 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10058 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10059 		   G_PMRXMAXPAGE(lo), free,
10060 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10061 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10062 
10063 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10064 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10065 	for (i = 0, free = 0; i < 4; i++)
10066 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10067 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10068 		   G_PMTXMAXPAGE(lo), free,
10069 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10070 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10071 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10072 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10073 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10074 
10075 	for (i = 0; i < 4; i++) {
10076 		if (chip_id(sc) > CHELSIO_T5)
10077 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10078 		else
10079 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10080 		if (is_t5(sc)) {
10081 			used = G_T5_USED(lo);
10082 			alloc = G_T5_ALLOC(lo);
10083 		} else {
10084 			used = G_USED(lo);
10085 			alloc = G_ALLOC(lo);
10086 		}
10087 		/* For T6 these are MAC buffer groups */
10088 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10089 		    i, used, alloc);
10090 	}
10091 	for (i = 0; i < sc->chip_params->nchan; i++) {
10092 		if (chip_id(sc) > CHELSIO_T5)
10093 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10094 		else
10095 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10096 		if (is_t5(sc)) {
10097 			used = G_T5_USED(lo);
10098 			alloc = G_T5_ALLOC(lo);
10099 		} else {
10100 			used = G_USED(lo);
10101 			alloc = G_ALLOC(lo);
10102 		}
10103 		/* For T6 these are MAC buffer groups */
10104 		sbuf_printf(sb,
10105 		    "\nLoopback %d using %u pages out of %u allocated",
10106 		    i, used, alloc);
10107 	}
10108 done:
10109 	mtx_unlock(&sc->reg_lock);
10110 	if (rc == 0)
10111 		rc = sbuf_finish(sb);
10112 	sbuf_delete(sb);
10113 	return (rc);
10114 }
10115 
10116 static inline void
10117 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10118 {
10119 	*mask = x | y;
10120 	y = htobe64(y);
10121 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10122 }
10123 
10124 static int
10125 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10126 {
10127 	struct adapter *sc = arg1;
10128 	struct sbuf *sb;
10129 	int rc, i;
10130 
10131 	MPASS(chip_id(sc) <= CHELSIO_T5);
10132 
10133 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10134 	if (sb == NULL)
10135 		return (ENOMEM);
10136 
10137 	sbuf_printf(sb,
10138 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10139 	    "  VF              Replication             P0 P1 P2 P3  ML");
10140 	rc = 0;
10141 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10142 		uint64_t tcamx, tcamy, mask;
10143 		uint32_t cls_lo, cls_hi;
10144 		uint8_t addr[ETHER_ADDR_LEN];
10145 
10146 		mtx_lock(&sc->reg_lock);
10147 		if (hw_off_limits(sc))
10148 			rc = ENXIO;
10149 		else {
10150 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10151 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10152 		}
10153 		mtx_unlock(&sc->reg_lock);
10154 		if (rc != 0)
10155 			break;
10156 		if (tcamx & tcamy)
10157 			continue;
10158 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10159 		mtx_lock(&sc->reg_lock);
10160 		if (hw_off_limits(sc))
10161 			rc = ENXIO;
10162 		else {
10163 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10164 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10165 		}
10166 		mtx_unlock(&sc->reg_lock);
10167 		if (rc != 0)
10168 			break;
10169 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10170 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10171 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10172 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10173 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10174 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10175 
10176 		if (cls_lo & F_REPLICATE) {
10177 			struct fw_ldst_cmd ldst_cmd;
10178 
10179 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10180 			ldst_cmd.op_to_addrspace =
10181 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10182 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10183 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10184 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10185 			ldst_cmd.u.mps.rplc.fid_idx =
10186 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10187 				V_FW_LDST_CMD_IDX(i));
10188 
10189 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10190 			    "t4mps");
10191 			if (rc)
10192 				break;
10193 			if (hw_off_limits(sc))
10194 				rc = ENXIO;
10195 			else
10196 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10197 				    sizeof(ldst_cmd), &ldst_cmd);
10198 			end_synchronized_op(sc, 0);
10199 			if (rc != 0)
10200 				break;
10201 			else {
10202 				sbuf_printf(sb, " %08x %08x %08x %08x",
10203 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10204 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10205 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10206 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10207 			}
10208 		} else
10209 			sbuf_printf(sb, "%36s", "");
10210 
10211 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10212 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10213 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10214 	}
10215 
10216 	if (rc)
10217 		(void) sbuf_finish(sb);
10218 	else
10219 		rc = sbuf_finish(sb);
10220 	sbuf_delete(sb);
10221 
10222 	return (rc);
10223 }
10224 
10225 static int
10226 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10227 {
10228 	struct adapter *sc = arg1;
10229 	struct sbuf *sb;
10230 	int rc, i;
10231 
10232 	MPASS(chip_id(sc) > CHELSIO_T5);
10233 
10234 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10235 	if (sb == NULL)
10236 		return (ENOMEM);
10237 
10238 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10239 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10240 	    "                           Replication"
10241 	    "                                    P0 P1 P2 P3  ML\n");
10242 
10243 	rc = 0;
10244 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10245 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10246 		uint16_t ivlan;
10247 		uint64_t tcamx, tcamy, val, mask;
10248 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10249 		uint8_t addr[ETHER_ADDR_LEN];
10250 
10251 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10252 		if (i < 256)
10253 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10254 		else
10255 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10256 		mtx_lock(&sc->reg_lock);
10257 		if (hw_off_limits(sc))
10258 			rc = ENXIO;
10259 		else {
10260 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10261 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10262 			tcamy = G_DMACH(val) << 32;
10263 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10264 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10265 		}
10266 		mtx_unlock(&sc->reg_lock);
10267 		if (rc != 0)
10268 			break;
10269 
10270 		lookup_type = G_DATALKPTYPE(data2);
10271 		port_num = G_DATAPORTNUM(data2);
10272 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10273 			/* Inner header VNI */
10274 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10275 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10276 			dip_hit = data2 & F_DATADIPHIT;
10277 			vlan_vld = 0;
10278 		} else {
10279 			vniy = 0;
10280 			dip_hit = 0;
10281 			vlan_vld = data2 & F_DATAVIDH2;
10282 			ivlan = G_VIDL(val);
10283 		}
10284 
10285 		ctl |= V_CTLXYBITSEL(1);
10286 		mtx_lock(&sc->reg_lock);
10287 		if (hw_off_limits(sc))
10288 			rc = ENXIO;
10289 		else {
10290 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10291 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10292 			tcamx = G_DMACH(val) << 32;
10293 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10294 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10295 		}
10296 		mtx_unlock(&sc->reg_lock);
10297 		if (rc != 0)
10298 			break;
10299 
10300 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10301 			/* Inner header VNI mask */
10302 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10303 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10304 		} else
10305 			vnix = 0;
10306 
10307 		if (tcamx & tcamy)
10308 			continue;
10309 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10310 
10311 		mtx_lock(&sc->reg_lock);
10312 		if (hw_off_limits(sc))
10313 			rc = ENXIO;
10314 		else {
10315 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10316 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10317 		}
10318 		mtx_unlock(&sc->reg_lock);
10319 		if (rc != 0)
10320 			break;
10321 
10322 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10323 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10324 			    "%012jx %06x %06x    -    -   %3c"
10325 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10326 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10327 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10328 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10329 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10330 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10331 		} else {
10332 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10333 			    "%012jx    -       -   ", i, addr[0], addr[1],
10334 			    addr[2], addr[3], addr[4], addr[5],
10335 			    (uintmax_t)mask);
10336 
10337 			if (vlan_vld)
10338 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10339 			else
10340 				sbuf_printf(sb, "  -    N     ");
10341 
10342 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10343 			    lookup_type ? 'I' : 'O', port_num,
10344 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10345 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10346 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10347 		}
10348 
10349 
10350 		if (cls_lo & F_T6_REPLICATE) {
10351 			struct fw_ldst_cmd ldst_cmd;
10352 
10353 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10354 			ldst_cmd.op_to_addrspace =
10355 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10356 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10357 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10358 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10359 			ldst_cmd.u.mps.rplc.fid_idx =
10360 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10361 				V_FW_LDST_CMD_IDX(i));
10362 
10363 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10364 			    "t6mps");
10365 			if (rc)
10366 				break;
10367 			if (hw_off_limits(sc))
10368 				rc = ENXIO;
10369 			else
10370 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10371 				    sizeof(ldst_cmd), &ldst_cmd);
10372 			end_synchronized_op(sc, 0);
10373 			if (rc != 0)
10374 				break;
10375 			else {
10376 				sbuf_printf(sb, " %08x %08x %08x %08x"
10377 				    " %08x %08x %08x %08x",
10378 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10379 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10380 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10381 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10382 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10383 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10384 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10385 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10386 			}
10387 		} else
10388 			sbuf_printf(sb, "%72s", "");
10389 
10390 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10391 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10392 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10393 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10394 	}
10395 
10396 	if (rc)
10397 		(void) sbuf_finish(sb);
10398 	else
10399 		rc = sbuf_finish(sb);
10400 	sbuf_delete(sb);
10401 
10402 	return (rc);
10403 }
10404 
10405 static int
10406 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10407 {
10408 	struct adapter *sc = arg1;
10409 	struct sbuf *sb;
10410 	int rc;
10411 	uint16_t mtus[NMTUS];
10412 
10413 	rc = 0;
10414 	mtx_lock(&sc->reg_lock);
10415 	if (hw_off_limits(sc))
10416 		rc = ENXIO;
10417 	else
10418 		t4_read_mtu_tbl(sc, mtus, NULL);
10419 	mtx_unlock(&sc->reg_lock);
10420 	if (rc != 0)
10421 		return (rc);
10422 
10423 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10424 	if (sb == NULL)
10425 		return (ENOMEM);
10426 
10427 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10428 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10429 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10430 	    mtus[14], mtus[15]);
10431 
10432 	rc = sbuf_finish(sb);
10433 	sbuf_delete(sb);
10434 
10435 	return (rc);
10436 }
10437 
10438 static int
10439 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10440 {
10441 	struct adapter *sc = arg1;
10442 	struct sbuf *sb;
10443 	int rc, i;
10444 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10445 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10446 	static const char *tx_stats[MAX_PM_NSTATS] = {
10447 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10448 		"Tx FIFO wait", NULL, "Tx latency"
10449 	};
10450 	static const char *rx_stats[MAX_PM_NSTATS] = {
10451 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10452 		"Rx FIFO wait", NULL, "Rx latency"
10453 	};
10454 
10455 	rc = 0;
10456 	mtx_lock(&sc->reg_lock);
10457 	if (hw_off_limits(sc))
10458 		rc = ENXIO;
10459 	else {
10460 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10461 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10462 	}
10463 	mtx_unlock(&sc->reg_lock);
10464 	if (rc != 0)
10465 		return (rc);
10466 
10467 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10468 	if (sb == NULL)
10469 		return (ENOMEM);
10470 
10471 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10472 	for (i = 0; i < 4; i++) {
10473 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10474 		    tx_cyc[i]);
10475 	}
10476 
10477 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10478 	for (i = 0; i < 4; i++) {
10479 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10480 		    rx_cyc[i]);
10481 	}
10482 
10483 	if (chip_id(sc) > CHELSIO_T5) {
10484 		sbuf_printf(sb,
10485 		    "\n              Total wait      Total occupancy");
10486 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10487 		    tx_cyc[i]);
10488 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10489 		    rx_cyc[i]);
10490 
10491 		i += 2;
10492 		MPASS(i < nitems(tx_stats));
10493 
10494 		sbuf_printf(sb,
10495 		    "\n                   Reads           Total wait");
10496 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10497 		    tx_cyc[i]);
10498 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10499 		    rx_cyc[i]);
10500 	}
10501 
10502 	rc = sbuf_finish(sb);
10503 	sbuf_delete(sb);
10504 
10505 	return (rc);
10506 }
10507 
10508 static int
10509 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10510 {
10511 	struct adapter *sc = arg1;
10512 	struct sbuf *sb;
10513 	int rc;
10514 	struct tp_rdma_stats stats;
10515 
10516 	rc = 0;
10517 	mtx_lock(&sc->reg_lock);
10518 	if (hw_off_limits(sc))
10519 		rc = ENXIO;
10520 	else
10521 		t4_tp_get_rdma_stats(sc, &stats, 0);
10522 	mtx_unlock(&sc->reg_lock);
10523 	if (rc != 0)
10524 		return (rc);
10525 
10526 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10527 	if (sb == NULL)
10528 		return (ENOMEM);
10529 
10530 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10531 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10532 
10533 	rc = sbuf_finish(sb);
10534 	sbuf_delete(sb);
10535 
10536 	return (rc);
10537 }
10538 
10539 static int
10540 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10541 {
10542 	struct adapter *sc = arg1;
10543 	struct sbuf *sb;
10544 	int rc;
10545 	struct tp_tcp_stats v4, v6;
10546 
10547 	rc = 0;
10548 	mtx_lock(&sc->reg_lock);
10549 	if (hw_off_limits(sc))
10550 		rc = ENXIO;
10551 	else
10552 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10553 	mtx_unlock(&sc->reg_lock);
10554 	if (rc != 0)
10555 		return (rc);
10556 
10557 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10558 	if (sb == NULL)
10559 		return (ENOMEM);
10560 
10561 	sbuf_printf(sb,
10562 	    "                                IP                 IPv6\n");
10563 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10564 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10565 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10566 	    v4.tcp_in_segs, v6.tcp_in_segs);
10567 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10568 	    v4.tcp_out_segs, v6.tcp_out_segs);
10569 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10570 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10571 
10572 	rc = sbuf_finish(sb);
10573 	sbuf_delete(sb);
10574 
10575 	return (rc);
10576 }
10577 
10578 static int
10579 sysctl_tids(SYSCTL_HANDLER_ARGS)
10580 {
10581 	struct adapter *sc = arg1;
10582 	struct sbuf *sb;
10583 	int rc;
10584 	uint32_t x, y;
10585 	struct tid_info *t = &sc->tids;
10586 
10587 	rc = 0;
10588 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10589 	if (sb == NULL)
10590 		return (ENOMEM);
10591 
10592 	if (t->natids) {
10593 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10594 		    t->atids_in_use);
10595 	}
10596 
10597 	if (t->nhpftids) {
10598 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10599 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10600 	}
10601 
10602 	if (t->ntids) {
10603 		bool hashen = false;
10604 
10605 		mtx_lock(&sc->reg_lock);
10606 		if (hw_off_limits(sc))
10607 			rc = ENXIO;
10608 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10609 			hashen = true;
10610 			if (chip_id(sc) <= CHELSIO_T5) {
10611 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10612 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10613 			} else {
10614 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10615 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10616 			}
10617 		}
10618 		mtx_unlock(&sc->reg_lock);
10619 		if (rc != 0)
10620 			goto done;
10621 
10622 		sbuf_printf(sb, "TID range: ");
10623 		if (hashen) {
10624 			if (x)
10625 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10626 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10627 		} else {
10628 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10629 			    t->ntids - 1);
10630 		}
10631 		sbuf_printf(sb, ", in use: %u\n",
10632 		    atomic_load_acq_int(&t->tids_in_use));
10633 	}
10634 
10635 	if (t->nstids) {
10636 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10637 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10638 	}
10639 
10640 	if (t->nftids) {
10641 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10642 		    t->ftid_end, t->ftids_in_use);
10643 	}
10644 
10645 	if (t->netids) {
10646 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10647 		    t->etid_base + t->netids - 1, t->etids_in_use);
10648 	}
10649 
10650 	mtx_lock(&sc->reg_lock);
10651 	if (hw_off_limits(sc))
10652 		rc = ENXIO;
10653 	else {
10654 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10655 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10656 	}
10657 	mtx_unlock(&sc->reg_lock);
10658 	if (rc != 0)
10659 		goto done;
10660 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10661 done:
10662 	if (rc == 0)
10663 		rc = sbuf_finish(sb);
10664 	else
10665 		(void)sbuf_finish(sb);
10666 	sbuf_delete(sb);
10667 
10668 	return (rc);
10669 }
10670 
10671 static int
10672 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10673 {
10674 	struct adapter *sc = arg1;
10675 	struct sbuf *sb;
10676 	int rc;
10677 	struct tp_err_stats stats;
10678 
10679 	rc = 0;
10680 	mtx_lock(&sc->reg_lock);
10681 	if (hw_off_limits(sc))
10682 		rc = ENXIO;
10683 	else
10684 		t4_tp_get_err_stats(sc, &stats, 0);
10685 	mtx_unlock(&sc->reg_lock);
10686 	if (rc != 0)
10687 		return (rc);
10688 
10689 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10690 	if (sb == NULL)
10691 		return (ENOMEM);
10692 
10693 	if (sc->chip_params->nchan > 2) {
10694 		sbuf_printf(sb, "                 channel 0  channel 1"
10695 		    "  channel 2  channel 3\n");
10696 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10697 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10698 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10699 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10700 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10701 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10702 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10703 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10704 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10705 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10706 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10707 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10708 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10709 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10710 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10711 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10712 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10713 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10714 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10715 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10716 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10717 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10718 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10719 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10720 	} else {
10721 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10722 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10723 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10724 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10725 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10726 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10727 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10728 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10729 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10730 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10731 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10732 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10733 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10734 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10735 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10736 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10737 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10738 	}
10739 
10740 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10741 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10742 
10743 	rc = sbuf_finish(sb);
10744 	sbuf_delete(sb);
10745 
10746 	return (rc);
10747 }
10748 
10749 static int
10750 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10751 {
10752 	struct adapter *sc = arg1;
10753 	struct sbuf *sb;
10754 	int rc;
10755 	struct tp_tnl_stats stats;
10756 
10757 	rc = 0;
10758 	mtx_lock(&sc->reg_lock);
10759 	if (hw_off_limits(sc))
10760 		rc = ENXIO;
10761 	else
10762 		t4_tp_get_tnl_stats(sc, &stats, 1);
10763 	mtx_unlock(&sc->reg_lock);
10764 	if (rc != 0)
10765 		return (rc);
10766 
10767 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10768 	if (sb == NULL)
10769 		return (ENOMEM);
10770 
10771 	if (sc->chip_params->nchan > 2) {
10772 		sbuf_printf(sb, "           channel 0  channel 1"
10773 		    "  channel 2  channel 3\n");
10774 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10775 		    stats.out_pkt[0], stats.out_pkt[1],
10776 		    stats.out_pkt[2], stats.out_pkt[3]);
10777 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10778 		    stats.in_pkt[0], stats.in_pkt[1],
10779 		    stats.in_pkt[2], stats.in_pkt[3]);
10780 	} else {
10781 		sbuf_printf(sb, "           channel 0  channel 1\n");
10782 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10783 		    stats.out_pkt[0], stats.out_pkt[1]);
10784 		sbuf_printf(sb, "InPkts:   %10u %10u",
10785 		    stats.in_pkt[0], stats.in_pkt[1]);
10786 	}
10787 
10788 	rc = sbuf_finish(sb);
10789 	sbuf_delete(sb);
10790 
10791 	return (rc);
10792 }
10793 
10794 static int
10795 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10796 {
10797 	struct adapter *sc = arg1;
10798 	struct tp_params *tpp = &sc->params.tp;
10799 	u_int mask;
10800 	int rc;
10801 
10802 	mask = tpp->la_mask >> 16;
10803 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10804 	if (rc != 0 || req->newptr == NULL)
10805 		return (rc);
10806 	if (mask > 0xffff)
10807 		return (EINVAL);
10808 	mtx_lock(&sc->reg_lock);
10809 	if (hw_off_limits(sc))
10810 		rc = ENXIO;
10811 	else {
10812 		tpp->la_mask = mask << 16;
10813 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10814 		    tpp->la_mask);
10815 	}
10816 	mtx_unlock(&sc->reg_lock);
10817 
10818 	return (rc);
10819 }
10820 
10821 struct field_desc {
10822 	const char *name;
10823 	u_int start;
10824 	u_int width;
10825 };
10826 
10827 static void
10828 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10829 {
10830 	char buf[32];
10831 	int line_size = 0;
10832 
10833 	while (f->name) {
10834 		uint64_t mask = (1ULL << f->width) - 1;
10835 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10836 		    ((uintmax_t)v >> f->start) & mask);
10837 
10838 		if (line_size + len >= 79) {
10839 			line_size = 8;
10840 			sbuf_printf(sb, "\n        ");
10841 		}
10842 		sbuf_printf(sb, "%s ", buf);
10843 		line_size += len + 1;
10844 		f++;
10845 	}
10846 	sbuf_printf(sb, "\n");
10847 }
10848 
10849 static const struct field_desc tp_la0[] = {
10850 	{ "RcfOpCodeOut", 60, 4 },
10851 	{ "State", 56, 4 },
10852 	{ "WcfState", 52, 4 },
10853 	{ "RcfOpcSrcOut", 50, 2 },
10854 	{ "CRxError", 49, 1 },
10855 	{ "ERxError", 48, 1 },
10856 	{ "SanityFailed", 47, 1 },
10857 	{ "SpuriousMsg", 46, 1 },
10858 	{ "FlushInputMsg", 45, 1 },
10859 	{ "FlushInputCpl", 44, 1 },
10860 	{ "RssUpBit", 43, 1 },
10861 	{ "RssFilterHit", 42, 1 },
10862 	{ "Tid", 32, 10 },
10863 	{ "InitTcb", 31, 1 },
10864 	{ "LineNumber", 24, 7 },
10865 	{ "Emsg", 23, 1 },
10866 	{ "EdataOut", 22, 1 },
10867 	{ "Cmsg", 21, 1 },
10868 	{ "CdataOut", 20, 1 },
10869 	{ "EreadPdu", 19, 1 },
10870 	{ "CreadPdu", 18, 1 },
10871 	{ "TunnelPkt", 17, 1 },
10872 	{ "RcfPeerFin", 16, 1 },
10873 	{ "RcfReasonOut", 12, 4 },
10874 	{ "TxCchannel", 10, 2 },
10875 	{ "RcfTxChannel", 8, 2 },
10876 	{ "RxEchannel", 6, 2 },
10877 	{ "RcfRxChannel", 5, 1 },
10878 	{ "RcfDataOutSrdy", 4, 1 },
10879 	{ "RxDvld", 3, 1 },
10880 	{ "RxOoDvld", 2, 1 },
10881 	{ "RxCongestion", 1, 1 },
10882 	{ "TxCongestion", 0, 1 },
10883 	{ NULL }
10884 };
10885 
10886 static const struct field_desc tp_la1[] = {
10887 	{ "CplCmdIn", 56, 8 },
10888 	{ "CplCmdOut", 48, 8 },
10889 	{ "ESynOut", 47, 1 },
10890 	{ "EAckOut", 46, 1 },
10891 	{ "EFinOut", 45, 1 },
10892 	{ "ERstOut", 44, 1 },
10893 	{ "SynIn", 43, 1 },
10894 	{ "AckIn", 42, 1 },
10895 	{ "FinIn", 41, 1 },
10896 	{ "RstIn", 40, 1 },
10897 	{ "DataIn", 39, 1 },
10898 	{ "DataInVld", 38, 1 },
10899 	{ "PadIn", 37, 1 },
10900 	{ "RxBufEmpty", 36, 1 },
10901 	{ "RxDdp", 35, 1 },
10902 	{ "RxFbCongestion", 34, 1 },
10903 	{ "TxFbCongestion", 33, 1 },
10904 	{ "TxPktSumSrdy", 32, 1 },
10905 	{ "RcfUlpType", 28, 4 },
10906 	{ "Eread", 27, 1 },
10907 	{ "Ebypass", 26, 1 },
10908 	{ "Esave", 25, 1 },
10909 	{ "Static0", 24, 1 },
10910 	{ "Cread", 23, 1 },
10911 	{ "Cbypass", 22, 1 },
10912 	{ "Csave", 21, 1 },
10913 	{ "CPktOut", 20, 1 },
10914 	{ "RxPagePoolFull", 18, 2 },
10915 	{ "RxLpbkPkt", 17, 1 },
10916 	{ "TxLpbkPkt", 16, 1 },
10917 	{ "RxVfValid", 15, 1 },
10918 	{ "SynLearned", 14, 1 },
10919 	{ "SetDelEntry", 13, 1 },
10920 	{ "SetInvEntry", 12, 1 },
10921 	{ "CpcmdDvld", 11, 1 },
10922 	{ "CpcmdSave", 10, 1 },
10923 	{ "RxPstructsFull", 8, 2 },
10924 	{ "EpcmdDvld", 7, 1 },
10925 	{ "EpcmdFlush", 6, 1 },
10926 	{ "EpcmdTrimPrefix", 5, 1 },
10927 	{ "EpcmdTrimPostfix", 4, 1 },
10928 	{ "ERssIp4Pkt", 3, 1 },
10929 	{ "ERssIp6Pkt", 2, 1 },
10930 	{ "ERssTcpUdpPkt", 1, 1 },
10931 	{ "ERssFceFipPkt", 0, 1 },
10932 	{ NULL }
10933 };
10934 
10935 static const struct field_desc tp_la2[] = {
10936 	{ "CplCmdIn", 56, 8 },
10937 	{ "MpsVfVld", 55, 1 },
10938 	{ "MpsPf", 52, 3 },
10939 	{ "MpsVf", 44, 8 },
10940 	{ "SynIn", 43, 1 },
10941 	{ "AckIn", 42, 1 },
10942 	{ "FinIn", 41, 1 },
10943 	{ "RstIn", 40, 1 },
10944 	{ "DataIn", 39, 1 },
10945 	{ "DataInVld", 38, 1 },
10946 	{ "PadIn", 37, 1 },
10947 	{ "RxBufEmpty", 36, 1 },
10948 	{ "RxDdp", 35, 1 },
10949 	{ "RxFbCongestion", 34, 1 },
10950 	{ "TxFbCongestion", 33, 1 },
10951 	{ "TxPktSumSrdy", 32, 1 },
10952 	{ "RcfUlpType", 28, 4 },
10953 	{ "Eread", 27, 1 },
10954 	{ "Ebypass", 26, 1 },
10955 	{ "Esave", 25, 1 },
10956 	{ "Static0", 24, 1 },
10957 	{ "Cread", 23, 1 },
10958 	{ "Cbypass", 22, 1 },
10959 	{ "Csave", 21, 1 },
10960 	{ "CPktOut", 20, 1 },
10961 	{ "RxPagePoolFull", 18, 2 },
10962 	{ "RxLpbkPkt", 17, 1 },
10963 	{ "TxLpbkPkt", 16, 1 },
10964 	{ "RxVfValid", 15, 1 },
10965 	{ "SynLearned", 14, 1 },
10966 	{ "SetDelEntry", 13, 1 },
10967 	{ "SetInvEntry", 12, 1 },
10968 	{ "CpcmdDvld", 11, 1 },
10969 	{ "CpcmdSave", 10, 1 },
10970 	{ "RxPstructsFull", 8, 2 },
10971 	{ "EpcmdDvld", 7, 1 },
10972 	{ "EpcmdFlush", 6, 1 },
10973 	{ "EpcmdTrimPrefix", 5, 1 },
10974 	{ "EpcmdTrimPostfix", 4, 1 },
10975 	{ "ERssIp4Pkt", 3, 1 },
10976 	{ "ERssIp6Pkt", 2, 1 },
10977 	{ "ERssTcpUdpPkt", 1, 1 },
10978 	{ "ERssFceFipPkt", 0, 1 },
10979 	{ NULL }
10980 };
10981 
10982 static void
10983 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10984 {
10985 
10986 	field_desc_show(sb, *p, tp_la0);
10987 }
10988 
10989 static void
10990 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10991 {
10992 
10993 	if (idx)
10994 		sbuf_printf(sb, "\n");
10995 	field_desc_show(sb, p[0], tp_la0);
10996 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10997 		field_desc_show(sb, p[1], tp_la0);
10998 }
10999 
11000 static void
11001 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11002 {
11003 
11004 	if (idx)
11005 		sbuf_printf(sb, "\n");
11006 	field_desc_show(sb, p[0], tp_la0);
11007 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11008 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11009 }
11010 
11011 static int
11012 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11013 {
11014 	struct adapter *sc = arg1;
11015 	struct sbuf *sb;
11016 	uint64_t *buf, *p;
11017 	int rc;
11018 	u_int i, inc;
11019 	void (*show_func)(struct sbuf *, uint64_t *, int);
11020 
11021 	rc = 0;
11022 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11023 	if (sb == NULL)
11024 		return (ENOMEM);
11025 
11026 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11027 
11028 	mtx_lock(&sc->reg_lock);
11029 	if (hw_off_limits(sc))
11030 		rc = ENXIO;
11031 	else {
11032 		t4_tp_read_la(sc, buf, NULL);
11033 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11034 		case 2:
11035 			inc = 2;
11036 			show_func = tp_la_show2;
11037 			break;
11038 		case 3:
11039 			inc = 2;
11040 			show_func = tp_la_show3;
11041 			break;
11042 		default:
11043 			inc = 1;
11044 			show_func = tp_la_show;
11045 		}
11046 	}
11047 	mtx_unlock(&sc->reg_lock);
11048 	if (rc != 0)
11049 		goto done;
11050 
11051 	p = buf;
11052 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11053 		(*show_func)(sb, p, i);
11054 	rc = sbuf_finish(sb);
11055 done:
11056 	sbuf_delete(sb);
11057 	free(buf, M_CXGBE);
11058 	return (rc);
11059 }
11060 
11061 static int
11062 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11063 {
11064 	struct adapter *sc = arg1;
11065 	struct sbuf *sb;
11066 	int rc;
11067 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11068 
11069 	rc = 0;
11070 	mtx_lock(&sc->reg_lock);
11071 	if (hw_off_limits(sc))
11072 		rc = ENXIO;
11073 	else
11074 		t4_get_chan_txrate(sc, nrate, orate);
11075 	mtx_unlock(&sc->reg_lock);
11076 	if (rc != 0)
11077 		return (rc);
11078 
11079 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11080 	if (sb == NULL)
11081 		return (ENOMEM);
11082 
11083 	if (sc->chip_params->nchan > 2) {
11084 		sbuf_printf(sb, "              channel 0   channel 1"
11085 		    "   channel 2   channel 3\n");
11086 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11087 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11088 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11089 		    orate[0], orate[1], orate[2], orate[3]);
11090 	} else {
11091 		sbuf_printf(sb, "              channel 0   channel 1\n");
11092 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11093 		    nrate[0], nrate[1]);
11094 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11095 		    orate[0], orate[1]);
11096 	}
11097 
11098 	rc = sbuf_finish(sb);
11099 	sbuf_delete(sb);
11100 
11101 	return (rc);
11102 }
11103 
11104 static int
11105 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11106 {
11107 	struct adapter *sc = arg1;
11108 	struct sbuf *sb;
11109 	uint32_t *buf, *p;
11110 	int rc, i;
11111 
11112 	rc = 0;
11113 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11114 	if (sb == NULL)
11115 		return (ENOMEM);
11116 
11117 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11118 	    M_ZERO | M_WAITOK);
11119 
11120 	mtx_lock(&sc->reg_lock);
11121 	if (hw_off_limits(sc))
11122 		rc = ENXIO;
11123 	else
11124 		t4_ulprx_read_la(sc, buf);
11125 	mtx_unlock(&sc->reg_lock);
11126 	if (rc != 0)
11127 		goto done;
11128 
11129 	p = buf;
11130 	sbuf_printf(sb, "      Pcmd        Type   Message"
11131 	    "                Data");
11132 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11133 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11134 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11135 	}
11136 	rc = sbuf_finish(sb);
11137 done:
11138 	sbuf_delete(sb);
11139 	free(buf, M_CXGBE);
11140 	return (rc);
11141 }
11142 
11143 static int
11144 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11145 {
11146 	struct adapter *sc = arg1;
11147 	struct sbuf *sb;
11148 	int rc;
11149 	uint32_t cfg, s1, s2;
11150 
11151 	MPASS(chip_id(sc) >= CHELSIO_T5);
11152 
11153 	rc = 0;
11154 	mtx_lock(&sc->reg_lock);
11155 	if (hw_off_limits(sc))
11156 		rc = ENXIO;
11157 	else {
11158 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11159 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11160 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11161 	}
11162 	mtx_unlock(&sc->reg_lock);
11163 	if (rc != 0)
11164 		return (rc);
11165 
11166 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11167 	if (sb == NULL)
11168 		return (ENOMEM);
11169 
11170 	if (G_STATSOURCE_T5(cfg) == 7) {
11171 		int mode;
11172 
11173 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11174 		if (mode == 0)
11175 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11176 		else if (mode == 1)
11177 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11178 		else
11179 			sbuf_printf(sb, "unknown mode %d", mode);
11180 	}
11181 	rc = sbuf_finish(sb);
11182 	sbuf_delete(sb);
11183 
11184 	return (rc);
11185 }
11186 
11187 static int
11188 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11189 {
11190 	struct adapter *sc = arg1;
11191 	enum cpu_sets op = arg2;
11192 	cpuset_t cpuset;
11193 	struct sbuf *sb;
11194 	int i, rc;
11195 
11196 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11197 
11198 	CPU_ZERO(&cpuset);
11199 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11200 	if (rc != 0)
11201 		return (rc);
11202 
11203 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11204 	if (sb == NULL)
11205 		return (ENOMEM);
11206 
11207 	CPU_FOREACH(i)
11208 		sbuf_printf(sb, "%d ", i);
11209 	rc = sbuf_finish(sb);
11210 	sbuf_delete(sb);
11211 
11212 	return (rc);
11213 }
11214 
11215 static int
11216 sysctl_reset(SYSCTL_HANDLER_ARGS)
11217 {
11218 	struct adapter *sc = arg1;
11219 	u_int val;
11220 	int rc;
11221 
11222 	val = atomic_load_int(&sc->num_resets);
11223 	rc = sysctl_handle_int(oidp, &val, 0, req);
11224 	if (rc != 0 || req->newptr == NULL)
11225 		return (rc);
11226 
11227 	if (val == 0) {
11228 		/* Zero out the counter that tracks reset. */
11229 		atomic_store_int(&sc->num_resets, 0);
11230 		return (0);
11231 	}
11232 
11233 	if (val != 1)
11234 		return (EINVAL);	/* 0 or 1 are the only legal values */
11235 
11236 	if (hw_off_limits(sc))		/* harmless race */
11237 		return (EALREADY);
11238 
11239 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11240 	return (0);
11241 }
11242 
11243 #ifdef TCP_OFFLOAD
11244 static int
11245 sysctl_tls(SYSCTL_HANDLER_ARGS)
11246 {
11247 	struct adapter *sc = arg1;
11248 	int i, j, v, rc;
11249 	struct vi_info *vi;
11250 
11251 	v = sc->tt.tls;
11252 	rc = sysctl_handle_int(oidp, &v, 0, req);
11253 	if (rc != 0 || req->newptr == NULL)
11254 		return (rc);
11255 
11256 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11257 		return (ENOTSUP);
11258 
11259 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11260 	if (rc)
11261 		return (rc);
11262 	if (hw_off_limits(sc))
11263 		rc = ENXIO;
11264 	else {
11265 		sc->tt.tls = !!v;
11266 		for_each_port(sc, i) {
11267 			for_each_vi(sc->port[i], j, vi) {
11268 				if (vi->flags & VI_INIT_DONE)
11269 					t4_update_fl_bufsize(vi->ifp);
11270 			}
11271 		}
11272 	}
11273 	end_synchronized_op(sc, 0);
11274 
11275 	return (rc);
11276 
11277 }
11278 
11279 static void
11280 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11281 {
11282 	u_int rem = val % factor;
11283 
11284 	if (rem == 0)
11285 		snprintf(buf, len, "%u", val / factor);
11286 	else {
11287 		while (rem % 10 == 0)
11288 			rem /= 10;
11289 		snprintf(buf, len, "%u.%u", val / factor, rem);
11290 	}
11291 }
11292 
11293 static int
11294 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11295 {
11296 	struct adapter *sc = arg1;
11297 	char buf[16];
11298 	u_int res, re;
11299 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11300 
11301 	mtx_lock(&sc->reg_lock);
11302 	if (hw_off_limits(sc))
11303 		res = (u_int)-1;
11304 	else
11305 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11306 	mtx_unlock(&sc->reg_lock);
11307 	if (res == (u_int)-1)
11308 		return (ENXIO);
11309 
11310 	switch (arg2) {
11311 	case 0:
11312 		/* timer_tick */
11313 		re = G_TIMERRESOLUTION(res);
11314 		break;
11315 	case 1:
11316 		/* TCP timestamp tick */
11317 		re = G_TIMESTAMPRESOLUTION(res);
11318 		break;
11319 	case 2:
11320 		/* DACK tick */
11321 		re = G_DELAYEDACKRESOLUTION(res);
11322 		break;
11323 	default:
11324 		return (EDOOFUS);
11325 	}
11326 
11327 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11328 
11329 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11330 }
11331 
11332 static int
11333 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11334 {
11335 	struct adapter *sc = arg1;
11336 	int rc;
11337 	u_int dack_tmr, dack_re, v;
11338 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11339 
11340 	mtx_lock(&sc->reg_lock);
11341 	if (hw_off_limits(sc))
11342 		rc = ENXIO;
11343 	else {
11344 		rc = 0;
11345 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11346 		    A_TP_TIMER_RESOLUTION));
11347 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11348 	}
11349 	mtx_unlock(&sc->reg_lock);
11350 	if (rc != 0)
11351 		return (rc);
11352 
11353 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11354 
11355 	return (sysctl_handle_int(oidp, &v, 0, req));
11356 }
11357 
11358 static int
11359 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11360 {
11361 	struct adapter *sc = arg1;
11362 	int rc, reg = arg2;
11363 	u_int tre;
11364 	u_long tp_tick_us, v;
11365 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11366 
11367 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11368 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11369 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11370 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11371 
11372 	mtx_lock(&sc->reg_lock);
11373 	if (hw_off_limits(sc))
11374 		rc = ENXIO;
11375 	else {
11376 		rc = 0;
11377 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11378 		tp_tick_us = (cclk_ps << tre) / 1000000;
11379 		if (reg == A_TP_INIT_SRTT)
11380 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11381 		else
11382 			v = tp_tick_us * t4_read_reg(sc, reg);
11383 	}
11384 	mtx_unlock(&sc->reg_lock);
11385 	if (rc != 0)
11386 		return (rc);
11387 	else
11388 		return (sysctl_handle_long(oidp, &v, 0, req));
11389 }
11390 
11391 /*
11392  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11393  * passed to this function.
11394  */
11395 static int
11396 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11397 {
11398 	struct adapter *sc = arg1;
11399 	int rc, idx = arg2;
11400 	u_int v;
11401 
11402 	MPASS(idx >= 0 && idx <= 24);
11403 
11404 	mtx_lock(&sc->reg_lock);
11405 	if (hw_off_limits(sc))
11406 		rc = ENXIO;
11407 	else {
11408 		rc = 0;
11409 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11410 	}
11411 	mtx_unlock(&sc->reg_lock);
11412 	if (rc != 0)
11413 		return (rc);
11414 	else
11415 		return (sysctl_handle_int(oidp, &v, 0, req));
11416 }
11417 
11418 static int
11419 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11420 {
11421 	struct adapter *sc = arg1;
11422 	int rc, idx = arg2;
11423 	u_int shift, v, r;
11424 
11425 	MPASS(idx >= 0 && idx < 16);
11426 
11427 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11428 	shift = (idx & 3) << 3;
11429 	mtx_lock(&sc->reg_lock);
11430 	if (hw_off_limits(sc))
11431 		rc = ENXIO;
11432 	else {
11433 		rc = 0;
11434 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11435 	}
11436 	mtx_unlock(&sc->reg_lock);
11437 	if (rc != 0)
11438 		return (rc);
11439 	else
11440 		return (sysctl_handle_int(oidp, &v, 0, req));
11441 }
11442 
11443 static int
11444 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11445 {
11446 	struct vi_info *vi = arg1;
11447 	struct adapter *sc = vi->adapter;
11448 	int idx, rc, i;
11449 	struct sge_ofld_rxq *ofld_rxq;
11450 	uint8_t v;
11451 
11452 	idx = vi->ofld_tmr_idx;
11453 
11454 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11455 	if (rc != 0 || req->newptr == NULL)
11456 		return (rc);
11457 
11458 	if (idx < 0 || idx >= SGE_NTIMERS)
11459 		return (EINVAL);
11460 
11461 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11462 	    "t4otmr");
11463 	if (rc)
11464 		return (rc);
11465 
11466 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11467 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11468 #ifdef atomic_store_rel_8
11469 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11470 #else
11471 		ofld_rxq->iq.intr_params = v;
11472 #endif
11473 	}
11474 	vi->ofld_tmr_idx = idx;
11475 
11476 	end_synchronized_op(sc, LOCK_HELD);
11477 	return (0);
11478 }
11479 
11480 static int
11481 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11482 {
11483 	struct vi_info *vi = arg1;
11484 	struct adapter *sc = vi->adapter;
11485 	int idx, rc;
11486 
11487 	idx = vi->ofld_pktc_idx;
11488 
11489 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11490 	if (rc != 0 || req->newptr == NULL)
11491 		return (rc);
11492 
11493 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11494 		return (EINVAL);
11495 
11496 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11497 	    "t4opktc");
11498 	if (rc)
11499 		return (rc);
11500 
11501 	if (vi->flags & VI_INIT_DONE)
11502 		rc = EBUSY; /* cannot be changed once the queues are created */
11503 	else
11504 		vi->ofld_pktc_idx = idx;
11505 
11506 	end_synchronized_op(sc, LOCK_HELD);
11507 	return (rc);
11508 }
11509 #endif
11510 
11511 static int
11512 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11513 {
11514 	int rc;
11515 
11516 	if (cntxt->cid > M_CTXTQID)
11517 		return (EINVAL);
11518 
11519 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11520 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11521 		return (EINVAL);
11522 
11523 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11524 	if (rc)
11525 		return (rc);
11526 
11527 	if (hw_off_limits(sc)) {
11528 		rc = ENXIO;
11529 		goto done;
11530 	}
11531 
11532 	if (sc->flags & FW_OK) {
11533 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11534 		    &cntxt->data[0]);
11535 		if (rc == 0)
11536 			goto done;
11537 	}
11538 
11539 	/*
11540 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11541 	 * the backdoor.
11542 	 */
11543 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11544 done:
11545 	end_synchronized_op(sc, 0);
11546 	return (rc);
11547 }
11548 
11549 static int
11550 load_fw(struct adapter *sc, struct t4_data *fw)
11551 {
11552 	int rc;
11553 	uint8_t *fw_data;
11554 
11555 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11556 	if (rc)
11557 		return (rc);
11558 
11559 	if (hw_off_limits(sc)) {
11560 		rc = ENXIO;
11561 		goto done;
11562 	}
11563 
11564 	/*
11565 	 * The firmware, with the sole exception of the memory parity error
11566 	 * handler, runs from memory and not flash.  It is almost always safe to
11567 	 * install a new firmware on a running system.  Just set bit 1 in
11568 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11569 	 */
11570 	if (sc->flags & FULL_INIT_DONE &&
11571 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11572 		rc = EBUSY;
11573 		goto done;
11574 	}
11575 
11576 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11577 
11578 	rc = copyin(fw->data, fw_data, fw->len);
11579 	if (rc == 0)
11580 		rc = -t4_load_fw(sc, fw_data, fw->len);
11581 
11582 	free(fw_data, M_CXGBE);
11583 done:
11584 	end_synchronized_op(sc, 0);
11585 	return (rc);
11586 }
11587 
11588 static int
11589 load_cfg(struct adapter *sc, struct t4_data *cfg)
11590 {
11591 	int rc;
11592 	uint8_t *cfg_data = NULL;
11593 
11594 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11595 	if (rc)
11596 		return (rc);
11597 
11598 	if (hw_off_limits(sc)) {
11599 		rc = ENXIO;
11600 		goto done;
11601 	}
11602 
11603 	if (cfg->len == 0) {
11604 		/* clear */
11605 		rc = -t4_load_cfg(sc, NULL, 0);
11606 		goto done;
11607 	}
11608 
11609 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11610 
11611 	rc = copyin(cfg->data, cfg_data, cfg->len);
11612 	if (rc == 0)
11613 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11614 
11615 	free(cfg_data, M_CXGBE);
11616 done:
11617 	end_synchronized_op(sc, 0);
11618 	return (rc);
11619 }
11620 
11621 static int
11622 load_boot(struct adapter *sc, struct t4_bootrom *br)
11623 {
11624 	int rc;
11625 	uint8_t *br_data = NULL;
11626 	u_int offset;
11627 
11628 	if (br->len > 1024 * 1024)
11629 		return (EFBIG);
11630 
11631 	if (br->pf_offset == 0) {
11632 		/* pfidx */
11633 		if (br->pfidx_addr > 7)
11634 			return (EINVAL);
11635 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11636 		    A_PCIE_PF_EXPROM_OFST)));
11637 	} else if (br->pf_offset == 1) {
11638 		/* offset */
11639 		offset = G_OFFSET(br->pfidx_addr);
11640 	} else {
11641 		return (EINVAL);
11642 	}
11643 
11644 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11645 	if (rc)
11646 		return (rc);
11647 
11648 	if (hw_off_limits(sc)) {
11649 		rc = ENXIO;
11650 		goto done;
11651 	}
11652 
11653 	if (br->len == 0) {
11654 		/* clear */
11655 		rc = -t4_load_boot(sc, NULL, offset, 0);
11656 		goto done;
11657 	}
11658 
11659 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11660 
11661 	rc = copyin(br->data, br_data, br->len);
11662 	if (rc == 0)
11663 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11664 
11665 	free(br_data, M_CXGBE);
11666 done:
11667 	end_synchronized_op(sc, 0);
11668 	return (rc);
11669 }
11670 
11671 static int
11672 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11673 {
11674 	int rc;
11675 	uint8_t *bc_data = NULL;
11676 
11677 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11678 	if (rc)
11679 		return (rc);
11680 
11681 	if (hw_off_limits(sc)) {
11682 		rc = ENXIO;
11683 		goto done;
11684 	}
11685 
11686 	if (bc->len == 0) {
11687 		/* clear */
11688 		rc = -t4_load_bootcfg(sc, NULL, 0);
11689 		goto done;
11690 	}
11691 
11692 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11693 
11694 	rc = copyin(bc->data, bc_data, bc->len);
11695 	if (rc == 0)
11696 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11697 
11698 	free(bc_data, M_CXGBE);
11699 done:
11700 	end_synchronized_op(sc, 0);
11701 	return (rc);
11702 }
11703 
11704 static int
11705 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11706 {
11707 	int rc;
11708 	struct cudbg_init *cudbg;
11709 	void *handle, *buf;
11710 
11711 	/* buf is large, don't block if no memory is available */
11712 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11713 	if (buf == NULL)
11714 		return (ENOMEM);
11715 
11716 	handle = cudbg_alloc_handle();
11717 	if (handle == NULL) {
11718 		rc = ENOMEM;
11719 		goto done;
11720 	}
11721 
11722 	cudbg = cudbg_get_init(handle);
11723 	cudbg->adap = sc;
11724 	cudbg->print = (cudbg_print_cb)printf;
11725 
11726 #ifndef notyet
11727 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11728 	    __func__, dump->wr_flash, dump->len, dump->data);
11729 #endif
11730 
11731 	if (dump->wr_flash)
11732 		cudbg->use_flash = 1;
11733 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11734 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11735 
11736 	rc = cudbg_collect(handle, buf, &dump->len);
11737 	if (rc != 0)
11738 		goto done;
11739 
11740 	rc = copyout(buf, dump->data, dump->len);
11741 done:
11742 	cudbg_free_handle(handle);
11743 	free(buf, M_CXGBE);
11744 	return (rc);
11745 }
11746 
11747 static void
11748 free_offload_policy(struct t4_offload_policy *op)
11749 {
11750 	struct offload_rule *r;
11751 	int i;
11752 
11753 	if (op == NULL)
11754 		return;
11755 
11756 	r = &op->rule[0];
11757 	for (i = 0; i < op->nrules; i++, r++) {
11758 		free(r->bpf_prog.bf_insns, M_CXGBE);
11759 	}
11760 	free(op->rule, M_CXGBE);
11761 	free(op, M_CXGBE);
11762 }
11763 
11764 static int
11765 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11766 {
11767 	int i, rc, len;
11768 	struct t4_offload_policy *op, *old;
11769 	struct bpf_program *bf;
11770 	const struct offload_settings *s;
11771 	struct offload_rule *r;
11772 	void *u;
11773 
11774 	if (!is_offload(sc))
11775 		return (ENODEV);
11776 
11777 	if (uop->nrules == 0) {
11778 		/* Delete installed policies. */
11779 		op = NULL;
11780 		goto set_policy;
11781 	} else if (uop->nrules > 256) { /* arbitrary */
11782 		return (E2BIG);
11783 	}
11784 
11785 	/* Copy userspace offload policy to kernel */
11786 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11787 	op->nrules = uop->nrules;
11788 	len = op->nrules * sizeof(struct offload_rule);
11789 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11790 	rc = copyin(uop->rule, op->rule, len);
11791 	if (rc) {
11792 		free(op->rule, M_CXGBE);
11793 		free(op, M_CXGBE);
11794 		return (rc);
11795 	}
11796 
11797 	r = &op->rule[0];
11798 	for (i = 0; i < op->nrules; i++, r++) {
11799 
11800 		/* Validate open_type */
11801 		if (r->open_type != OPEN_TYPE_LISTEN &&
11802 		    r->open_type != OPEN_TYPE_ACTIVE &&
11803 		    r->open_type != OPEN_TYPE_PASSIVE &&
11804 		    r->open_type != OPEN_TYPE_DONTCARE) {
11805 error:
11806 			/*
11807 			 * Rules 0 to i have malloc'd filters that need to be
11808 			 * freed.  Rules i+1 to nrules have userspace pointers
11809 			 * and should be left alone.
11810 			 */
11811 			op->nrules = i;
11812 			free_offload_policy(op);
11813 			return (rc);
11814 		}
11815 
11816 		/* Validate settings */
11817 		s = &r->settings;
11818 		if ((s->offload != 0 && s->offload != 1) ||
11819 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11820 		    s->sched_class < -1 ||
11821 		    s->sched_class >= sc->params.nsched_cls) {
11822 			rc = EINVAL;
11823 			goto error;
11824 		}
11825 
11826 		bf = &r->bpf_prog;
11827 		u = bf->bf_insns;	/* userspace ptr */
11828 		bf->bf_insns = NULL;
11829 		if (bf->bf_len == 0) {
11830 			/* legal, matches everything */
11831 			continue;
11832 		}
11833 		len = bf->bf_len * sizeof(*bf->bf_insns);
11834 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11835 		rc = copyin(u, bf->bf_insns, len);
11836 		if (rc != 0)
11837 			goto error;
11838 
11839 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11840 			rc = EINVAL;
11841 			goto error;
11842 		}
11843 	}
11844 set_policy:
11845 	rw_wlock(&sc->policy_lock);
11846 	old = sc->policy;
11847 	sc->policy = op;
11848 	rw_wunlock(&sc->policy_lock);
11849 	free_offload_policy(old);
11850 
11851 	return (0);
11852 }
11853 
11854 #define MAX_READ_BUF_SIZE (128 * 1024)
11855 static int
11856 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11857 {
11858 	uint32_t addr, remaining, n;
11859 	uint32_t *buf;
11860 	int rc;
11861 	uint8_t *dst;
11862 
11863 	mtx_lock(&sc->reg_lock);
11864 	if (hw_off_limits(sc))
11865 		rc = ENXIO;
11866 	else
11867 		rc = validate_mem_range(sc, mr->addr, mr->len);
11868 	mtx_unlock(&sc->reg_lock);
11869 	if (rc != 0)
11870 		return (rc);
11871 
11872 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11873 	addr = mr->addr;
11874 	remaining = mr->len;
11875 	dst = (void *)mr->data;
11876 
11877 	while (remaining) {
11878 		n = min(remaining, MAX_READ_BUF_SIZE);
11879 		mtx_lock(&sc->reg_lock);
11880 		if (hw_off_limits(sc))
11881 			rc = ENXIO;
11882 		else
11883 			read_via_memwin(sc, 2, addr, buf, n);
11884 		mtx_unlock(&sc->reg_lock);
11885 		if (rc != 0)
11886 			break;
11887 
11888 		rc = copyout(buf, dst, n);
11889 		if (rc != 0)
11890 			break;
11891 
11892 		dst += n;
11893 		remaining -= n;
11894 		addr += n;
11895 	}
11896 
11897 	free(buf, M_CXGBE);
11898 	return (rc);
11899 }
11900 #undef MAX_READ_BUF_SIZE
11901 
11902 static int
11903 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11904 {
11905 	int rc;
11906 
11907 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11908 		return (EINVAL);
11909 
11910 	if (i2cd->len > sizeof(i2cd->data))
11911 		return (EFBIG);
11912 
11913 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11914 	if (rc)
11915 		return (rc);
11916 	if (hw_off_limits(sc))
11917 		rc = ENXIO;
11918 	else
11919 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11920 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11921 	end_synchronized_op(sc, 0);
11922 
11923 	return (rc);
11924 }
11925 
11926 static int
11927 clear_stats(struct adapter *sc, u_int port_id)
11928 {
11929 	int i, v, chan_map;
11930 	struct port_info *pi;
11931 	struct vi_info *vi;
11932 	struct sge_rxq *rxq;
11933 	struct sge_txq *txq;
11934 	struct sge_wrq *wrq;
11935 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11936 	struct sge_ofld_txq *ofld_txq;
11937 #endif
11938 #ifdef TCP_OFFLOAD
11939 	struct sge_ofld_rxq *ofld_rxq;
11940 #endif
11941 
11942 	if (port_id >= sc->params.nports)
11943 		return (EINVAL);
11944 	pi = sc->port[port_id];
11945 	if (pi == NULL)
11946 		return (EIO);
11947 
11948 	mtx_lock(&sc->reg_lock);
11949 	if (!hw_off_limits(sc)) {
11950 		/* MAC stats */
11951 		t4_clr_port_stats(sc, pi->tx_chan);
11952 		if (is_t6(sc)) {
11953 			if (pi->fcs_reg != -1)
11954 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11955 			else
11956 				pi->stats.rx_fcs_err = 0;
11957 		}
11958 		for_each_vi(pi, v, vi) {
11959 			if (vi->flags & VI_INIT_DONE)
11960 				t4_clr_vi_stats(sc, vi->vin);
11961 		}
11962 		chan_map = pi->rx_e_chan_map;
11963 		v = 0;	/* reuse */
11964 		while (chan_map) {
11965 			i = ffs(chan_map) - 1;
11966 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11967 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11968 			chan_map &= ~(1 << i);
11969 		}
11970 	}
11971 	mtx_unlock(&sc->reg_lock);
11972 	pi->tx_parse_error = 0;
11973 	pi->tnl_cong_drops = 0;
11974 
11975 	/*
11976 	 * Since this command accepts a port, clear stats for
11977 	 * all VIs on this port.
11978 	 */
11979 	for_each_vi(pi, v, vi) {
11980 		if (vi->flags & VI_INIT_DONE) {
11981 
11982 			for_each_rxq(vi, i, rxq) {
11983 #if defined(INET) || defined(INET6)
11984 				rxq->lro.lro_queued = 0;
11985 				rxq->lro.lro_flushed = 0;
11986 #endif
11987 				rxq->rxcsum = 0;
11988 				rxq->vlan_extraction = 0;
11989 				rxq->vxlan_rxcsum = 0;
11990 
11991 				rxq->fl.cl_allocated = 0;
11992 				rxq->fl.cl_recycled = 0;
11993 				rxq->fl.cl_fast_recycled = 0;
11994 			}
11995 
11996 			for_each_txq(vi, i, txq) {
11997 				txq->txcsum = 0;
11998 				txq->tso_wrs = 0;
11999 				txq->vlan_insertion = 0;
12000 				txq->imm_wrs = 0;
12001 				txq->sgl_wrs = 0;
12002 				txq->txpkt_wrs = 0;
12003 				txq->txpkts0_wrs = 0;
12004 				txq->txpkts1_wrs = 0;
12005 				txq->txpkts0_pkts = 0;
12006 				txq->txpkts1_pkts = 0;
12007 				txq->txpkts_flush = 0;
12008 				txq->raw_wrs = 0;
12009 				txq->vxlan_tso_wrs = 0;
12010 				txq->vxlan_txcsum = 0;
12011 				txq->kern_tls_records = 0;
12012 				txq->kern_tls_short = 0;
12013 				txq->kern_tls_partial = 0;
12014 				txq->kern_tls_full = 0;
12015 				txq->kern_tls_octets = 0;
12016 				txq->kern_tls_waste = 0;
12017 				txq->kern_tls_options = 0;
12018 				txq->kern_tls_header = 0;
12019 				txq->kern_tls_fin = 0;
12020 				txq->kern_tls_fin_short = 0;
12021 				txq->kern_tls_cbc = 0;
12022 				txq->kern_tls_gcm = 0;
12023 				mp_ring_reset_stats(txq->r);
12024 			}
12025 
12026 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12027 			for_each_ofld_txq(vi, i, ofld_txq) {
12028 				ofld_txq->wrq.tx_wrs_direct = 0;
12029 				ofld_txq->wrq.tx_wrs_copied = 0;
12030 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12031 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12032 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12033 				counter_u64_zero(ofld_txq->tx_aio_jobs);
12034 				counter_u64_zero(ofld_txq->tx_aio_octets);
12035 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12036 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12037 			}
12038 #endif
12039 #ifdef TCP_OFFLOAD
12040 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12041 				ofld_rxq->fl.cl_allocated = 0;
12042 				ofld_rxq->fl.cl_recycled = 0;
12043 				ofld_rxq->fl.cl_fast_recycled = 0;
12044 				counter_u64_zero(
12045 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12046 				counter_u64_zero(
12047 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12048 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12049 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12050 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12051 				ofld_rxq->rx_iscsi_fl_octets = 0;
12052 				ofld_rxq->rx_aio_ddp_jobs = 0;
12053 				ofld_rxq->rx_aio_ddp_octets = 0;
12054 				ofld_rxq->rx_toe_tls_records = 0;
12055 				ofld_rxq->rx_toe_tls_octets = 0;
12056 				ofld_rxq->rx_toe_ddp_octets = 0;
12057 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12058 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12059 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12060 			}
12061 #endif
12062 
12063 			if (IS_MAIN_VI(vi)) {
12064 				wrq = &sc->sge.ctrlq[pi->port_id];
12065 				wrq->tx_wrs_direct = 0;
12066 				wrq->tx_wrs_copied = 0;
12067 			}
12068 		}
12069 	}
12070 
12071 	return (0);
12072 }
12073 
12074 static int
12075 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12076 {
12077 #ifdef INET6
12078 	struct in6_addr in6;
12079 
12080 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12081 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12082 		return (0);
12083 	else
12084 		return (EIO);
12085 #else
12086 	return (ENOTSUP);
12087 #endif
12088 }
12089 
12090 static int
12091 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12092 {
12093 #ifdef INET6
12094 	struct in6_addr in6;
12095 
12096 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12097 	return (t4_release_clip_addr(sc, &in6));
12098 #else
12099 	return (ENOTSUP);
12100 #endif
12101 }
12102 
12103 int
12104 t4_os_find_pci_capability(struct adapter *sc, int cap)
12105 {
12106 	int i;
12107 
12108 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12109 }
12110 
12111 int
12112 t4_os_pci_save_state(struct adapter *sc)
12113 {
12114 	device_t dev;
12115 	struct pci_devinfo *dinfo;
12116 
12117 	dev = sc->dev;
12118 	dinfo = device_get_ivars(dev);
12119 
12120 	pci_cfg_save(dev, dinfo, 0);
12121 	return (0);
12122 }
12123 
12124 int
12125 t4_os_pci_restore_state(struct adapter *sc)
12126 {
12127 	device_t dev;
12128 	struct pci_devinfo *dinfo;
12129 
12130 	dev = sc->dev;
12131 	dinfo = device_get_ivars(dev);
12132 
12133 	pci_cfg_restore(dev, dinfo);
12134 	return (0);
12135 }
12136 
12137 void
12138 t4_os_portmod_changed(struct port_info *pi)
12139 {
12140 	struct adapter *sc = pi->adapter;
12141 	struct vi_info *vi;
12142 	if_t ifp;
12143 	static const char *mod_str[] = {
12144 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12145 	};
12146 
12147 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12148 	    ("%s: port_type %u", __func__, pi->port_type));
12149 
12150 	vi = &pi->vi[0];
12151 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12152 		PORT_LOCK(pi);
12153 		build_medialist(pi);
12154 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12155 			fixup_link_config(pi);
12156 			apply_link_config(pi);
12157 		}
12158 		PORT_UNLOCK(pi);
12159 		end_synchronized_op(sc, LOCK_HELD);
12160 	}
12161 
12162 	ifp = vi->ifp;
12163 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12164 		if_printf(ifp, "transceiver unplugged.\n");
12165 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12166 		if_printf(ifp, "unknown transceiver inserted.\n");
12167 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12168 		if_printf(ifp, "unsupported transceiver inserted.\n");
12169 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12170 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12171 		    port_top_speed(pi), mod_str[pi->mod_type]);
12172 	} else {
12173 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12174 		    pi->mod_type);
12175 	}
12176 }
12177 
12178 void
12179 t4_os_link_changed(struct port_info *pi)
12180 {
12181 	struct vi_info *vi;
12182 	if_t ifp;
12183 	struct link_config *lc = &pi->link_cfg;
12184 	struct adapter *sc = pi->adapter;
12185 	int v;
12186 
12187 	PORT_LOCK_ASSERT_OWNED(pi);
12188 
12189 	if (is_t6(sc)) {
12190 		if (lc->link_ok) {
12191 			if (lc->speed > 25000 ||
12192 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12193 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12194 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12195 			} else {
12196 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12197 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12198 			}
12199 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12200 			pi->stats.rx_fcs_err = 0;
12201 		} else {
12202 			pi->fcs_reg = -1;
12203 		}
12204 	} else {
12205 		MPASS(pi->fcs_reg != -1);
12206 		MPASS(pi->fcs_base == 0);
12207 	}
12208 
12209 	for_each_vi(pi, v, vi) {
12210 		ifp = vi->ifp;
12211 		if (ifp == NULL || IS_DETACHING(vi))
12212 			continue;
12213 
12214 		if (lc->link_ok) {
12215 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12216 			if_link_state_change(ifp, LINK_STATE_UP);
12217 		} else {
12218 			if_link_state_change(ifp, LINK_STATE_DOWN);
12219 		}
12220 	}
12221 }
12222 
12223 void
12224 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12225 {
12226 	struct adapter *sc;
12227 
12228 	sx_slock(&t4_list_lock);
12229 	SLIST_FOREACH(sc, &t4_list, link) {
12230 		/*
12231 		 * func should not make any assumptions about what state sc is
12232 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12233 		 */
12234 		func(sc, arg);
12235 	}
12236 	sx_sunlock(&t4_list_lock);
12237 }
12238 
12239 static int
12240 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12241     struct thread *td)
12242 {
12243 	int rc;
12244 	struct adapter *sc = dev->si_drv1;
12245 
12246 	rc = priv_check(td, PRIV_DRIVER);
12247 	if (rc != 0)
12248 		return (rc);
12249 
12250 	switch (cmd) {
12251 	case CHELSIO_T4_GETREG: {
12252 		struct t4_reg *edata = (struct t4_reg *)data;
12253 
12254 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12255 			return (EFAULT);
12256 
12257 		mtx_lock(&sc->reg_lock);
12258 		if (hw_off_limits(sc))
12259 			rc = ENXIO;
12260 		else if (edata->size == 4)
12261 			edata->val = t4_read_reg(sc, edata->addr);
12262 		else if (edata->size == 8)
12263 			edata->val = t4_read_reg64(sc, edata->addr);
12264 		else
12265 			rc = EINVAL;
12266 		mtx_unlock(&sc->reg_lock);
12267 
12268 		break;
12269 	}
12270 	case CHELSIO_T4_SETREG: {
12271 		struct t4_reg *edata = (struct t4_reg *)data;
12272 
12273 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12274 			return (EFAULT);
12275 
12276 		mtx_lock(&sc->reg_lock);
12277 		if (hw_off_limits(sc))
12278 			rc = ENXIO;
12279 		else if (edata->size == 4) {
12280 			if (edata->val & 0xffffffff00000000)
12281 				rc = EINVAL;
12282 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12283 		} else if (edata->size == 8)
12284 			t4_write_reg64(sc, edata->addr, edata->val);
12285 		else
12286 			rc = EINVAL;
12287 		mtx_unlock(&sc->reg_lock);
12288 
12289 		break;
12290 	}
12291 	case CHELSIO_T4_REGDUMP: {
12292 		struct t4_regdump *regs = (struct t4_regdump *)data;
12293 		int reglen = t4_get_regs_len(sc);
12294 		uint8_t *buf;
12295 
12296 		if (regs->len < reglen) {
12297 			regs->len = reglen; /* hint to the caller */
12298 			return (ENOBUFS);
12299 		}
12300 
12301 		regs->len = reglen;
12302 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12303 		mtx_lock(&sc->reg_lock);
12304 		if (hw_off_limits(sc))
12305 			rc = ENXIO;
12306 		else
12307 			get_regs(sc, regs, buf);
12308 		mtx_unlock(&sc->reg_lock);
12309 		if (rc == 0)
12310 			rc = copyout(buf, regs->data, reglen);
12311 		free(buf, M_CXGBE);
12312 		break;
12313 	}
12314 	case CHELSIO_T4_GET_FILTER_MODE:
12315 		rc = get_filter_mode(sc, (uint32_t *)data);
12316 		break;
12317 	case CHELSIO_T4_SET_FILTER_MODE:
12318 		rc = set_filter_mode(sc, *(uint32_t *)data);
12319 		break;
12320 	case CHELSIO_T4_SET_FILTER_MASK:
12321 		rc = set_filter_mask(sc, *(uint32_t *)data);
12322 		break;
12323 	case CHELSIO_T4_GET_FILTER:
12324 		rc = get_filter(sc, (struct t4_filter *)data);
12325 		break;
12326 	case CHELSIO_T4_SET_FILTER:
12327 		rc = set_filter(sc, (struct t4_filter *)data);
12328 		break;
12329 	case CHELSIO_T4_DEL_FILTER:
12330 		rc = del_filter(sc, (struct t4_filter *)data);
12331 		break;
12332 	case CHELSIO_T4_GET_SGE_CONTEXT:
12333 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12334 		break;
12335 	case CHELSIO_T4_LOAD_FW:
12336 		rc = load_fw(sc, (struct t4_data *)data);
12337 		break;
12338 	case CHELSIO_T4_GET_MEM:
12339 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12340 		break;
12341 	case CHELSIO_T4_GET_I2C:
12342 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12343 		break;
12344 	case CHELSIO_T4_CLEAR_STATS:
12345 		rc = clear_stats(sc, *(uint32_t *)data);
12346 		break;
12347 	case CHELSIO_T4_SCHED_CLASS:
12348 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12349 		break;
12350 	case CHELSIO_T4_SCHED_QUEUE:
12351 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12352 		break;
12353 	case CHELSIO_T4_GET_TRACER:
12354 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12355 		break;
12356 	case CHELSIO_T4_SET_TRACER:
12357 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12358 		break;
12359 	case CHELSIO_T4_LOAD_CFG:
12360 		rc = load_cfg(sc, (struct t4_data *)data);
12361 		break;
12362 	case CHELSIO_T4_LOAD_BOOT:
12363 		rc = load_boot(sc, (struct t4_bootrom *)data);
12364 		break;
12365 	case CHELSIO_T4_LOAD_BOOTCFG:
12366 		rc = load_bootcfg(sc, (struct t4_data *)data);
12367 		break;
12368 	case CHELSIO_T4_CUDBG_DUMP:
12369 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12370 		break;
12371 	case CHELSIO_T4_SET_OFLD_POLICY:
12372 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12373 		break;
12374 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12375 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12376 		break;
12377 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12378 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12379 		break;
12380 	default:
12381 		rc = ENOTTY;
12382 	}
12383 
12384 	return (rc);
12385 }
12386 
12387 #ifdef TCP_OFFLOAD
12388 int
12389 toe_capability(struct vi_info *vi, bool enable)
12390 {
12391 	int rc;
12392 	struct port_info *pi = vi->pi;
12393 	struct adapter *sc = pi->adapter;
12394 
12395 	ASSERT_SYNCHRONIZED_OP(sc);
12396 
12397 	if (!is_offload(sc))
12398 		return (ENODEV);
12399 	if (hw_off_limits(sc))
12400 		return (ENXIO);
12401 
12402 	if (enable) {
12403 #ifdef KERN_TLS
12404 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12405 			int i, j, n;
12406 			struct port_info *p;
12407 			struct vi_info *v;
12408 
12409 			/*
12410 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12411 			 * on any ifnet.
12412 			 */
12413 			n = 0;
12414 			for_each_port(sc, i) {
12415 				p = sc->port[i];
12416 				for_each_vi(p, j, v) {
12417 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12418 						CH_WARN(sc,
12419 						    "%s has NIC TLS enabled.\n",
12420 						    device_get_nameunit(v->dev));
12421 						n++;
12422 					}
12423 				}
12424 			}
12425 			if (n > 0) {
12426 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12427 				    "associated with this adapter before "
12428 				    "trying to enable TOE.\n");
12429 				return (EAGAIN);
12430 			}
12431 			rc = t6_config_kern_tls(sc, false);
12432 			if (rc)
12433 				return (rc);
12434 		}
12435 #endif
12436 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12437 			/* TOE is already enabled. */
12438 			return (0);
12439 		}
12440 
12441 		/*
12442 		 * We need the port's queues around so that we're able to send
12443 		 * and receive CPLs to/from the TOE even if the ifnet for this
12444 		 * port has never been UP'd administratively.
12445 		 */
12446 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12447 			return (rc);
12448 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12449 		    ((rc = vi_init(&pi->vi[0])) != 0))
12450 			return (rc);
12451 
12452 		if (isset(&sc->offload_map, pi->port_id)) {
12453 			/* TOE is enabled on another VI of this port. */
12454 			MPASS(pi->uld_vis > 0);
12455 			pi->uld_vis++;
12456 			return (0);
12457 		}
12458 
12459 		if (!uld_active(sc, ULD_TOM)) {
12460 			rc = t4_activate_uld(sc, ULD_TOM);
12461 			if (rc == EAGAIN) {
12462 				log(LOG_WARNING,
12463 				    "You must kldload t4_tom.ko before trying "
12464 				    "to enable TOE on a cxgbe interface.\n");
12465 			}
12466 			if (rc != 0)
12467 				return (rc);
12468 			KASSERT(sc->tom_softc != NULL,
12469 			    ("%s: TOM activated but softc NULL", __func__));
12470 			KASSERT(uld_active(sc, ULD_TOM),
12471 			    ("%s: TOM activated but flag not set", __func__));
12472 		}
12473 
12474 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12475 		if (!uld_active(sc, ULD_IWARP))
12476 			(void) t4_activate_uld(sc, ULD_IWARP);
12477 		if (!uld_active(sc, ULD_ISCSI))
12478 			(void) t4_activate_uld(sc, ULD_ISCSI);
12479 
12480 		if (pi->uld_vis++ == 0)
12481 			setbit(&sc->offload_map, pi->port_id);
12482 	} else {
12483 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) == 0) {
12484 			/* TOE is already disabled. */
12485 			return (0);
12486 		}
12487 		MPASS(isset(&sc->offload_map, pi->port_id));
12488 		MPASS(pi->uld_vis > 0);
12489 		if (--pi->uld_vis == 0)
12490 			clrbit(&sc->offload_map, pi->port_id);
12491 	}
12492 
12493 	return (0);
12494 }
12495 
12496 /*
12497  * Add an upper layer driver to the global list.
12498  */
12499 int
12500 t4_register_uld(struct uld_info *ui, int id)
12501 {
12502 	int rc;
12503 
12504 	if (id < 0 || id > ULD_MAX)
12505 		return (EINVAL);
12506 	sx_xlock(&t4_uld_list_lock);
12507 	if (t4_uld_list[id] != NULL)
12508 		rc = EEXIST;
12509 	else {
12510 		t4_uld_list[id] = ui;
12511 		rc = 0;
12512 	}
12513 	sx_xunlock(&t4_uld_list_lock);
12514 	return (rc);
12515 }
12516 
12517 int
12518 t4_unregister_uld(struct uld_info *ui, int id)
12519 {
12520 
12521 	if (id < 0 || id > ULD_MAX)
12522 		return (EINVAL);
12523 	sx_xlock(&t4_uld_list_lock);
12524 	MPASS(t4_uld_list[id] == ui);
12525 	t4_uld_list[id] = NULL;
12526 	sx_xunlock(&t4_uld_list_lock);
12527 	return (0);
12528 }
12529 
12530 int
12531 t4_activate_uld(struct adapter *sc, int id)
12532 {
12533 	int rc;
12534 
12535 	ASSERT_SYNCHRONIZED_OP(sc);
12536 
12537 	if (id < 0 || id > ULD_MAX)
12538 		return (EINVAL);
12539 
12540 	/* Adapter needs to be initialized before any ULD can be activated. */
12541 	if (!(sc->flags & FULL_INIT_DONE)) {
12542 		rc = adapter_init(sc);
12543 		if (rc != 0)
12544 			return (rc);
12545 	}
12546 
12547 	sx_slock(&t4_uld_list_lock);
12548 	if (t4_uld_list[id] == NULL)
12549 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
12550 	else {
12551 		rc = t4_uld_list[id]->uld_activate(sc);
12552 		if (rc == 0)
12553 			setbit(&sc->active_ulds, id);
12554 	}
12555 	sx_sunlock(&t4_uld_list_lock);
12556 
12557 	return (rc);
12558 }
12559 
12560 int
12561 t4_deactivate_uld(struct adapter *sc, int id)
12562 {
12563 	int rc;
12564 
12565 	ASSERT_SYNCHRONIZED_OP(sc);
12566 
12567 	if (id < 0 || id > ULD_MAX)
12568 		return (EINVAL);
12569 
12570 	sx_slock(&t4_uld_list_lock);
12571 	if (t4_uld_list[id] == NULL)
12572 		rc = ENXIO;
12573 	else {
12574 		rc = t4_uld_list[id]->uld_deactivate(sc);
12575 		if (rc == 0)
12576 			clrbit(&sc->active_ulds, id);
12577 	}
12578 	sx_sunlock(&t4_uld_list_lock);
12579 
12580 	return (rc);
12581 }
12582 
12583 static int
12584 deactivate_all_uld(struct adapter *sc)
12585 {
12586 	int i, rc;
12587 
12588 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12589 	if (rc != 0)
12590 		return (ENXIO);
12591 	sx_slock(&t4_uld_list_lock);
12592 	for (i = 0; i <= ULD_MAX; i++) {
12593 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
12594 			continue;
12595 		rc = t4_uld_list[i]->uld_deactivate(sc);
12596 		if (rc != 0)
12597 			break;
12598 		clrbit(&sc->active_ulds, i);
12599 	}
12600 	sx_sunlock(&t4_uld_list_lock);
12601 	end_synchronized_op(sc, 0);
12602 
12603 	return (rc);
12604 }
12605 
12606 static void
12607 stop_all_uld(struct adapter *sc)
12608 {
12609 	int i;
12610 
12611 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
12612 		return;
12613 	sx_slock(&t4_uld_list_lock);
12614 	for (i = 0; i <= ULD_MAX; i++) {
12615 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12616 		    t4_uld_list[i]->uld_stop == NULL)
12617 			continue;
12618 		(void) t4_uld_list[i]->uld_stop(sc);
12619 	}
12620 	sx_sunlock(&t4_uld_list_lock);
12621 	end_synchronized_op(sc, 0);
12622 }
12623 
12624 static void
12625 restart_all_uld(struct adapter *sc)
12626 {
12627 	int i;
12628 
12629 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
12630 		return;
12631 	sx_slock(&t4_uld_list_lock);
12632 	for (i = 0; i <= ULD_MAX; i++) {
12633 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12634 		    t4_uld_list[i]->uld_restart == NULL)
12635 			continue;
12636 		(void) t4_uld_list[i]->uld_restart(sc);
12637 	}
12638 	sx_sunlock(&t4_uld_list_lock);
12639 	end_synchronized_op(sc, 0);
12640 }
12641 
12642 int
12643 uld_active(struct adapter *sc, int id)
12644 {
12645 
12646 	MPASS(id >= 0 && id <= ULD_MAX);
12647 
12648 	return (isset(&sc->active_ulds, id));
12649 }
12650 #endif
12651 
12652 #ifdef KERN_TLS
12653 static int
12654 ktls_capability(struct adapter *sc, bool enable)
12655 {
12656 	ASSERT_SYNCHRONIZED_OP(sc);
12657 
12658 	if (!is_ktls(sc))
12659 		return (ENODEV);
12660 	if (!is_t6(sc))
12661 		return (0);
12662 	if (hw_off_limits(sc))
12663 		return (ENXIO);
12664 
12665 	if (enable) {
12666 		if (sc->flags & KERN_TLS_ON)
12667 			return (0);	/* already on */
12668 		if (sc->offload_map != 0) {
12669 			CH_WARN(sc,
12670 			    "Disable TOE on all interfaces associated with "
12671 			    "this adapter before trying to enable NIC TLS.\n");
12672 			return (EAGAIN);
12673 		}
12674 		return (t6_config_kern_tls(sc, true));
12675 	} else {
12676 		/*
12677 		 * Nothing to do for disable.  If TOE is enabled sometime later
12678 		 * then toe_capability will reconfigure the hardware.
12679 		 */
12680 		return (0);
12681 	}
12682 }
12683 #endif
12684 
12685 /*
12686  * t  = ptr to tunable.
12687  * nc = number of CPUs.
12688  * c  = compiled in default for that tunable.
12689  */
12690 static void
12691 calculate_nqueues(int *t, int nc, const int c)
12692 {
12693 	int nq;
12694 
12695 	if (*t > 0)
12696 		return;
12697 	nq = *t < 0 ? -*t : c;
12698 	*t = min(nc, nq);
12699 }
12700 
12701 /*
12702  * Come up with reasonable defaults for some of the tunables, provided they're
12703  * not set by the user (in which case we'll use the values as is).
12704  */
12705 static void
12706 tweak_tunables(void)
12707 {
12708 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12709 
12710 	if (t4_ntxq < 1) {
12711 #ifdef RSS
12712 		t4_ntxq = rss_getnumbuckets();
12713 #else
12714 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12715 #endif
12716 	}
12717 
12718 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12719 
12720 	if (t4_nrxq < 1) {
12721 #ifdef RSS
12722 		t4_nrxq = rss_getnumbuckets();
12723 #else
12724 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12725 #endif
12726 	}
12727 
12728 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12729 
12730 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12731 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12732 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12733 #endif
12734 #ifdef TCP_OFFLOAD
12735 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12736 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12737 #endif
12738 
12739 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12740 	if (t4_toecaps_allowed == -1)
12741 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12742 #else
12743 	if (t4_toecaps_allowed == -1)
12744 		t4_toecaps_allowed = 0;
12745 #endif
12746 
12747 #ifdef TCP_OFFLOAD
12748 	if (t4_rdmacaps_allowed == -1) {
12749 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12750 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12751 	}
12752 
12753 	if (t4_iscsicaps_allowed == -1) {
12754 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12755 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12756 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12757 	}
12758 
12759 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12760 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12761 
12762 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12763 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12764 #else
12765 	if (t4_rdmacaps_allowed == -1)
12766 		t4_rdmacaps_allowed = 0;
12767 
12768 	if (t4_iscsicaps_allowed == -1)
12769 		t4_iscsicaps_allowed = 0;
12770 #endif
12771 
12772 #ifdef DEV_NETMAP
12773 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12774 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12775 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12776 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12777 #endif
12778 
12779 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12780 		t4_tmr_idx = TMR_IDX;
12781 
12782 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12783 		t4_pktc_idx = PKTC_IDX;
12784 
12785 	if (t4_qsize_txq < 128)
12786 		t4_qsize_txq = 128;
12787 
12788 	if (t4_qsize_rxq < 128)
12789 		t4_qsize_rxq = 128;
12790 	while (t4_qsize_rxq & 7)
12791 		t4_qsize_rxq++;
12792 
12793 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12794 
12795 	/*
12796 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12797 	 * VI for the port.  The rest are additional virtual interfaces on the
12798 	 * same physical port.  Note that the main VI does not have native
12799 	 * netmap support but the extra VIs do.
12800 	 *
12801 	 * Limit the number of VIs per port to the number of available
12802 	 * MAC addresses per port.
12803 	 */
12804 	if (t4_num_vis < 1)
12805 		t4_num_vis = 1;
12806 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12807 		t4_num_vis = nitems(vi_mac_funcs);
12808 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12809 	}
12810 
12811 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12812 		pcie_relaxed_ordering = 1;
12813 #if defined(__i386__) || defined(__amd64__)
12814 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12815 			pcie_relaxed_ordering = 0;
12816 #endif
12817 	}
12818 }
12819 
12820 #ifdef DDB
12821 static void
12822 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
12823 {
12824 	uint32_t base, j, off, pf, reg, save, win_pos;
12825 
12826 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12827 	save = t4_read_reg(sc, reg);
12828 	base = sc->memwin[2].mw_base;
12829 
12830 	if (is_t4(sc)) {
12831 		pf = 0;
12832 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
12833 	} else {
12834 		pf = V_PFNUM(sc->pf);
12835 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
12836 	}
12837 	off = addr - win_pos;
12838 	t4_write_reg(sc, reg, win_pos | pf);
12839 	t4_read_reg(sc, reg);
12840 
12841 	while (len > 0 && !db_pager_quit) {
12842 		uint32_t buf[8];
12843 		for (j = 0; j < 8; j++, off += 4)
12844 			buf[j] = htonl(t4_read_reg(sc, base + off));
12845 
12846 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12847 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12848 		    buf[7]);
12849 		if (len <= sizeof(buf))
12850 			len = 0;
12851 		else
12852 			len -= sizeof(buf);
12853 	}
12854 
12855 	t4_write_reg(sc, reg, save);
12856 	t4_read_reg(sc, reg);
12857 }
12858 
12859 static void
12860 t4_dump_tcb(struct adapter *sc, int tid)
12861 {
12862 	uint32_t tcb_addr;
12863 
12864 	/* Dump TCB for the tid */
12865 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12866 	tcb_addr += tid * TCB_SIZE;
12867 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
12868 }
12869 
12870 static void
12871 t4_dump_devlog(struct adapter *sc)
12872 {
12873 	struct devlog_params *dparams = &sc->params.devlog;
12874 	struct fw_devlog_e e;
12875 	int i, first, j, m, nentries, rc;
12876 	uint64_t ftstamp = UINT64_MAX;
12877 
12878 	if (dparams->start == 0) {
12879 		db_printf("devlog params not valid\n");
12880 		return;
12881 	}
12882 
12883 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12884 	m = fwmtype_to_hwmtype(dparams->memtype);
12885 
12886 	/* Find the first entry. */
12887 	first = -1;
12888 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12889 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12890 		    sizeof(e), (void *)&e);
12891 		if (rc != 0)
12892 			break;
12893 
12894 		if (e.timestamp == 0)
12895 			break;
12896 
12897 		e.timestamp = be64toh(e.timestamp);
12898 		if (e.timestamp < ftstamp) {
12899 			ftstamp = e.timestamp;
12900 			first = i;
12901 		}
12902 	}
12903 
12904 	if (first == -1)
12905 		return;
12906 
12907 	i = first;
12908 	do {
12909 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12910 		    sizeof(e), (void *)&e);
12911 		if (rc != 0)
12912 			return;
12913 
12914 		if (e.timestamp == 0)
12915 			return;
12916 
12917 		e.timestamp = be64toh(e.timestamp);
12918 		e.seqno = be32toh(e.seqno);
12919 		for (j = 0; j < 8; j++)
12920 			e.params[j] = be32toh(e.params[j]);
12921 
12922 		db_printf("%10d  %15ju  %8s  %8s  ",
12923 		    e.seqno, e.timestamp,
12924 		    (e.level < nitems(devlog_level_strings) ?
12925 			devlog_level_strings[e.level] : "UNKNOWN"),
12926 		    (e.facility < nitems(devlog_facility_strings) ?
12927 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12928 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12929 		    e.params[3], e.params[4], e.params[5], e.params[6],
12930 		    e.params[7]);
12931 
12932 		if (++i == nentries)
12933 			i = 0;
12934 	} while (i != first && !db_pager_quit);
12935 }
12936 
12937 static DB_DEFINE_TABLE(show, t4, show_t4);
12938 
12939 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12940 {
12941 	device_t dev;
12942 	int t;
12943 	bool valid;
12944 
12945 	valid = false;
12946 	t = db_read_token();
12947 	if (t == tIDENT) {
12948 		dev = device_lookup_by_name(db_tok_string);
12949 		valid = true;
12950 	}
12951 	db_skip_to_eol();
12952 	if (!valid) {
12953 		db_printf("usage: show t4 devlog <nexus>\n");
12954 		return;
12955 	}
12956 
12957 	if (dev == NULL) {
12958 		db_printf("device not found\n");
12959 		return;
12960 	}
12961 
12962 	t4_dump_devlog(device_get_softc(dev));
12963 }
12964 
12965 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12966 {
12967 	device_t dev;
12968 	int radix, tid, t;
12969 	bool valid;
12970 
12971 	valid = false;
12972 	radix = db_radix;
12973 	db_radix = 10;
12974 	t = db_read_token();
12975 	if (t == tIDENT) {
12976 		dev = device_lookup_by_name(db_tok_string);
12977 		t = db_read_token();
12978 		if (t == tNUMBER) {
12979 			tid = db_tok_number;
12980 			valid = true;
12981 		}
12982 	}
12983 	db_radix = radix;
12984 	db_skip_to_eol();
12985 	if (!valid) {
12986 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12987 		return;
12988 	}
12989 
12990 	if (dev == NULL) {
12991 		db_printf("device not found\n");
12992 		return;
12993 	}
12994 	if (tid < 0) {
12995 		db_printf("invalid tid\n");
12996 		return;
12997 	}
12998 
12999 	t4_dump_tcb(device_get_softc(dev), tid);
13000 }
13001 
13002 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
13003 {
13004 	device_t dev;
13005 	int radix, t;
13006 	bool valid;
13007 
13008 	valid = false;
13009 	radix = db_radix;
13010 	db_radix = 10;
13011 	t = db_read_token();
13012 	if (t == tIDENT) {
13013 		dev = device_lookup_by_name(db_tok_string);
13014 		t = db_read_token();
13015 		if (t == tNUMBER) {
13016 			addr = db_tok_number;
13017 			t = db_read_token();
13018 			if (t == tNUMBER) {
13019 				count = db_tok_number;
13020 				valid = true;
13021 			}
13022 		}
13023 	}
13024 	db_radix = radix;
13025 	db_skip_to_eol();
13026 	if (!valid) {
13027 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
13028 		return;
13029 	}
13030 
13031 	if (dev == NULL) {
13032 		db_printf("device not found\n");
13033 		return;
13034 	}
13035 	if (addr < 0) {
13036 		db_printf("invalid address\n");
13037 		return;
13038 	}
13039 	if (count <= 0) {
13040 		db_printf("invalid length\n");
13041 		return;
13042 	}
13043 
13044 	t4_dump_mem(device_get_softc(dev), addr, count);
13045 }
13046 #endif
13047 
13048 static eventhandler_tag vxlan_start_evtag;
13049 static eventhandler_tag vxlan_stop_evtag;
13050 
13051 struct vxlan_evargs {
13052 	if_t ifp;
13053 	uint16_t port;
13054 };
13055 
13056 static void
13057 enable_vxlan_rx(struct adapter *sc)
13058 {
13059 	int i, rc;
13060 	struct port_info *pi;
13061 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13062 
13063 	ASSERT_SYNCHRONIZED_OP(sc);
13064 
13065 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13066 	    F_VXLAN_EN);
13067 	for_each_port(sc, i) {
13068 		pi = sc->port[i];
13069 		if (pi->vxlan_tcam_entry == true)
13070 			continue;
13071 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13072 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13073 		    true);
13074 		if (rc < 0) {
13075 			rc = -rc;
13076 			CH_ERR(&pi->vi[0],
13077 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13078 		} else {
13079 			MPASS(rc == sc->rawf_base + pi->port_id);
13080 			pi->vxlan_tcam_entry = true;
13081 		}
13082 	}
13083 }
13084 
13085 static void
13086 t4_vxlan_start(struct adapter *sc, void *arg)
13087 {
13088 	struct vxlan_evargs *v = arg;
13089 
13090 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13091 		return;
13092 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13093 		return;
13094 
13095 	if (sc->vxlan_refcount == 0) {
13096 		sc->vxlan_port = v->port;
13097 		sc->vxlan_refcount = 1;
13098 		if (!hw_off_limits(sc))
13099 			enable_vxlan_rx(sc);
13100 	} else if (sc->vxlan_port == v->port) {
13101 		sc->vxlan_refcount++;
13102 	} else {
13103 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13104 		    "ignoring attempt to configure it on port %d\n",
13105 		    sc->vxlan_port, v->port);
13106 	}
13107 	end_synchronized_op(sc, 0);
13108 }
13109 
13110 static void
13111 t4_vxlan_stop(struct adapter *sc, void *arg)
13112 {
13113 	struct vxlan_evargs *v = arg;
13114 
13115 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13116 		return;
13117 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13118 		return;
13119 
13120 	/*
13121 	 * VXLANs may have been configured before the driver was loaded so we
13122 	 * may see more stops than starts.  This is not handled cleanly but at
13123 	 * least we keep the refcount sane.
13124 	 */
13125 	if (sc->vxlan_port != v->port)
13126 		goto done;
13127 	if (sc->vxlan_refcount == 0) {
13128 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13129 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13130 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13131 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13132 done:
13133 	end_synchronized_op(sc, 0);
13134 }
13135 
13136 static void
13137 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13138     sa_family_t family, u_int port)
13139 {
13140 	struct vxlan_evargs v;
13141 
13142 	MPASS(family == AF_INET || family == AF_INET6);
13143 	v.ifp = ifp;
13144 	v.port = port;
13145 
13146 	t4_iterate(t4_vxlan_start, &v);
13147 }
13148 
13149 static void
13150 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13151     u_int port)
13152 {
13153 	struct vxlan_evargs v;
13154 
13155 	MPASS(family == AF_INET || family == AF_INET6);
13156 	v.ifp = ifp;
13157 	v.port = port;
13158 
13159 	t4_iterate(t4_vxlan_stop, &v);
13160 }
13161 
13162 
13163 static struct sx mlu;	/* mod load unload */
13164 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13165 
13166 static int
13167 mod_event(module_t mod, int cmd, void *arg)
13168 {
13169 	int rc = 0;
13170 	static int loaded = 0;
13171 
13172 	switch (cmd) {
13173 	case MOD_LOAD:
13174 		sx_xlock(&mlu);
13175 		if (loaded++ == 0) {
13176 			t4_sge_modload();
13177 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13178 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13179 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13180 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13181 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13182 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13183 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13184 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13185 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13186 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13187 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13188 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13189 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13190 			    do_smt_write_rpl);
13191 			sx_init(&t4_list_lock, "T4/T5 adapters");
13192 			SLIST_INIT(&t4_list);
13193 			callout_init(&fatal_callout, 1);
13194 #ifdef TCP_OFFLOAD
13195 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13196 #endif
13197 #ifdef INET6
13198 			t4_clip_modload();
13199 #endif
13200 #ifdef KERN_TLS
13201 			t6_ktls_modload();
13202 #endif
13203 			t4_tracer_modload();
13204 			tweak_tunables();
13205 			vxlan_start_evtag =
13206 			    EVENTHANDLER_REGISTER(vxlan_start,
13207 				t4_vxlan_start_handler, NULL,
13208 				EVENTHANDLER_PRI_ANY);
13209 			vxlan_stop_evtag =
13210 			    EVENTHANDLER_REGISTER(vxlan_stop,
13211 				t4_vxlan_stop_handler, NULL,
13212 				EVENTHANDLER_PRI_ANY);
13213 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13214 			    taskqueue_thread_enqueue, &reset_tq);
13215 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13216 			    "t4_rst_thr");
13217 		}
13218 		sx_xunlock(&mlu);
13219 		break;
13220 
13221 	case MOD_UNLOAD:
13222 		sx_xlock(&mlu);
13223 		if (--loaded == 0) {
13224 #ifdef TCP_OFFLOAD
13225 			int i;
13226 #endif
13227 			int tries;
13228 
13229 			taskqueue_free(reset_tq);
13230 
13231 			tries = 0;
13232 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13233 				uprintf("%ju clusters with custom free routine "
13234 				    "still is use.\n", t4_sge_extfree_refs());
13235 				pause("t4unload", 2 * hz);
13236 			}
13237 
13238 			sx_slock(&t4_list_lock);
13239 			if (!SLIST_EMPTY(&t4_list)) {
13240 				rc = EBUSY;
13241 				sx_sunlock(&t4_list_lock);
13242 				goto done_unload;
13243 			}
13244 #ifdef TCP_OFFLOAD
13245 			sx_slock(&t4_uld_list_lock);
13246 			for (i = 0; i <= ULD_MAX; i++) {
13247 				if (t4_uld_list[i] != NULL) {
13248 					rc = EBUSY;
13249 					sx_sunlock(&t4_uld_list_lock);
13250 					sx_sunlock(&t4_list_lock);
13251 					goto done_unload;
13252 				}
13253 			}
13254 			sx_sunlock(&t4_uld_list_lock);
13255 #endif
13256 			sx_sunlock(&t4_list_lock);
13257 
13258 			if (t4_sge_extfree_refs() == 0) {
13259 				EVENTHANDLER_DEREGISTER(vxlan_start,
13260 				    vxlan_start_evtag);
13261 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13262 				    vxlan_stop_evtag);
13263 				t4_tracer_modunload();
13264 #ifdef KERN_TLS
13265 				t6_ktls_modunload();
13266 #endif
13267 #ifdef INET6
13268 				t4_clip_modunload();
13269 #endif
13270 #ifdef TCP_OFFLOAD
13271 				sx_destroy(&t4_uld_list_lock);
13272 #endif
13273 				sx_destroy(&t4_list_lock);
13274 				t4_sge_modunload();
13275 				loaded = 0;
13276 			} else {
13277 				rc = EBUSY;
13278 				loaded++;	/* undo earlier decrement */
13279 			}
13280 		}
13281 done_unload:
13282 		sx_xunlock(&mlu);
13283 		break;
13284 	}
13285 
13286 	return (rc);
13287 }
13288 
13289 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13290 MODULE_VERSION(t4nex, 1);
13291 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13292 #ifdef DEV_NETMAP
13293 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13294 #endif /* DEV_NETMAP */
13295 
13296 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13297 MODULE_VERSION(t5nex, 1);
13298 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13299 #ifdef DEV_NETMAP
13300 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13301 #endif /* DEV_NETMAP */
13302 
13303 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13304 MODULE_VERSION(t6nex, 1);
13305 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13306 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13307 #ifdef DEV_NETMAP
13308 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13309 #endif /* DEV_NETMAP */
13310 
13311 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13312 MODULE_VERSION(cxgbe, 1);
13313 
13314 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13315 MODULE_VERSION(cxl, 1);
13316 
13317 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13318 MODULE_VERSION(cc, 1);
13319 
13320 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13321 MODULE_VERSION(vcxgbe, 1);
13322 
13323 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13324 MODULE_VERSION(vcxl, 1);
13325 
13326 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13327 MODULE_VERSION(vcc, 1);
13328