xref: /freebsd-14.2/sys/dev/cxgbe/t4_main.c (revision 7300dec1)
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 <[email protected]>
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 SLIST_HEAD(, uld_info) t4_uld_list;
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 get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
784 static void vi_refresh_stats(struct vi_info *);
785 static void cxgbe_refresh_stats(struct vi_info *);
786 static void cxgbe_tick(void *);
787 static void vi_tick(void *);
788 static void cxgbe_sysctls(struct port_info *);
789 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
790 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
791 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
792 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
793 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
794 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
795 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
796 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
797 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
798 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
799 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
800 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
801 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
802 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
803 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
804 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
805 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
806 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
807 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
808 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
809 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
810 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
811 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
812 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
813 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
814 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
817 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
820 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
822 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
824 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
825 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
826 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
827 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
828 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
829 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
830 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
831 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
837 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
838 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
839 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
840 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
841 #ifdef TCP_OFFLOAD
842 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
843 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
844 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
845 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
846 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
847 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
848 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
849 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
850 #endif
851 static int get_sge_context(struct adapter *, struct t4_sge_context *);
852 static int load_fw(struct adapter *, struct t4_data *);
853 static int load_cfg(struct adapter *, struct t4_data *);
854 static int load_boot(struct adapter *, struct t4_bootrom *);
855 static int load_bootcfg(struct adapter *, struct t4_data *);
856 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
857 static void free_offload_policy(struct t4_offload_policy *);
858 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
859 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
860 static int read_i2c(struct adapter *, struct t4_i2c_data *);
861 static int clear_stats(struct adapter *, u_int);
862 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
863 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
864 #ifdef TCP_OFFLOAD
865 static int toe_capability(struct vi_info *, bool);
866 static int t4_deactivate_all_uld(struct adapter *);
867 static void t4_async_event(struct adapter *);
868 #endif
869 #ifdef KERN_TLS
870 static int ktls_capability(struct adapter *, bool);
871 #endif
872 static int mod_event(module_t, int, void *);
873 static int notify_siblings(device_t, int);
874 static uint64_t vi_get_counter(if_t, ift_counter);
875 static uint64_t cxgbe_get_counter(if_t, ift_counter);
876 static void enable_vxlan_rx(struct adapter *);
877 static void reset_adapter_task(void *, int);
878 static void fatal_error_task(void *, int);
879 static void dump_devlog(struct adapter *);
880 static void dump_cim_regs(struct adapter *);
881 static void dump_cimla(struct adapter *);
882 
883 struct {
884 	uint16_t device;
885 	char *desc;
886 } t4_pciids[] = {
887 	{0xa000, "Chelsio Terminator 4 FPGA"},
888 	{0x4400, "Chelsio T440-dbg"},
889 	{0x4401, "Chelsio T420-CR"},
890 	{0x4402, "Chelsio T422-CR"},
891 	{0x4403, "Chelsio T440-CR"},
892 	{0x4404, "Chelsio T420-BCH"},
893 	{0x4405, "Chelsio T440-BCH"},
894 	{0x4406, "Chelsio T440-CH"},
895 	{0x4407, "Chelsio T420-SO"},
896 	{0x4408, "Chelsio T420-CX"},
897 	{0x4409, "Chelsio T420-BT"},
898 	{0x440a, "Chelsio T404-BT"},
899 	{0x440e, "Chelsio T440-LP-CR"},
900 }, t5_pciids[] = {
901 	{0xb000, "Chelsio Terminator 5 FPGA"},
902 	{0x5400, "Chelsio T580-dbg"},
903 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
904 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
905 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
906 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
907 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
908 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
909 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
910 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
911 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
912 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
913 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
914 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
915 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
916 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
917 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
918 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
919 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
920 
921 	/* Custom */
922 	{0x5483, "Custom T540-CR"},
923 	{0x5484, "Custom T540-BT"},
924 }, t6_pciids[] = {
925 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
926 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
927 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
928 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
929 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
930 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
931 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
932 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
933 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
934 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
935 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
936 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
937 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
938 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
939 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
940 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
941 
942 	/* Custom */
943 	{0x6480, "Custom T6225-CR"},
944 	{0x6481, "Custom T62100-CR"},
945 	{0x6482, "Custom T6225-CR"},
946 	{0x6483, "Custom T62100-CR"},
947 	{0x6484, "Custom T64100-CR"},
948 	{0x6485, "Custom T6240-SO"},
949 	{0x6486, "Custom T6225-SO-CR"},
950 	{0x6487, "Custom T6225-CR"},
951 };
952 
953 #ifdef TCP_OFFLOAD
954 /*
955  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
956  * be exactly the same for both rxq and ofld_rxq.
957  */
958 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
959 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
960 #endif
961 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
962 
963 static int
964 t4_probe(device_t dev)
965 {
966 	int i;
967 	uint16_t v = pci_get_vendor(dev);
968 	uint16_t d = pci_get_device(dev);
969 	uint8_t f = pci_get_function(dev);
970 
971 	if (v != PCI_VENDOR_ID_CHELSIO)
972 		return (ENXIO);
973 
974 	/* Attach only to PF0 of the FPGA */
975 	if (d == 0xa000 && f != 0)
976 		return (ENXIO);
977 
978 	for (i = 0; i < nitems(t4_pciids); i++) {
979 		if (d == t4_pciids[i].device) {
980 			device_set_desc(dev, t4_pciids[i].desc);
981 			return (BUS_PROBE_DEFAULT);
982 		}
983 	}
984 
985 	return (ENXIO);
986 }
987 
988 static int
989 t5_probe(device_t dev)
990 {
991 	int i;
992 	uint16_t v = pci_get_vendor(dev);
993 	uint16_t d = pci_get_device(dev);
994 	uint8_t f = pci_get_function(dev);
995 
996 	if (v != PCI_VENDOR_ID_CHELSIO)
997 		return (ENXIO);
998 
999 	/* Attach only to PF0 of the FPGA */
1000 	if (d == 0xb000 && f != 0)
1001 		return (ENXIO);
1002 
1003 	for (i = 0; i < nitems(t5_pciids); i++) {
1004 		if (d == t5_pciids[i].device) {
1005 			device_set_desc(dev, t5_pciids[i].desc);
1006 			return (BUS_PROBE_DEFAULT);
1007 		}
1008 	}
1009 
1010 	return (ENXIO);
1011 }
1012 
1013 static int
1014 t6_probe(device_t dev)
1015 {
1016 	int i;
1017 	uint16_t v = pci_get_vendor(dev);
1018 	uint16_t d = pci_get_device(dev);
1019 
1020 	if (v != PCI_VENDOR_ID_CHELSIO)
1021 		return (ENXIO);
1022 
1023 	for (i = 0; i < nitems(t6_pciids); i++) {
1024 		if (d == t6_pciids[i].device) {
1025 			device_set_desc(dev, t6_pciids[i].desc);
1026 			return (BUS_PROBE_DEFAULT);
1027 		}
1028 	}
1029 
1030 	return (ENXIO);
1031 }
1032 
1033 static void
1034 t5_attribute_workaround(device_t dev)
1035 {
1036 	device_t root_port;
1037 	uint32_t v;
1038 
1039 	/*
1040 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1041 	 * Ordering attributes when replying to a TLP from a Root
1042 	 * Port.  As a workaround, find the parent Root Port and
1043 	 * disable No Snoop and Relaxed Ordering.  Note that this
1044 	 * affects all devices under this root port.
1045 	 */
1046 	root_port = pci_find_pcie_root_port(dev);
1047 	if (root_port == NULL) {
1048 		device_printf(dev, "Unable to find parent root port\n");
1049 		return;
1050 	}
1051 
1052 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1053 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1054 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1055 	    0)
1056 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1057 		    device_get_nameunit(root_port));
1058 }
1059 
1060 static const struct devnames devnames[] = {
1061 	{
1062 		.nexus_name = "t4nex",
1063 		.ifnet_name = "cxgbe",
1064 		.vi_ifnet_name = "vcxgbe",
1065 		.pf03_drv_name = "t4iov",
1066 		.vf_nexus_name = "t4vf",
1067 		.vf_ifnet_name = "cxgbev"
1068 	}, {
1069 		.nexus_name = "t5nex",
1070 		.ifnet_name = "cxl",
1071 		.vi_ifnet_name = "vcxl",
1072 		.pf03_drv_name = "t5iov",
1073 		.vf_nexus_name = "t5vf",
1074 		.vf_ifnet_name = "cxlv"
1075 	}, {
1076 		.nexus_name = "t6nex",
1077 		.ifnet_name = "cc",
1078 		.vi_ifnet_name = "vcc",
1079 		.pf03_drv_name = "t6iov",
1080 		.vf_nexus_name = "t6vf",
1081 		.vf_ifnet_name = "ccv"
1082 	}
1083 };
1084 
1085 void
1086 t4_init_devnames(struct adapter *sc)
1087 {
1088 	int id;
1089 
1090 	id = chip_id(sc);
1091 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1092 		sc->names = &devnames[id - CHELSIO_T4];
1093 	else {
1094 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1095 		sc->names = NULL;
1096 	}
1097 }
1098 
1099 static int
1100 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1101 {
1102 	const char *parent, *name;
1103 	long value;
1104 	int line, unit;
1105 
1106 	line = 0;
1107 	parent = device_get_nameunit(sc->dev);
1108 	name = sc->names->ifnet_name;
1109 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1110 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1111 		    value == pi->port_id)
1112 			return (unit);
1113 	}
1114 	return (-1);
1115 }
1116 
1117 static void
1118 t4_calibration(void *arg)
1119 {
1120 	struct adapter *sc;
1121 	struct clock_sync *cur, *nex;
1122 	uint64_t hw;
1123 	sbintime_t sbt;
1124 	int next_up;
1125 
1126 	sc = (struct adapter *)arg;
1127 
1128 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1129 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1130 	sbt = sbinuptime();
1131 
1132 	cur = &sc->cal_info[sc->cal_current];
1133 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1134 	nex = &sc->cal_info[next_up];
1135 	if (__predict_false(sc->cal_count == 0)) {
1136 		/* First time in, just get the values in */
1137 		cur->hw_cur = hw;
1138 		cur->sbt_cur = sbt;
1139 		sc->cal_count++;
1140 		goto done;
1141 	}
1142 
1143 	if (cur->hw_cur == hw) {
1144 		/* The clock is not advancing? */
1145 		sc->cal_count = 0;
1146 		atomic_store_rel_int(&cur->gen, 0);
1147 		goto done;
1148 	}
1149 
1150 	seqc_write_begin(&nex->gen);
1151 	nex->hw_prev = cur->hw_cur;
1152 	nex->sbt_prev = cur->sbt_cur;
1153 	nex->hw_cur = hw;
1154 	nex->sbt_cur = sbt;
1155 	seqc_write_end(&nex->gen);
1156 	sc->cal_current = next_up;
1157 done:
1158 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1159 	    sc, C_DIRECT_EXEC);
1160 }
1161 
1162 static void
1163 t4_calibration_start(struct adapter *sc)
1164 {
1165 	/*
1166 	 * Here if we have not done a calibration
1167 	 * then do so otherwise start the appropriate
1168 	 * timer.
1169 	 */
1170 	int i;
1171 
1172 	for (i = 0; i < CNT_CAL_INFO; i++) {
1173 		sc->cal_info[i].gen = 0;
1174 	}
1175 	sc->cal_current = 0;
1176 	sc->cal_count = 0;
1177 	sc->cal_gen = 0;
1178 	t4_calibration(sc);
1179 }
1180 
1181 static int
1182 t4_attach(device_t dev)
1183 {
1184 	struct adapter *sc;
1185 	int rc = 0, i, j, rqidx, tqidx, nports;
1186 	struct make_dev_args mda;
1187 	struct intrs_and_queues iaq;
1188 	struct sge *s;
1189 	uint32_t *buf;
1190 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1191 	int ofld_tqidx;
1192 #endif
1193 #ifdef TCP_OFFLOAD
1194 	int ofld_rqidx;
1195 #endif
1196 #ifdef DEV_NETMAP
1197 	int nm_rqidx, nm_tqidx;
1198 #endif
1199 	int num_vis;
1200 
1201 	sc = device_get_softc(dev);
1202 	sc->dev = dev;
1203 	sysctl_ctx_init(&sc->ctx);
1204 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1205 
1206 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1207 		t5_attribute_workaround(dev);
1208 	pci_enable_busmaster(dev);
1209 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1210 		uint32_t v;
1211 
1212 		pci_set_max_read_req(dev, 4096);
1213 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1214 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1215 		if (pcie_relaxed_ordering == 0 &&
1216 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1217 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1218 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1219 		} else if (pcie_relaxed_ordering == 1 &&
1220 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1221 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1222 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1223 		}
1224 	}
1225 
1226 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1227 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1228 	sc->traceq = -1;
1229 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1230 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1231 	    device_get_nameunit(dev));
1232 
1233 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1234 	    device_get_nameunit(dev));
1235 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1236 	t4_add_adapter(sc);
1237 
1238 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1239 	TAILQ_INIT(&sc->sfl);
1240 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1241 
1242 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1243 
1244 	sc->policy = NULL;
1245 	rw_init(&sc->policy_lock, "connection offload policy");
1246 
1247 	callout_init(&sc->ktls_tick, 1);
1248 
1249 	callout_init(&sc->cal_callout, 1);
1250 
1251 	refcount_init(&sc->vxlan_refcount, 0);
1252 
1253 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1254 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1255 
1256 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1257 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1258 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1259 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1260 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1261 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1262 
1263 	rc = t4_map_bars_0_and_4(sc);
1264 	if (rc != 0)
1265 		goto done; /* error message displayed already */
1266 
1267 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1268 
1269 	/* Prepare the adapter for operation. */
1270 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1271 	rc = -t4_prep_adapter(sc, buf);
1272 	free(buf, M_CXGBE);
1273 	if (rc != 0) {
1274 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1275 		goto done;
1276 	}
1277 
1278 	/*
1279 	 * This is the real PF# to which we're attaching.  Works from within PCI
1280 	 * passthrough environments too, where pci_get_function() could return a
1281 	 * different PF# depending on the passthrough configuration.  We need to
1282 	 * use the real PF# in all our communication with the firmware.
1283 	 */
1284 	j = t4_read_reg(sc, A_PL_WHOAMI);
1285 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1286 	sc->mbox = sc->pf;
1287 
1288 	t4_init_devnames(sc);
1289 	if (sc->names == NULL) {
1290 		rc = ENOTSUP;
1291 		goto done; /* error message displayed already */
1292 	}
1293 
1294 	/*
1295 	 * Do this really early, with the memory windows set up even before the
1296 	 * character device.  The userland tool's register i/o and mem read
1297 	 * will work even in "recovery mode".
1298 	 */
1299 	setup_memwin(sc);
1300 	if (t4_init_devlog_params(sc, 0) == 0)
1301 		fixup_devlog_params(sc);
1302 	make_dev_args_init(&mda);
1303 	mda.mda_devsw = &t4_cdevsw;
1304 	mda.mda_uid = UID_ROOT;
1305 	mda.mda_gid = GID_WHEEL;
1306 	mda.mda_mode = 0600;
1307 	mda.mda_si_drv1 = sc;
1308 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1309 	if (rc != 0)
1310 		device_printf(dev, "failed to create nexus char device: %d.\n",
1311 		    rc);
1312 
1313 	/* Go no further if recovery mode has been requested. */
1314 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1315 		device_printf(dev, "recovery mode.\n");
1316 		goto done;
1317 	}
1318 
1319 #if defined(__i386__)
1320 	if ((cpu_feature & CPUID_CX8) == 0) {
1321 		device_printf(dev, "64 bit atomics not available.\n");
1322 		rc = ENOTSUP;
1323 		goto done;
1324 	}
1325 #endif
1326 
1327 	/* Contact the firmware and try to become the master driver. */
1328 	rc = contact_firmware(sc);
1329 	if (rc != 0)
1330 		goto done; /* error message displayed already */
1331 	MPASS(sc->flags & FW_OK);
1332 
1333 	rc = get_params__pre_init(sc);
1334 	if (rc != 0)
1335 		goto done; /* error message displayed already */
1336 
1337 	if (sc->flags & MASTER_PF) {
1338 		rc = partition_resources(sc);
1339 		if (rc != 0)
1340 			goto done; /* error message displayed already */
1341 	}
1342 
1343 	rc = get_params__post_init(sc);
1344 	if (rc != 0)
1345 		goto done; /* error message displayed already */
1346 
1347 	rc = set_params__post_init(sc);
1348 	if (rc != 0)
1349 		goto done; /* error message displayed already */
1350 
1351 	rc = t4_map_bar_2(sc);
1352 	if (rc != 0)
1353 		goto done; /* error message displayed already */
1354 
1355 	rc = t4_adj_doorbells(sc);
1356 	if (rc != 0)
1357 		goto done; /* error message displayed already */
1358 
1359 	rc = t4_create_dma_tag(sc);
1360 	if (rc != 0)
1361 		goto done; /* error message displayed already */
1362 
1363 	/*
1364 	 * First pass over all the ports - allocate VIs and initialize some
1365 	 * basic parameters like mac address, port type, etc.
1366 	 */
1367 	for_each_port(sc, i) {
1368 		struct port_info *pi;
1369 
1370 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1371 		sc->port[i] = pi;
1372 
1373 		/* These must be set before t4_port_init */
1374 		pi->adapter = sc;
1375 		pi->port_id = i;
1376 		/*
1377 		 * XXX: vi[0] is special so we can't delay this allocation until
1378 		 * pi->nvi's final value is known.
1379 		 */
1380 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1381 		    M_ZERO | M_WAITOK);
1382 
1383 		/*
1384 		 * Allocate the "main" VI and initialize parameters
1385 		 * like mac addr.
1386 		 */
1387 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1388 		if (rc != 0) {
1389 			device_printf(dev, "unable to initialize port %d: %d\n",
1390 			    i, rc);
1391 			free(pi->vi, M_CXGBE);
1392 			free(pi, M_CXGBE);
1393 			sc->port[i] = NULL;
1394 			goto done;
1395 		}
1396 
1397 		if (is_bt(pi->port_type))
1398 			setbit(&sc->bt_map, pi->tx_chan);
1399 		else
1400 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1401 
1402 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1403 		    device_get_nameunit(dev), i);
1404 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1405 		sc->chan_map[pi->tx_chan] = i;
1406 
1407 		/*
1408 		 * The MPS counter for FCS errors doesn't work correctly on the
1409 		 * T6 so we use the MAC counter here.  Which MAC is in use
1410 		 * depends on the link settings which will be known when the
1411 		 * link comes up.
1412 		 */
1413 		if (is_t6(sc))
1414 			pi->fcs_reg = -1;
1415 		else {
1416 			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1417 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1418 		}
1419 		pi->fcs_base = 0;
1420 
1421 		/* All VIs on this port share this media. */
1422 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1423 		    cxgbe_media_status);
1424 
1425 		PORT_LOCK(pi);
1426 		init_link_config(pi);
1427 		fixup_link_config(pi);
1428 		build_medialist(pi);
1429 		if (fixed_ifmedia(pi))
1430 			pi->flags |= FIXED_IFMEDIA;
1431 		PORT_UNLOCK(pi);
1432 
1433 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1434 		    t4_ifnet_unit(sc, pi));
1435 		if (pi->dev == NULL) {
1436 			device_printf(dev,
1437 			    "failed to add device for port %d.\n", i);
1438 			rc = ENXIO;
1439 			goto done;
1440 		}
1441 		pi->vi[0].dev = pi->dev;
1442 		device_set_softc(pi->dev, pi);
1443 	}
1444 
1445 	/*
1446 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1447 	 */
1448 	nports = sc->params.nports;
1449 	rc = cfg_itype_and_nqueues(sc, &iaq);
1450 	if (rc != 0)
1451 		goto done; /* error message displayed already */
1452 
1453 	num_vis = iaq.num_vis;
1454 	sc->intr_type = iaq.intr_type;
1455 	sc->intr_count = iaq.nirq;
1456 
1457 	s = &sc->sge;
1458 	s->nrxq = nports * iaq.nrxq;
1459 	s->ntxq = nports * iaq.ntxq;
1460 	if (num_vis > 1) {
1461 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1462 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1463 	}
1464 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1465 	s->neq += nports;		/* ctrl queues: 1 per port */
1466 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1467 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1468 	if (is_offload(sc) || is_ethoffload(sc)) {
1469 		s->nofldtxq = nports * iaq.nofldtxq;
1470 		if (num_vis > 1)
1471 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1472 		s->neq += s->nofldtxq;
1473 
1474 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1475 		    M_CXGBE, M_ZERO | M_WAITOK);
1476 	}
1477 #endif
1478 #ifdef TCP_OFFLOAD
1479 	if (is_offload(sc)) {
1480 		s->nofldrxq = nports * iaq.nofldrxq;
1481 		if (num_vis > 1)
1482 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1483 		s->neq += s->nofldrxq;	/* free list */
1484 		s->niq += s->nofldrxq;
1485 
1486 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1487 		    M_CXGBE, M_ZERO | M_WAITOK);
1488 	}
1489 #endif
1490 #ifdef DEV_NETMAP
1491 	s->nnmrxq = 0;
1492 	s->nnmtxq = 0;
1493 	if (t4_native_netmap & NN_MAIN_VI) {
1494 		s->nnmrxq += nports * iaq.nnmrxq;
1495 		s->nnmtxq += nports * iaq.nnmtxq;
1496 	}
1497 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1498 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1499 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1500 	}
1501 	s->neq += s->nnmtxq + s->nnmrxq;
1502 	s->niq += s->nnmrxq;
1503 
1504 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1505 	    M_CXGBE, M_ZERO | M_WAITOK);
1506 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1507 	    M_CXGBE, M_ZERO | M_WAITOK);
1508 #endif
1509 	MPASS(s->niq <= s->iqmap_sz);
1510 	MPASS(s->neq <= s->eqmap_sz);
1511 
1512 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1513 	    M_ZERO | M_WAITOK);
1514 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1515 	    M_ZERO | M_WAITOK);
1516 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1517 	    M_ZERO | M_WAITOK);
1518 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1519 	    M_ZERO | M_WAITOK);
1520 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1521 	    M_ZERO | M_WAITOK);
1522 
1523 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1524 	    M_ZERO | M_WAITOK);
1525 
1526 	t4_init_l2t(sc, M_WAITOK);
1527 	t4_init_smt(sc, M_WAITOK);
1528 	t4_init_tx_sched(sc);
1529 	t4_init_atid_table(sc);
1530 #ifdef RATELIMIT
1531 	t4_init_etid_table(sc);
1532 #endif
1533 #ifdef INET6
1534 	t4_init_clip_table(sc);
1535 #endif
1536 	if (sc->vres.key.size != 0)
1537 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1538 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1539 
1540 	/*
1541 	 * Second pass over the ports.  This time we know the number of rx and
1542 	 * tx queues that each port should get.
1543 	 */
1544 	rqidx = tqidx = 0;
1545 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1546 	ofld_tqidx = 0;
1547 #endif
1548 #ifdef TCP_OFFLOAD
1549 	ofld_rqidx = 0;
1550 #endif
1551 #ifdef DEV_NETMAP
1552 	nm_rqidx = nm_tqidx = 0;
1553 #endif
1554 	for_each_port(sc, i) {
1555 		struct port_info *pi = sc->port[i];
1556 		struct vi_info *vi;
1557 
1558 		if (pi == NULL)
1559 			continue;
1560 
1561 		pi->nvi = num_vis;
1562 		for_each_vi(pi, j, vi) {
1563 			vi->pi = pi;
1564 			vi->adapter = sc;
1565 			vi->first_intr = -1;
1566 			vi->qsize_rxq = t4_qsize_rxq;
1567 			vi->qsize_txq = t4_qsize_txq;
1568 
1569 			vi->first_rxq = rqidx;
1570 			vi->first_txq = tqidx;
1571 			vi->tmr_idx = t4_tmr_idx;
1572 			vi->pktc_idx = t4_pktc_idx;
1573 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1574 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1575 
1576 			rqidx += vi->nrxq;
1577 			tqidx += vi->ntxq;
1578 
1579 			if (j == 0 && vi->ntxq > 1)
1580 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1581 			else
1582 				vi->rsrv_noflowq = 0;
1583 
1584 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1585 			vi->first_ofld_txq = ofld_tqidx;
1586 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1587 			ofld_tqidx += vi->nofldtxq;
1588 #endif
1589 #ifdef TCP_OFFLOAD
1590 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1591 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1592 			vi->first_ofld_rxq = ofld_rqidx;
1593 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1594 
1595 			ofld_rqidx += vi->nofldrxq;
1596 #endif
1597 #ifdef DEV_NETMAP
1598 			vi->first_nm_rxq = nm_rqidx;
1599 			vi->first_nm_txq = nm_tqidx;
1600 			if (j == 0) {
1601 				vi->nnmrxq = iaq.nnmrxq;
1602 				vi->nnmtxq = iaq.nnmtxq;
1603 			} else {
1604 				vi->nnmrxq = iaq.nnmrxq_vi;
1605 				vi->nnmtxq = iaq.nnmtxq_vi;
1606 			}
1607 			nm_rqidx += vi->nnmrxq;
1608 			nm_tqidx += vi->nnmtxq;
1609 #endif
1610 		}
1611 	}
1612 
1613 	rc = t4_setup_intr_handlers(sc);
1614 	if (rc != 0) {
1615 		device_printf(dev,
1616 		    "failed to setup interrupt handlers: %d\n", rc);
1617 		goto done;
1618 	}
1619 
1620 	rc = bus_generic_probe(dev);
1621 	if (rc != 0) {
1622 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1623 		goto done;
1624 	}
1625 
1626 	/*
1627 	 * Ensure thread-safe mailbox access (in debug builds).
1628 	 *
1629 	 * So far this was the only thread accessing the mailbox but various
1630 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1631 	 * will access the mailbox from different threads.
1632 	 */
1633 	sc->flags |= CHK_MBOX_ACCESS;
1634 
1635 	rc = bus_generic_attach(dev);
1636 	if (rc != 0) {
1637 		device_printf(dev,
1638 		    "failed to attach all child ports: %d\n", rc);
1639 		goto done;
1640 	}
1641 	t4_calibration_start(sc);
1642 
1643 	device_printf(dev,
1644 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1645 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1646 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1647 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1648 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1649 
1650 	t4_set_desc(sc);
1651 
1652 	notify_siblings(dev, 0);
1653 
1654 done:
1655 	if (rc != 0 && sc->cdev) {
1656 		/* cdev was created and so cxgbetool works; recover that way. */
1657 		device_printf(dev,
1658 		    "error during attach, adapter is now in recovery mode.\n");
1659 		rc = 0;
1660 	}
1661 
1662 	if (rc != 0)
1663 		t4_detach_common(dev);
1664 	else
1665 		t4_sysctls(sc);
1666 
1667 	return (rc);
1668 }
1669 
1670 static int
1671 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1672 {
1673 	struct adapter *sc;
1674 	struct port_info *pi;
1675 	int i;
1676 
1677 	sc = device_get_softc(bus);
1678 	for_each_port(sc, i) {
1679 		pi = sc->port[i];
1680 		if (pi != NULL && pi->dev == dev) {
1681 			sbuf_printf(sb, "port=%d", pi->port_id);
1682 			break;
1683 		}
1684 	}
1685 	return (0);
1686 }
1687 
1688 static int
1689 t4_ready(device_t dev)
1690 {
1691 	struct adapter *sc;
1692 
1693 	sc = device_get_softc(dev);
1694 	if (sc->flags & FW_OK)
1695 		return (0);
1696 	return (ENXIO);
1697 }
1698 
1699 static int
1700 t4_read_port_device(device_t dev, int port, device_t *child)
1701 {
1702 	struct adapter *sc;
1703 	struct port_info *pi;
1704 
1705 	sc = device_get_softc(dev);
1706 	if (port < 0 || port >= MAX_NPORTS)
1707 		return (EINVAL);
1708 	pi = sc->port[port];
1709 	if (pi == NULL || pi->dev == NULL)
1710 		return (ENXIO);
1711 	*child = pi->dev;
1712 	return (0);
1713 }
1714 
1715 static int
1716 notify_siblings(device_t dev, int detaching)
1717 {
1718 	device_t sibling;
1719 	int error, i;
1720 
1721 	error = 0;
1722 	for (i = 0; i < PCI_FUNCMAX; i++) {
1723 		if (i == pci_get_function(dev))
1724 			continue;
1725 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1726 		    pci_get_slot(dev), i);
1727 		if (sibling == NULL || !device_is_attached(sibling))
1728 			continue;
1729 		if (detaching)
1730 			error = T4_DETACH_CHILD(sibling);
1731 		else
1732 			(void)T4_ATTACH_CHILD(sibling);
1733 		if (error)
1734 			break;
1735 	}
1736 	return (error);
1737 }
1738 
1739 /*
1740  * Idempotent
1741  */
1742 static int
1743 t4_detach(device_t dev)
1744 {
1745 	int rc;
1746 
1747 	rc = notify_siblings(dev, 1);
1748 	if (rc) {
1749 		device_printf(dev,
1750 		    "failed to detach sibling devices: %d\n", rc);
1751 		return (rc);
1752 	}
1753 
1754 	return (t4_detach_common(dev));
1755 }
1756 
1757 int
1758 t4_detach_common(device_t dev)
1759 {
1760 	struct adapter *sc;
1761 	struct port_info *pi;
1762 	int i, rc;
1763 
1764 	sc = device_get_softc(dev);
1765 
1766 #ifdef TCP_OFFLOAD
1767 	rc = t4_deactivate_all_uld(sc);
1768 	if (rc) {
1769 		device_printf(dev,
1770 		    "failed to detach upper layer drivers: %d\n", rc);
1771 		return (rc);
1772 	}
1773 #endif
1774 
1775 	if (sc->cdev) {
1776 		destroy_dev(sc->cdev);
1777 		sc->cdev = NULL;
1778 	}
1779 
1780 	sx_xlock(&t4_list_lock);
1781 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1782 	sx_xunlock(&t4_list_lock);
1783 
1784 	sc->flags &= ~CHK_MBOX_ACCESS;
1785 	if (sc->flags & FULL_INIT_DONE) {
1786 		if (!(sc->flags & IS_VF))
1787 			t4_intr_disable(sc);
1788 	}
1789 
1790 	if (device_is_attached(dev)) {
1791 		rc = bus_generic_detach(dev);
1792 		if (rc) {
1793 			device_printf(dev,
1794 			    "failed to detach child devices: %d\n", rc);
1795 			return (rc);
1796 		}
1797 	}
1798 
1799 	for (i = 0; i < sc->intr_count; i++)
1800 		t4_free_irq(sc, &sc->irq[i]);
1801 
1802 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1803 		t4_free_tx_sched(sc);
1804 
1805 	for (i = 0; i < MAX_NPORTS; i++) {
1806 		pi = sc->port[i];
1807 		if (pi) {
1808 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1809 			if (pi->dev)
1810 				device_delete_child(dev, pi->dev);
1811 
1812 			mtx_destroy(&pi->pi_lock);
1813 			free(pi->vi, M_CXGBE);
1814 			free(pi, M_CXGBE);
1815 		}
1816 	}
1817 	callout_stop(&sc->cal_callout);
1818 	callout_drain(&sc->cal_callout);
1819 	device_delete_children(dev);
1820 	sysctl_ctx_free(&sc->ctx);
1821 	adapter_full_uninit(sc);
1822 
1823 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1824 		t4_fw_bye(sc, sc->mbox);
1825 
1826 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1827 		pci_release_msi(dev);
1828 
1829 	if (sc->regs_res)
1830 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1831 		    sc->regs_res);
1832 
1833 	if (sc->udbs_res)
1834 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1835 		    sc->udbs_res);
1836 
1837 	if (sc->msix_res)
1838 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1839 		    sc->msix_res);
1840 
1841 	if (sc->l2t)
1842 		t4_free_l2t(sc->l2t);
1843 	if (sc->smt)
1844 		t4_free_smt(sc->smt);
1845 	t4_free_atid_table(sc);
1846 #ifdef RATELIMIT
1847 	t4_free_etid_table(sc);
1848 #endif
1849 	if (sc->key_map)
1850 		vmem_destroy(sc->key_map);
1851 #ifdef INET6
1852 	t4_destroy_clip_table(sc);
1853 #endif
1854 
1855 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1856 	free(sc->sge.ofld_txq, M_CXGBE);
1857 #endif
1858 #ifdef TCP_OFFLOAD
1859 	free(sc->sge.ofld_rxq, M_CXGBE);
1860 #endif
1861 #ifdef DEV_NETMAP
1862 	free(sc->sge.nm_rxq, M_CXGBE);
1863 	free(sc->sge.nm_txq, M_CXGBE);
1864 #endif
1865 	free(sc->irq, M_CXGBE);
1866 	free(sc->sge.rxq, M_CXGBE);
1867 	free(sc->sge.txq, M_CXGBE);
1868 	free(sc->sge.ctrlq, M_CXGBE);
1869 	free(sc->sge.iqmap, M_CXGBE);
1870 	free(sc->sge.eqmap, M_CXGBE);
1871 	free(sc->tids.ftid_tab, M_CXGBE);
1872 	free(sc->tids.hpftid_tab, M_CXGBE);
1873 	free_hftid_hash(&sc->tids);
1874 	free(sc->tids.tid_tab, M_CXGBE);
1875 	t4_destroy_dma_tag(sc);
1876 
1877 	callout_drain(&sc->ktls_tick);
1878 	callout_drain(&sc->sfl_callout);
1879 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1880 		mtx_destroy(&sc->tids.ftid_lock);
1881 		cv_destroy(&sc->tids.ftid_cv);
1882 	}
1883 	if (mtx_initialized(&sc->tids.atid_lock))
1884 		mtx_destroy(&sc->tids.atid_lock);
1885 	if (mtx_initialized(&sc->ifp_lock))
1886 		mtx_destroy(&sc->ifp_lock);
1887 
1888 	if (rw_initialized(&sc->policy_lock)) {
1889 		rw_destroy(&sc->policy_lock);
1890 #ifdef TCP_OFFLOAD
1891 		if (sc->policy != NULL)
1892 			free_offload_policy(sc->policy);
1893 #endif
1894 	}
1895 
1896 	for (i = 0; i < NUM_MEMWIN; i++) {
1897 		struct memwin *mw = &sc->memwin[i];
1898 
1899 		if (rw_initialized(&mw->mw_lock))
1900 			rw_destroy(&mw->mw_lock);
1901 	}
1902 
1903 	mtx_destroy(&sc->sfl_lock);
1904 	mtx_destroy(&sc->reg_lock);
1905 	mtx_destroy(&sc->sc_lock);
1906 
1907 	bzero(sc, sizeof(*sc));
1908 
1909 	return (0);
1910 }
1911 
1912 static inline bool
1913 ok_to_reset(struct adapter *sc)
1914 {
1915 	struct tid_info *t = &sc->tids;
1916 	struct port_info *pi;
1917 	struct vi_info *vi;
1918 	int i, j;
1919 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1920 
1921 	if (is_t6(sc))
1922 		caps |= IFCAP_TXTLS;
1923 
1924 	ASSERT_SYNCHRONIZED_OP(sc);
1925 	MPASS(!(sc->flags & IS_VF));
1926 
1927 	for_each_port(sc, i) {
1928 		pi = sc->port[i];
1929 		for_each_vi(pi, j, vi) {
1930 			if (if_getcapenable(vi->ifp) & caps)
1931 				return (false);
1932 		}
1933 	}
1934 
1935 	if (atomic_load_int(&t->tids_in_use) > 0)
1936 		return (false);
1937 	if (atomic_load_int(&t->stids_in_use) > 0)
1938 		return (false);
1939 	if (atomic_load_int(&t->atids_in_use) > 0)
1940 		return (false);
1941 	if (atomic_load_int(&t->ftids_in_use) > 0)
1942 		return (false);
1943 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1944 		return (false);
1945 	if (atomic_load_int(&t->etids_in_use) > 0)
1946 		return (false);
1947 
1948 	return (true);
1949 }
1950 
1951 static inline int
1952 stop_adapter(struct adapter *sc)
1953 {
1954 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1955 		return (1);		/* Already stopped. */
1956 	return (t4_shutdown_adapter(sc));
1957 }
1958 
1959 static int
1960 t4_suspend(device_t dev)
1961 {
1962 	struct adapter *sc = device_get_softc(dev);
1963 	struct port_info *pi;
1964 	struct vi_info *vi;
1965 	if_t ifp;
1966 	struct sge_rxq *rxq;
1967 	struct sge_txq *txq;
1968 	struct sge_wrq *wrq;
1969 #ifdef TCP_OFFLOAD
1970 	struct sge_ofld_rxq *ofld_rxq;
1971 #endif
1972 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1973 	struct sge_ofld_txq *ofld_txq;
1974 #endif
1975 	int rc, i, j, k;
1976 
1977 	CH_ALERT(sc, "suspend requested\n");
1978 
1979 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1980 	if (rc != 0)
1981 		return (ENXIO);
1982 
1983 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1984 	MPASS(!hw_off_limits(sc));
1985 
1986 	if (!ok_to_reset(sc)) {
1987 		/* XXX: should list what resource is preventing suspend. */
1988 		CH_ERR(sc, "not safe to suspend.\n");
1989 		rc = EBUSY;
1990 		goto done;
1991 	}
1992 
1993 	/* No more DMA or interrupts. */
1994 	stop_adapter(sc);
1995 
1996 	/* Quiesce all activity. */
1997 	for_each_port(sc, i) {
1998 		pi = sc->port[i];
1999 		pi->vxlan_tcam_entry = false;
2000 
2001 		PORT_LOCK(pi);
2002 		if (pi->up_vis > 0) {
2003 			/*
2004 			 * t4_shutdown_adapter has already shut down all the
2005 			 * PHYs but it also disables interrupts and DMA so there
2006 			 * won't be a link interrupt.  So we update the state
2007 			 * manually and inform the kernel.
2008 			 */
2009 			pi->link_cfg.link_ok = false;
2010 			t4_os_link_changed(pi);
2011 		}
2012 		PORT_UNLOCK(pi);
2013 
2014 		for_each_vi(pi, j, vi) {
2015 			vi->xact_addr_filt = -1;
2016 			mtx_lock(&vi->tick_mtx);
2017 			vi->flags |= VI_SKIP_STATS;
2018 			mtx_unlock(&vi->tick_mtx);
2019 			if (!(vi->flags & VI_INIT_DONE))
2020 				continue;
2021 
2022 			ifp = vi->ifp;
2023 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2024 				mtx_lock(&vi->tick_mtx);
2025 				callout_stop(&vi->tick);
2026 				mtx_unlock(&vi->tick_mtx);
2027 				callout_drain(&vi->tick);
2028 			}
2029 
2030 			/*
2031 			 * Note that the HW is not available.
2032 			 */
2033 			for_each_txq(vi, k, txq) {
2034 				TXQ_LOCK(txq);
2035 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2036 				TXQ_UNLOCK(txq);
2037 			}
2038 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2039 			for_each_ofld_txq(vi, k, ofld_txq) {
2040 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2041 			}
2042 #endif
2043 			for_each_rxq(vi, k, rxq) {
2044 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2045 			}
2046 #if defined(TCP_OFFLOAD)
2047 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2048 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2049 			}
2050 #endif
2051 
2052 			quiesce_vi(vi);
2053 		}
2054 
2055 		if (sc->flags & FULL_INIT_DONE) {
2056 			/* Control queue */
2057 			wrq = &sc->sge.ctrlq[i];
2058 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2059 			quiesce_wrq(wrq);
2060 		}
2061 	}
2062 	if (sc->flags & FULL_INIT_DONE) {
2063 		/* Firmware event queue */
2064 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2065 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2066 	}
2067 
2068 	/* Stop calibration */
2069 	callout_stop(&sc->cal_callout);
2070 	callout_drain(&sc->cal_callout);
2071 
2072 	/* Mark the adapter totally off limits. */
2073 	mtx_lock(&sc->reg_lock);
2074 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2075 	sc->flags &= ~(FW_OK | MASTER_PF);
2076 	sc->reset_thread = NULL;
2077 	mtx_unlock(&sc->reg_lock);
2078 
2079 	if (t4_clock_gate_on_suspend) {
2080 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2081 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2082 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2083 	}
2084 
2085 	CH_ALERT(sc, "suspend completed.\n");
2086 done:
2087 	end_synchronized_op(sc, 0);
2088 	return (rc);
2089 }
2090 
2091 struct adapter_pre_reset_state {
2092 	u_int flags;
2093 	uint16_t nbmcaps;
2094 	uint16_t linkcaps;
2095 	uint16_t switchcaps;
2096 	uint16_t niccaps;
2097 	uint16_t toecaps;
2098 	uint16_t rdmacaps;
2099 	uint16_t cryptocaps;
2100 	uint16_t iscsicaps;
2101 	uint16_t fcoecaps;
2102 
2103 	u_int cfcsum;
2104 	char cfg_file[32];
2105 
2106 	struct adapter_params params;
2107 	struct t4_virt_res vres;
2108 	struct tid_info tids;
2109 	struct sge sge;
2110 
2111 	int rawf_base;
2112 	int nrawf;
2113 
2114 };
2115 
2116 static void
2117 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2118 {
2119 
2120 	ASSERT_SYNCHRONIZED_OP(sc);
2121 
2122 	o->flags = sc->flags;
2123 
2124 	o->nbmcaps =  sc->nbmcaps;
2125 	o->linkcaps = sc->linkcaps;
2126 	o->switchcaps = sc->switchcaps;
2127 	o->niccaps = sc->niccaps;
2128 	o->toecaps = sc->toecaps;
2129 	o->rdmacaps = sc->rdmacaps;
2130 	o->cryptocaps = sc->cryptocaps;
2131 	o->iscsicaps = sc->iscsicaps;
2132 	o->fcoecaps = sc->fcoecaps;
2133 
2134 	o->cfcsum = sc->cfcsum;
2135 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2136 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2137 
2138 	o->params = sc->params;
2139 	o->vres = sc->vres;
2140 	o->tids = sc->tids;
2141 	o->sge = sc->sge;
2142 
2143 	o->rawf_base = sc->rawf_base;
2144 	o->nrawf = sc->nrawf;
2145 }
2146 
2147 static int
2148 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2149 {
2150 	int rc = 0;
2151 
2152 	ASSERT_SYNCHRONIZED_OP(sc);
2153 
2154 	/* Capabilities */
2155 #define COMPARE_CAPS(c) do { \
2156 	if (o->c##caps != sc->c##caps) { \
2157 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2158 		    sc->c##caps); \
2159 		rc = EINVAL; \
2160 	} \
2161 } while (0)
2162 	COMPARE_CAPS(nbm);
2163 	COMPARE_CAPS(link);
2164 	COMPARE_CAPS(switch);
2165 	COMPARE_CAPS(nic);
2166 	COMPARE_CAPS(toe);
2167 	COMPARE_CAPS(rdma);
2168 	COMPARE_CAPS(crypto);
2169 	COMPARE_CAPS(iscsi);
2170 	COMPARE_CAPS(fcoe);
2171 #undef COMPARE_CAPS
2172 
2173 	/* Firmware config file */
2174 	if (o->cfcsum != sc->cfcsum) {
2175 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2176 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2177 		rc = EINVAL;
2178 	}
2179 
2180 #define COMPARE_PARAM(p, name) do { \
2181 	if (o->p != sc->p) { \
2182 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2183 		rc = EINVAL; \
2184 	} \
2185 } while (0)
2186 	COMPARE_PARAM(sge.iq_start, iq_start);
2187 	COMPARE_PARAM(sge.eq_start, eq_start);
2188 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2189 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2190 	COMPARE_PARAM(tids.nftids, nftids);
2191 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2192 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2193 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2194 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2195 	COMPARE_PARAM(tids.tid_base, tid_base);
2196 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2197 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2198 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2199 	COMPARE_PARAM(rawf_base, rawf_base);
2200 	COMPARE_PARAM(nrawf, nrawf);
2201 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2202 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2203 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2204 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2205 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2206 	COMPARE_PARAM(tids.ntids, ntids);
2207 	COMPARE_PARAM(tids.etid_base, etid_base);
2208 	COMPARE_PARAM(tids.etid_end, etid_end);
2209 	COMPARE_PARAM(tids.netids, netids);
2210 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2211 	COMPARE_PARAM(params.ethoffload, ethoffload);
2212 	COMPARE_PARAM(tids.natids, natids);
2213 	COMPARE_PARAM(tids.stid_base, stid_base);
2214 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2215 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2216 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2217 	COMPARE_PARAM(vres.stag.start, stag_start);
2218 	COMPARE_PARAM(vres.stag.size, stag_size);
2219 	COMPARE_PARAM(vres.rq.start, rq_start);
2220 	COMPARE_PARAM(vres.rq.size, rq_size);
2221 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2222 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2223 	COMPARE_PARAM(vres.qp.start, qp_start);
2224 	COMPARE_PARAM(vres.qp.size, qp_size);
2225 	COMPARE_PARAM(vres.cq.start, cq_start);
2226 	COMPARE_PARAM(vres.cq.size, cq_size);
2227 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2228 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2229 	COMPARE_PARAM(vres.srq.start, srq_start);
2230 	COMPARE_PARAM(vres.srq.size, srq_size);
2231 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2232 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2233 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2234 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2235 	COMPARE_PARAM(vres.key.start, key_start);
2236 	COMPARE_PARAM(vres.key.size, key_size);
2237 #undef COMPARE_PARAM
2238 
2239 	return (rc);
2240 }
2241 
2242 static int
2243 t4_resume(device_t dev)
2244 {
2245 	struct adapter *sc = device_get_softc(dev);
2246 	struct adapter_pre_reset_state *old_state = NULL;
2247 	struct port_info *pi;
2248 	struct vi_info *vi;
2249 	if_t ifp;
2250 	struct sge_txq *txq;
2251 	int rc, i, j, k;
2252 
2253 	CH_ALERT(sc, "resume requested.\n");
2254 
2255 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2256 	if (rc != 0)
2257 		return (ENXIO);
2258 	MPASS(hw_off_limits(sc));
2259 	MPASS((sc->flags & FW_OK) == 0);
2260 	MPASS((sc->flags & MASTER_PF) == 0);
2261 	MPASS(sc->reset_thread == NULL);
2262 	sc->reset_thread = curthread;
2263 
2264 	/* Register access is expected to work by the time we're here. */
2265 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2266 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2267 		rc = ENXIO;
2268 		goto done;
2269 	}
2270 
2271 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2272 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2273 
2274 	/* Restore memory window. */
2275 	setup_memwin(sc);
2276 
2277 	/* Go no further if recovery mode has been requested. */
2278 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2279 		CH_ALERT(sc, "recovery mode on resume.\n");
2280 		rc = 0;
2281 		mtx_lock(&sc->reg_lock);
2282 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2283 		mtx_unlock(&sc->reg_lock);
2284 		goto done;
2285 	}
2286 
2287 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2288 	save_caps_and_params(sc, old_state);
2289 
2290 	/* Reestablish contact with firmware and become the primary PF. */
2291 	rc = contact_firmware(sc);
2292 	if (rc != 0)
2293 		goto done; /* error message displayed already */
2294 	MPASS(sc->flags & FW_OK);
2295 
2296 	if (sc->flags & MASTER_PF) {
2297 		rc = partition_resources(sc);
2298 		if (rc != 0)
2299 			goto done; /* error message displayed already */
2300 	}
2301 
2302 	rc = get_params__post_init(sc);
2303 	if (rc != 0)
2304 		goto done; /* error message displayed already */
2305 
2306 	rc = set_params__post_init(sc);
2307 	if (rc != 0)
2308 		goto done; /* error message displayed already */
2309 
2310 	rc = compare_caps_and_params(sc, old_state);
2311 	if (rc != 0)
2312 		goto done; /* error message displayed already */
2313 
2314 	for_each_port(sc, i) {
2315 		pi = sc->port[i];
2316 		MPASS(pi != NULL);
2317 		MPASS(pi->vi != NULL);
2318 		MPASS(pi->vi[0].dev == pi->dev);
2319 
2320 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2321 		if (rc != 0) {
2322 			CH_ERR(sc,
2323 			    "failed to re-initialize port %d: %d\n", i, rc);
2324 			goto done;
2325 		}
2326 		MPASS(sc->chan_map[pi->tx_chan] == i);
2327 
2328 		PORT_LOCK(pi);
2329 		fixup_link_config(pi);
2330 		build_medialist(pi);
2331 		PORT_UNLOCK(pi);
2332 		for_each_vi(pi, j, vi) {
2333 			if (IS_MAIN_VI(vi))
2334 				continue;
2335 			rc = alloc_extra_vi(sc, pi, vi);
2336 			if (rc != 0) {
2337 				CH_ERR(vi,
2338 				    "failed to re-allocate extra VI: %d\n", rc);
2339 				goto done;
2340 			}
2341 		}
2342 	}
2343 
2344 	/*
2345 	 * Interrupts and queues are about to be enabled and other threads will
2346 	 * want to access the hardware too.  It is safe to do so.  Note that
2347 	 * this thread is still in the middle of a synchronized_op.
2348 	 */
2349 	mtx_lock(&sc->reg_lock);
2350 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2351 	mtx_unlock(&sc->reg_lock);
2352 
2353 	if (sc->flags & FULL_INIT_DONE) {
2354 		rc = adapter_full_init(sc);
2355 		if (rc != 0) {
2356 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2357 			goto done;
2358 		}
2359 
2360 		if (sc->vxlan_refcount > 0)
2361 			enable_vxlan_rx(sc);
2362 
2363 		for_each_port(sc, i) {
2364 			pi = sc->port[i];
2365 			for_each_vi(pi, j, vi) {
2366 				mtx_lock(&vi->tick_mtx);
2367 				vi->flags &= ~VI_SKIP_STATS;
2368 				mtx_unlock(&vi->tick_mtx);
2369 				if (!(vi->flags & VI_INIT_DONE))
2370 					continue;
2371 				rc = vi_full_init(vi);
2372 				if (rc != 0) {
2373 					CH_ERR(vi, "failed to re-initialize "
2374 					    "interface: %d\n", rc);
2375 					goto done;
2376 				}
2377 
2378 				ifp = vi->ifp;
2379 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2380 					continue;
2381 				/*
2382 				 * Note that we do not setup multicast addresses
2383 				 * in the first pass.  This ensures that the
2384 				 * unicast DMACs for all VIs on all ports get an
2385 				 * MPS TCAM entry.
2386 				 */
2387 				rc = update_mac_settings(ifp, XGMAC_ALL &
2388 				    ~XGMAC_MCADDRS);
2389 				if (rc != 0) {
2390 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2391 					goto done;
2392 				}
2393 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2394 				    true);
2395 				if (rc != 0) {
2396 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2397 					goto done;
2398 				}
2399 				for_each_txq(vi, k, txq) {
2400 					TXQ_LOCK(txq);
2401 					txq->eq.flags |= EQ_ENABLED;
2402 					TXQ_UNLOCK(txq);
2403 				}
2404 				mtx_lock(&vi->tick_mtx);
2405 				callout_schedule(&vi->tick, hz);
2406 				mtx_unlock(&vi->tick_mtx);
2407 			}
2408 			PORT_LOCK(pi);
2409 			if (pi->up_vis > 0) {
2410 				t4_update_port_info(pi);
2411 				fixup_link_config(pi);
2412 				build_medialist(pi);
2413 				apply_link_config(pi);
2414 				if (pi->link_cfg.link_ok)
2415 					t4_os_link_changed(pi);
2416 			}
2417 			PORT_UNLOCK(pi);
2418 		}
2419 
2420 		/* Now reprogram the L2 multicast addresses. */
2421 		for_each_port(sc, i) {
2422 			pi = sc->port[i];
2423 			for_each_vi(pi, j, vi) {
2424 				if (!(vi->flags & VI_INIT_DONE))
2425 					continue;
2426 				ifp = vi->ifp;
2427 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2428 					continue;
2429 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2430 				if (rc != 0) {
2431 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2432 					rc = 0;	/* carry on */
2433 				}
2434 			}
2435 		}
2436 	}
2437 
2438 	/* Reset all calibration */
2439 	t4_calibration_start(sc);
2440 
2441 done:
2442 	if (rc == 0) {
2443 		sc->incarnation++;
2444 		CH_ALERT(sc, "resume completed.\n");
2445 	}
2446 	end_synchronized_op(sc, 0);
2447 	free(old_state, M_CXGBE);
2448 	return (rc);
2449 }
2450 
2451 static int
2452 t4_reset_prepare(device_t dev, device_t child)
2453 {
2454 	struct adapter *sc = device_get_softc(dev);
2455 
2456 	CH_ALERT(sc, "reset_prepare.\n");
2457 	return (0);
2458 }
2459 
2460 static int
2461 t4_reset_post(device_t dev, device_t child)
2462 {
2463 	struct adapter *sc = device_get_softc(dev);
2464 
2465 	CH_ALERT(sc, "reset_post.\n");
2466 	return (0);
2467 }
2468 
2469 static int
2470 reset_adapter(struct adapter *sc)
2471 {
2472 	int rc, oldinc, error_flags;
2473 
2474 	CH_ALERT(sc, "reset requested.\n");
2475 
2476 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2477 	if (rc != 0)
2478 		return (EBUSY);
2479 
2480 	if (hw_off_limits(sc)) {
2481 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2482 		rc = ENXIO;
2483 		goto done;
2484 	}
2485 
2486 	if (!ok_to_reset(sc)) {
2487 		/* XXX: should list what resource is preventing reset. */
2488 		CH_ERR(sc, "not safe to reset.\n");
2489 		rc = EBUSY;
2490 		goto done;
2491 	}
2492 
2493 done:
2494 	oldinc = sc->incarnation;
2495 	end_synchronized_op(sc, 0);
2496 	if (rc != 0)
2497 		return (rc);	/* Error logged already. */
2498 
2499 	atomic_add_int(&sc->num_resets, 1);
2500 	mtx_lock(&Giant);
2501 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2502 	mtx_unlock(&Giant);
2503 	if (rc != 0)
2504 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2505 	else {
2506 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2507 		if (rc != 0)
2508 			return (EBUSY);
2509 		error_flags = atomic_load_int(&sc->error_flags);
2510 		if (sc->incarnation > oldinc && error_flags == 0) {
2511 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2512 		} else {
2513 			CH_ERR(sc, "adapter did not reset properly, flags "
2514 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2515 			    error_flags);
2516 			rc = ENXIO;
2517 		}
2518 		end_synchronized_op(sc, 0);
2519 	}
2520 
2521 	return (rc);
2522 }
2523 
2524 static void
2525 reset_adapter_task(void *arg, int pending)
2526 {
2527 	/* XXX: t4_async_event here? */
2528 	reset_adapter(arg);
2529 }
2530 
2531 static int
2532 cxgbe_probe(device_t dev)
2533 {
2534 	struct port_info *pi = device_get_softc(dev);
2535 
2536 	device_set_descf(dev, "port %d", pi->port_id);
2537 
2538 	return (BUS_PROBE_DEFAULT);
2539 }
2540 
2541 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2542     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2543     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2544     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2545 #define T4_CAP_ENABLE (T4_CAP)
2546 
2547 static void
2548 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2549 {
2550 	if_t ifp;
2551 	struct sbuf *sb;
2552 	struct sysctl_ctx_list *ctx = &vi->ctx;
2553 	struct sysctl_oid_list *children;
2554 	struct pfil_head_args pa;
2555 	struct adapter *sc = vi->adapter;
2556 
2557 	sysctl_ctx_init(ctx);
2558 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2559 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2560 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2561 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2562 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2563 #ifdef DEV_NETMAP
2564 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2565 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2566 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2567 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2568 #endif
2569 #ifdef TCP_OFFLOAD
2570 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2571 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2572 #endif
2573 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2574 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2575 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2576 #endif
2577 
2578 	vi->xact_addr_filt = -1;
2579 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2580 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2581 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2582 		vi->flags |= TX_USES_VM_WR;
2583 
2584 	/* Allocate an ifnet and set it up */
2585 	ifp = if_alloc_dev(IFT_ETHER, dev);
2586 	vi->ifp = ifp;
2587 	if_setsoftc(ifp, vi);
2588 
2589 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2590 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2591 
2592 	if_setinitfn(ifp, cxgbe_init);
2593 	if_setioctlfn(ifp, cxgbe_ioctl);
2594 	if_settransmitfn(ifp, cxgbe_transmit);
2595 	if_setqflushfn(ifp, cxgbe_qflush);
2596 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2597 		if_setgetcounterfn(ifp, vi_get_counter);
2598 	else
2599 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2600 #if defined(KERN_TLS) || defined(RATELIMIT)
2601 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2602 #endif
2603 #ifdef RATELIMIT
2604 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2605 #endif
2606 
2607 	if_setcapabilities(ifp, T4_CAP);
2608 	if_setcapenable(ifp, T4_CAP_ENABLE);
2609 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2610 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2611 	if (chip_id(sc) >= CHELSIO_T6) {
2612 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2613 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2614 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2615 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2616 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2617 	}
2618 
2619 #ifdef TCP_OFFLOAD
2620 	if (vi->nofldrxq != 0)
2621 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2622 #endif
2623 #ifdef RATELIMIT
2624 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2625 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2626 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2627 	}
2628 #endif
2629 
2630 	if_sethwtsomax(ifp, IP_MAXPACKET);
2631 	if (vi->flags & TX_USES_VM_WR)
2632 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2633 	else
2634 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2635 #ifdef RATELIMIT
2636 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2637 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2638 #endif
2639 	if_sethwtsomaxsegsize(ifp, 65536);
2640 #ifdef KERN_TLS
2641 	if (is_ktls(sc)) {
2642 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2643 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2644 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2645 	}
2646 #endif
2647 
2648 	ether_ifattach(ifp, vi->hw_addr);
2649 #ifdef DEV_NETMAP
2650 	if (vi->nnmrxq != 0)
2651 		cxgbe_nm_attach(vi);
2652 #endif
2653 	sb = sbuf_new_auto();
2654 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2655 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2656 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2657 	case IFCAP_TOE:
2658 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2659 		break;
2660 	case IFCAP_TOE | IFCAP_TXRTLMT:
2661 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2662 		break;
2663 	case IFCAP_TXRTLMT:
2664 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2665 		break;
2666 	}
2667 #endif
2668 #ifdef TCP_OFFLOAD
2669 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2670 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2671 #endif
2672 #ifdef DEV_NETMAP
2673 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2674 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2675 		    vi->nnmtxq, vi->nnmrxq);
2676 #endif
2677 	sbuf_finish(sb);
2678 	device_printf(dev, "%s\n", sbuf_data(sb));
2679 	sbuf_delete(sb);
2680 
2681 	vi_sysctls(vi);
2682 
2683 	pa.pa_version = PFIL_VERSION;
2684 	pa.pa_flags = PFIL_IN;
2685 	pa.pa_type = PFIL_TYPE_ETHERNET;
2686 	pa.pa_headname = if_name(ifp);
2687 	vi->pfil = pfil_head_register(&pa);
2688 }
2689 
2690 static int
2691 cxgbe_attach(device_t dev)
2692 {
2693 	struct port_info *pi = device_get_softc(dev);
2694 	struct adapter *sc = pi->adapter;
2695 	struct vi_info *vi;
2696 	int i;
2697 
2698 	sysctl_ctx_init(&pi->ctx);
2699 
2700 	cxgbe_vi_attach(dev, &pi->vi[0]);
2701 
2702 	for_each_vi(pi, i, vi) {
2703 		if (i == 0)
2704 			continue;
2705 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2706 		if (vi->dev == NULL) {
2707 			device_printf(dev, "failed to add VI %d\n", i);
2708 			continue;
2709 		}
2710 		device_set_softc(vi->dev, vi);
2711 	}
2712 
2713 	cxgbe_sysctls(pi);
2714 
2715 	bus_generic_attach(dev);
2716 
2717 	return (0);
2718 }
2719 
2720 static void
2721 cxgbe_vi_detach(struct vi_info *vi)
2722 {
2723 	if_t ifp = vi->ifp;
2724 
2725 	if (vi->pfil != NULL) {
2726 		pfil_head_unregister(vi->pfil);
2727 		vi->pfil = NULL;
2728 	}
2729 
2730 	ether_ifdetach(ifp);
2731 
2732 	/* Let detach proceed even if these fail. */
2733 #ifdef DEV_NETMAP
2734 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2735 		cxgbe_nm_detach(vi);
2736 #endif
2737 	cxgbe_uninit_synchronized(vi);
2738 	callout_drain(&vi->tick);
2739 	mtx_destroy(&vi->tick_mtx);
2740 	sysctl_ctx_free(&vi->ctx);
2741 	vi_full_uninit(vi);
2742 
2743 	if_free(vi->ifp);
2744 	vi->ifp = NULL;
2745 }
2746 
2747 static int
2748 cxgbe_detach(device_t dev)
2749 {
2750 	struct port_info *pi = device_get_softc(dev);
2751 	struct adapter *sc = pi->adapter;
2752 	int rc;
2753 
2754 	/* Detach the extra VIs first. */
2755 	rc = bus_generic_detach(dev);
2756 	if (rc)
2757 		return (rc);
2758 	device_delete_children(dev);
2759 
2760 	sysctl_ctx_free(&pi->ctx);
2761 	begin_vi_detach(sc, &pi->vi[0]);
2762 	if (pi->flags & HAS_TRACEQ) {
2763 		sc->traceq = -1;	/* cloner should not create ifnet */
2764 		t4_tracer_port_detach(sc);
2765 	}
2766 	cxgbe_vi_detach(&pi->vi[0]);
2767 	ifmedia_removeall(&pi->media);
2768 	end_vi_detach(sc, &pi->vi[0]);
2769 
2770 	return (0);
2771 }
2772 
2773 static void
2774 cxgbe_init(void *arg)
2775 {
2776 	struct vi_info *vi = arg;
2777 	struct adapter *sc = vi->adapter;
2778 
2779 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2780 		return;
2781 	cxgbe_init_synchronized(vi);
2782 	end_synchronized_op(sc, 0);
2783 }
2784 
2785 static int
2786 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2787 {
2788 	int rc = 0, mtu, flags;
2789 	struct vi_info *vi = if_getsoftc(ifp);
2790 	struct port_info *pi = vi->pi;
2791 	struct adapter *sc = pi->adapter;
2792 	struct ifreq *ifr = (struct ifreq *)data;
2793 	uint32_t mask;
2794 
2795 	switch (cmd) {
2796 	case SIOCSIFMTU:
2797 		mtu = ifr->ifr_mtu;
2798 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2799 			return (EINVAL);
2800 
2801 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2802 		if (rc)
2803 			return (rc);
2804 		if_setmtu(ifp, mtu);
2805 		if (vi->flags & VI_INIT_DONE) {
2806 			t4_update_fl_bufsize(ifp);
2807 			if (!hw_off_limits(sc) &&
2808 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2809 				rc = update_mac_settings(ifp, XGMAC_MTU);
2810 		}
2811 		end_synchronized_op(sc, 0);
2812 		break;
2813 
2814 	case SIOCSIFFLAGS:
2815 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2816 		if (rc)
2817 			return (rc);
2818 
2819 		if (hw_off_limits(sc)) {
2820 			rc = ENXIO;
2821 			goto fail;
2822 		}
2823 
2824 		if (if_getflags(ifp) & IFF_UP) {
2825 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2826 				flags = vi->if_flags;
2827 				if ((if_getflags(ifp) ^ flags) &
2828 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2829 					rc = update_mac_settings(ifp,
2830 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2831 				}
2832 			} else {
2833 				rc = cxgbe_init_synchronized(vi);
2834 			}
2835 			vi->if_flags = if_getflags(ifp);
2836 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2837 			rc = cxgbe_uninit_synchronized(vi);
2838 		}
2839 		end_synchronized_op(sc, 0);
2840 		break;
2841 
2842 	case SIOCADDMULTI:
2843 	case SIOCDELMULTI:
2844 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2845 		if (rc)
2846 			return (rc);
2847 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2848 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2849 		end_synchronized_op(sc, 0);
2850 		break;
2851 
2852 	case SIOCSIFCAP:
2853 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2854 		if (rc)
2855 			return (rc);
2856 
2857 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2858 		if (mask & IFCAP_TXCSUM) {
2859 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2860 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2861 
2862 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2863 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2864 				mask &= ~IFCAP_TSO4;
2865 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2866 				if_printf(ifp,
2867 				    "tso4 disabled due to -txcsum.\n");
2868 			}
2869 		}
2870 		if (mask & IFCAP_TXCSUM_IPV6) {
2871 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2872 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2873 
2874 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2875 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2876 				mask &= ~IFCAP_TSO6;
2877 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2878 				if_printf(ifp,
2879 				    "tso6 disabled due to -txcsum6.\n");
2880 			}
2881 		}
2882 		if (mask & IFCAP_RXCSUM)
2883 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2884 		if (mask & IFCAP_RXCSUM_IPV6)
2885 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2886 
2887 		/*
2888 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2889 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2890 		 * sending a TSO request our way, so it's sufficient to toggle
2891 		 * IFCAP_TSOx only.
2892 		 */
2893 		if (mask & IFCAP_TSO4) {
2894 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2895 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2896 				if_printf(ifp, "enable txcsum first.\n");
2897 				rc = EAGAIN;
2898 				goto fail;
2899 			}
2900 			if_togglecapenable(ifp, IFCAP_TSO4);
2901 		}
2902 		if (mask & IFCAP_TSO6) {
2903 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2904 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2905 				if_printf(ifp, "enable txcsum6 first.\n");
2906 				rc = EAGAIN;
2907 				goto fail;
2908 			}
2909 			if_togglecapenable(ifp, IFCAP_TSO6);
2910 		}
2911 		if (mask & IFCAP_LRO) {
2912 #if defined(INET) || defined(INET6)
2913 			int i;
2914 			struct sge_rxq *rxq;
2915 
2916 			if_togglecapenable(ifp, IFCAP_LRO);
2917 			for_each_rxq(vi, i, rxq) {
2918 				if (if_getcapenable(ifp) & IFCAP_LRO)
2919 					rxq->iq.flags |= IQ_LRO_ENABLED;
2920 				else
2921 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2922 			}
2923 #endif
2924 		}
2925 #ifdef TCP_OFFLOAD
2926 		if (mask & IFCAP_TOE) {
2927 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2928 
2929 			rc = toe_capability(vi, enable);
2930 			if (rc != 0)
2931 				goto fail;
2932 
2933 			if_togglecapenable(ifp, mask);
2934 		}
2935 #endif
2936 		if (mask & IFCAP_VLAN_HWTAGGING) {
2937 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2938 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2939 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2940 		}
2941 		if (mask & IFCAP_VLAN_MTU) {
2942 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2943 
2944 			/* Need to find out how to disable auto-mtu-inflation */
2945 		}
2946 		if (mask & IFCAP_VLAN_HWTSO)
2947 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2948 		if (mask & IFCAP_VLAN_HWCSUM)
2949 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2950 #ifdef RATELIMIT
2951 		if (mask & IFCAP_TXRTLMT)
2952 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2953 #endif
2954 		if (mask & IFCAP_HWRXTSTMP) {
2955 			int i;
2956 			struct sge_rxq *rxq;
2957 
2958 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2959 			for_each_rxq(vi, i, rxq) {
2960 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2961 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2962 				else
2963 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2964 			}
2965 		}
2966 		if (mask & IFCAP_MEXTPG)
2967 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2968 
2969 #ifdef KERN_TLS
2970 		if (mask & IFCAP_TXTLS) {
2971 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2972 
2973 			rc = ktls_capability(sc, enable);
2974 			if (rc != 0)
2975 				goto fail;
2976 
2977 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2978 		}
2979 #endif
2980 		if (mask & IFCAP_VXLAN_HWCSUM) {
2981 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2982 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2983 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2984 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2985 		}
2986 		if (mask & IFCAP_VXLAN_HWTSO) {
2987 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2988 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2989 			    CSUM_INNER_IP_TSO);
2990 		}
2991 
2992 #ifdef VLAN_CAPABILITIES
2993 		VLAN_CAPABILITIES(ifp);
2994 #endif
2995 fail:
2996 		end_synchronized_op(sc, 0);
2997 		break;
2998 
2999 	case SIOCSIFMEDIA:
3000 	case SIOCGIFMEDIA:
3001 	case SIOCGIFXMEDIA:
3002 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3003 		break;
3004 
3005 	case SIOCGI2C: {
3006 		struct ifi2creq i2c;
3007 
3008 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3009 		if (rc != 0)
3010 			break;
3011 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3012 			rc = EPERM;
3013 			break;
3014 		}
3015 		if (i2c.len > sizeof(i2c.data)) {
3016 			rc = EINVAL;
3017 			break;
3018 		}
3019 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3020 		if (rc)
3021 			return (rc);
3022 		if (hw_off_limits(sc))
3023 			rc = ENXIO;
3024 		else
3025 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3026 			    i2c.offset, i2c.len, &i2c.data[0]);
3027 		end_synchronized_op(sc, 0);
3028 		if (rc == 0)
3029 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3030 		break;
3031 	}
3032 
3033 	default:
3034 		rc = ether_ioctl(ifp, cmd, data);
3035 	}
3036 
3037 	return (rc);
3038 }
3039 
3040 static int
3041 cxgbe_transmit(if_t ifp, struct mbuf *m)
3042 {
3043 	struct vi_info *vi = if_getsoftc(ifp);
3044 	struct port_info *pi = vi->pi;
3045 	struct adapter *sc;
3046 	struct sge_txq *txq;
3047 	void *items[1];
3048 	int rc;
3049 
3050 	M_ASSERTPKTHDR(m);
3051 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3052 #if defined(KERN_TLS) || defined(RATELIMIT)
3053 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3054 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3055 #endif
3056 
3057 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3058 		m_freem(m);
3059 		return (ENETDOWN);
3060 	}
3061 
3062 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3063 	if (__predict_false(rc != 0)) {
3064 		if (__predict_true(rc == EINPROGRESS)) {
3065 			/* queued by parse_pkt */
3066 			MPASS(m != NULL);
3067 			return (0);
3068 		}
3069 
3070 		MPASS(m == NULL);			/* was freed already */
3071 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3072 		return (rc);
3073 	}
3074 
3075 	/* Select a txq. */
3076 	sc = vi->adapter;
3077 	txq = &sc->sge.txq[vi->first_txq];
3078 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3079 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3080 		    vi->rsrv_noflowq);
3081 
3082 	items[0] = m;
3083 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3084 	if (__predict_false(rc != 0))
3085 		m_freem(m);
3086 
3087 	return (rc);
3088 }
3089 
3090 static void
3091 cxgbe_qflush(if_t ifp)
3092 {
3093 	struct vi_info *vi = if_getsoftc(ifp);
3094 	struct sge_txq *txq;
3095 	int i;
3096 
3097 	/* queues do not exist if !VI_INIT_DONE. */
3098 	if (vi->flags & VI_INIT_DONE) {
3099 		for_each_txq(vi, i, txq) {
3100 			TXQ_LOCK(txq);
3101 			txq->eq.flags |= EQ_QFLUSH;
3102 			TXQ_UNLOCK(txq);
3103 			while (!mp_ring_is_idle(txq->r)) {
3104 				mp_ring_check_drainage(txq->r, 4096);
3105 				pause("qflush", 1);
3106 			}
3107 			TXQ_LOCK(txq);
3108 			txq->eq.flags &= ~EQ_QFLUSH;
3109 			TXQ_UNLOCK(txq);
3110 		}
3111 	}
3112 	if_qflush(ifp);
3113 }
3114 
3115 static uint64_t
3116 vi_get_counter(if_t ifp, ift_counter c)
3117 {
3118 	struct vi_info *vi = if_getsoftc(ifp);
3119 	struct fw_vi_stats_vf *s = &vi->stats;
3120 
3121 	mtx_lock(&vi->tick_mtx);
3122 	vi_refresh_stats(vi);
3123 	mtx_unlock(&vi->tick_mtx);
3124 
3125 	switch (c) {
3126 	case IFCOUNTER_IPACKETS:
3127 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3128 		    s->rx_ucast_frames);
3129 	case IFCOUNTER_IERRORS:
3130 		return (s->rx_err_frames);
3131 	case IFCOUNTER_OPACKETS:
3132 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3133 		    s->tx_ucast_frames + s->tx_offload_frames);
3134 	case IFCOUNTER_OERRORS:
3135 		return (s->tx_drop_frames);
3136 	case IFCOUNTER_IBYTES:
3137 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3138 		    s->rx_ucast_bytes);
3139 	case IFCOUNTER_OBYTES:
3140 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3141 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3142 	case IFCOUNTER_IMCASTS:
3143 		return (s->rx_mcast_frames);
3144 	case IFCOUNTER_OMCASTS:
3145 		return (s->tx_mcast_frames);
3146 	case IFCOUNTER_OQDROPS: {
3147 		uint64_t drops;
3148 
3149 		drops = 0;
3150 		if (vi->flags & VI_INIT_DONE) {
3151 			int i;
3152 			struct sge_txq *txq;
3153 
3154 			for_each_txq(vi, i, txq)
3155 				drops += counter_u64_fetch(txq->r->dropped);
3156 		}
3157 
3158 		return (drops);
3159 
3160 	}
3161 
3162 	default:
3163 		return (if_get_counter_default(ifp, c));
3164 	}
3165 }
3166 
3167 static uint64_t
3168 cxgbe_get_counter(if_t ifp, ift_counter c)
3169 {
3170 	struct vi_info *vi = if_getsoftc(ifp);
3171 	struct port_info *pi = vi->pi;
3172 	struct port_stats *s = &pi->stats;
3173 
3174 	mtx_lock(&vi->tick_mtx);
3175 	cxgbe_refresh_stats(vi);
3176 	mtx_unlock(&vi->tick_mtx);
3177 
3178 	switch (c) {
3179 	case IFCOUNTER_IPACKETS:
3180 		return (s->rx_frames);
3181 
3182 	case IFCOUNTER_IERRORS:
3183 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3184 		    s->rx_fcs_err + s->rx_len_err);
3185 
3186 	case IFCOUNTER_OPACKETS:
3187 		return (s->tx_frames);
3188 
3189 	case IFCOUNTER_OERRORS:
3190 		return (s->tx_error_frames);
3191 
3192 	case IFCOUNTER_IBYTES:
3193 		return (s->rx_octets);
3194 
3195 	case IFCOUNTER_OBYTES:
3196 		return (s->tx_octets);
3197 
3198 	case IFCOUNTER_IMCASTS:
3199 		return (s->rx_mcast_frames);
3200 
3201 	case IFCOUNTER_OMCASTS:
3202 		return (s->tx_mcast_frames);
3203 
3204 	case IFCOUNTER_IQDROPS:
3205 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3206 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3207 		    s->rx_trunc3 + pi->tnl_cong_drops);
3208 
3209 	case IFCOUNTER_OQDROPS: {
3210 		uint64_t drops;
3211 
3212 		drops = s->tx_drop;
3213 		if (vi->flags & VI_INIT_DONE) {
3214 			int i;
3215 			struct sge_txq *txq;
3216 
3217 			for_each_txq(vi, i, txq)
3218 				drops += counter_u64_fetch(txq->r->dropped);
3219 		}
3220 
3221 		return (drops);
3222 
3223 	}
3224 
3225 	default:
3226 		return (if_get_counter_default(ifp, c));
3227 	}
3228 }
3229 
3230 #if defined(KERN_TLS) || defined(RATELIMIT)
3231 static int
3232 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3233     struct m_snd_tag **pt)
3234 {
3235 	int error;
3236 
3237 	switch (params->hdr.type) {
3238 #ifdef RATELIMIT
3239 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3240 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3241 		break;
3242 #endif
3243 #ifdef KERN_TLS
3244 	case IF_SND_TAG_TYPE_TLS:
3245 	{
3246 		struct vi_info *vi = if_getsoftc(ifp);
3247 
3248 		if (is_t6(vi->pi->adapter))
3249 			error = t6_tls_tag_alloc(ifp, params, pt);
3250 		else
3251 			error = EOPNOTSUPP;
3252 		break;
3253 	}
3254 #endif
3255 	default:
3256 		error = EOPNOTSUPP;
3257 	}
3258 	return (error);
3259 }
3260 #endif
3261 
3262 /*
3263  * The kernel picks a media from the list we had provided but we still validate
3264  * the requeste.
3265  */
3266 int
3267 cxgbe_media_change(if_t ifp)
3268 {
3269 	struct vi_info *vi = if_getsoftc(ifp);
3270 	struct port_info *pi = vi->pi;
3271 	struct ifmedia *ifm = &pi->media;
3272 	struct link_config *lc = &pi->link_cfg;
3273 	struct adapter *sc = pi->adapter;
3274 	int rc;
3275 
3276 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3277 	if (rc != 0)
3278 		return (rc);
3279 	PORT_LOCK(pi);
3280 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3281 		/* ifconfig .. media autoselect */
3282 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3283 			rc = ENOTSUP; /* AN not supported by transceiver */
3284 			goto done;
3285 		}
3286 		lc->requested_aneg = AUTONEG_ENABLE;
3287 		lc->requested_speed = 0;
3288 		lc->requested_fc |= PAUSE_AUTONEG;
3289 	} else {
3290 		lc->requested_aneg = AUTONEG_DISABLE;
3291 		lc->requested_speed =
3292 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3293 		lc->requested_fc = 0;
3294 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3295 			lc->requested_fc |= PAUSE_RX;
3296 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3297 			lc->requested_fc |= PAUSE_TX;
3298 	}
3299 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3300 		fixup_link_config(pi);
3301 		rc = apply_link_config(pi);
3302 	}
3303 done:
3304 	PORT_UNLOCK(pi);
3305 	end_synchronized_op(sc, 0);
3306 	return (rc);
3307 }
3308 
3309 /*
3310  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3311  * given speed.
3312  */
3313 static int
3314 port_mword(struct port_info *pi, uint32_t speed)
3315 {
3316 
3317 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3318 	MPASS(powerof2(speed));
3319 
3320 	switch(pi->port_type) {
3321 	case FW_PORT_TYPE_BT_SGMII:
3322 	case FW_PORT_TYPE_BT_XFI:
3323 	case FW_PORT_TYPE_BT_XAUI:
3324 		/* BaseT */
3325 		switch (speed) {
3326 		case FW_PORT_CAP32_SPEED_100M:
3327 			return (IFM_100_T);
3328 		case FW_PORT_CAP32_SPEED_1G:
3329 			return (IFM_1000_T);
3330 		case FW_PORT_CAP32_SPEED_10G:
3331 			return (IFM_10G_T);
3332 		}
3333 		break;
3334 	case FW_PORT_TYPE_KX4:
3335 		if (speed == FW_PORT_CAP32_SPEED_10G)
3336 			return (IFM_10G_KX4);
3337 		break;
3338 	case FW_PORT_TYPE_CX4:
3339 		if (speed == FW_PORT_CAP32_SPEED_10G)
3340 			return (IFM_10G_CX4);
3341 		break;
3342 	case FW_PORT_TYPE_KX:
3343 		if (speed == FW_PORT_CAP32_SPEED_1G)
3344 			return (IFM_1000_KX);
3345 		break;
3346 	case FW_PORT_TYPE_KR:
3347 	case FW_PORT_TYPE_BP_AP:
3348 	case FW_PORT_TYPE_BP4_AP:
3349 	case FW_PORT_TYPE_BP40_BA:
3350 	case FW_PORT_TYPE_KR4_100G:
3351 	case FW_PORT_TYPE_KR_SFP28:
3352 	case FW_PORT_TYPE_KR_XLAUI:
3353 		switch (speed) {
3354 		case FW_PORT_CAP32_SPEED_1G:
3355 			return (IFM_1000_KX);
3356 		case FW_PORT_CAP32_SPEED_10G:
3357 			return (IFM_10G_KR);
3358 		case FW_PORT_CAP32_SPEED_25G:
3359 			return (IFM_25G_KR);
3360 		case FW_PORT_CAP32_SPEED_40G:
3361 			return (IFM_40G_KR4);
3362 		case FW_PORT_CAP32_SPEED_50G:
3363 			return (IFM_50G_KR2);
3364 		case FW_PORT_CAP32_SPEED_100G:
3365 			return (IFM_100G_KR4);
3366 		}
3367 		break;
3368 	case FW_PORT_TYPE_FIBER_XFI:
3369 	case FW_PORT_TYPE_FIBER_XAUI:
3370 	case FW_PORT_TYPE_SFP:
3371 	case FW_PORT_TYPE_QSFP_10G:
3372 	case FW_PORT_TYPE_QSA:
3373 	case FW_PORT_TYPE_QSFP:
3374 	case FW_PORT_TYPE_CR4_QSFP:
3375 	case FW_PORT_TYPE_CR_QSFP:
3376 	case FW_PORT_TYPE_CR2_QSFP:
3377 	case FW_PORT_TYPE_SFP28:
3378 		/* Pluggable transceiver */
3379 		switch (pi->mod_type) {
3380 		case FW_PORT_MOD_TYPE_LR:
3381 			switch (speed) {
3382 			case FW_PORT_CAP32_SPEED_1G:
3383 				return (IFM_1000_LX);
3384 			case FW_PORT_CAP32_SPEED_10G:
3385 				return (IFM_10G_LR);
3386 			case FW_PORT_CAP32_SPEED_25G:
3387 				return (IFM_25G_LR);
3388 			case FW_PORT_CAP32_SPEED_40G:
3389 				return (IFM_40G_LR4);
3390 			case FW_PORT_CAP32_SPEED_50G:
3391 				return (IFM_50G_LR2);
3392 			case FW_PORT_CAP32_SPEED_100G:
3393 				return (IFM_100G_LR4);
3394 			}
3395 			break;
3396 		case FW_PORT_MOD_TYPE_SR:
3397 			switch (speed) {
3398 			case FW_PORT_CAP32_SPEED_1G:
3399 				return (IFM_1000_SX);
3400 			case FW_PORT_CAP32_SPEED_10G:
3401 				return (IFM_10G_SR);
3402 			case FW_PORT_CAP32_SPEED_25G:
3403 				return (IFM_25G_SR);
3404 			case FW_PORT_CAP32_SPEED_40G:
3405 				return (IFM_40G_SR4);
3406 			case FW_PORT_CAP32_SPEED_50G:
3407 				return (IFM_50G_SR2);
3408 			case FW_PORT_CAP32_SPEED_100G:
3409 				return (IFM_100G_SR4);
3410 			}
3411 			break;
3412 		case FW_PORT_MOD_TYPE_ER:
3413 			if (speed == FW_PORT_CAP32_SPEED_10G)
3414 				return (IFM_10G_ER);
3415 			break;
3416 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3417 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3418 			switch (speed) {
3419 			case FW_PORT_CAP32_SPEED_1G:
3420 				return (IFM_1000_CX);
3421 			case FW_PORT_CAP32_SPEED_10G:
3422 				return (IFM_10G_TWINAX);
3423 			case FW_PORT_CAP32_SPEED_25G:
3424 				return (IFM_25G_CR);
3425 			case FW_PORT_CAP32_SPEED_40G:
3426 				return (IFM_40G_CR4);
3427 			case FW_PORT_CAP32_SPEED_50G:
3428 				return (IFM_50G_CR2);
3429 			case FW_PORT_CAP32_SPEED_100G:
3430 				return (IFM_100G_CR4);
3431 			}
3432 			break;
3433 		case FW_PORT_MOD_TYPE_LRM:
3434 			if (speed == FW_PORT_CAP32_SPEED_10G)
3435 				return (IFM_10G_LRM);
3436 			break;
3437 		case FW_PORT_MOD_TYPE_NA:
3438 			MPASS(0);	/* Not pluggable? */
3439 			/* fall throough */
3440 		case FW_PORT_MOD_TYPE_ERROR:
3441 		case FW_PORT_MOD_TYPE_UNKNOWN:
3442 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3443 			break;
3444 		case FW_PORT_MOD_TYPE_NONE:
3445 			return (IFM_NONE);
3446 		}
3447 		break;
3448 	case FW_PORT_TYPE_NONE:
3449 		return (IFM_NONE);
3450 	}
3451 
3452 	return (IFM_UNKNOWN);
3453 }
3454 
3455 void
3456 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3457 {
3458 	struct vi_info *vi = if_getsoftc(ifp);
3459 	struct port_info *pi = vi->pi;
3460 	struct adapter *sc = pi->adapter;
3461 	struct link_config *lc = &pi->link_cfg;
3462 
3463 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3464 		return;
3465 	PORT_LOCK(pi);
3466 
3467 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3468 		/*
3469 		 * If all the interfaces are administratively down the firmware
3470 		 * does not report transceiver changes.  Refresh port info here
3471 		 * so that ifconfig displays accurate ifmedia at all times.
3472 		 * This is the only reason we have a synchronized op in this
3473 		 * function.  Just PORT_LOCK would have been enough otherwise.
3474 		 */
3475 		t4_update_port_info(pi);
3476 		build_medialist(pi);
3477 	}
3478 
3479 	/* ifm_status */
3480 	ifmr->ifm_status = IFM_AVALID;
3481 	if (lc->link_ok == false)
3482 		goto done;
3483 	ifmr->ifm_status |= IFM_ACTIVE;
3484 
3485 	/* ifm_active */
3486 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3487 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3488 	if (lc->fc & PAUSE_RX)
3489 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3490 	if (lc->fc & PAUSE_TX)
3491 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3492 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3493 done:
3494 	PORT_UNLOCK(pi);
3495 	end_synchronized_op(sc, 0);
3496 }
3497 
3498 static int
3499 vcxgbe_probe(device_t dev)
3500 {
3501 	struct vi_info *vi = device_get_softc(dev);
3502 
3503 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3504 	    vi - vi->pi->vi);
3505 
3506 	return (BUS_PROBE_DEFAULT);
3507 }
3508 
3509 static int
3510 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3511 {
3512 	int func, index, rc;
3513 	uint32_t param, val;
3514 
3515 	ASSERT_SYNCHRONIZED_OP(sc);
3516 
3517 	index = vi - pi->vi;
3518 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3519 	KASSERT(index < nitems(vi_mac_funcs),
3520 	    ("%s: VI %s doesn't have a MAC func", __func__,
3521 	    device_get_nameunit(vi->dev)));
3522 	func = vi_mac_funcs[index];
3523 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3524 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3525 	if (rc < 0) {
3526 		CH_ERR(vi, "failed to allocate virtual interface %d"
3527 		    "for port %d: %d\n", index, pi->port_id, -rc);
3528 		return (-rc);
3529 	}
3530 	vi->viid = rc;
3531 
3532 	if (vi->rss_size == 1) {
3533 		/*
3534 		 * This VI didn't get a slice of the RSS table.  Reduce the
3535 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3536 		 * configuration file (nvi, rssnvi for this PF) if this is a
3537 		 * problem.
3538 		 */
3539 		device_printf(vi->dev, "RSS table not available.\n");
3540 		vi->rss_base = 0xffff;
3541 
3542 		return (0);
3543 	}
3544 
3545 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3546 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3547 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3548 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3549 	if (rc)
3550 		vi->rss_base = 0xffff;
3551 	else {
3552 		MPASS((val >> 16) == vi->rss_size);
3553 		vi->rss_base = val & 0xffff;
3554 	}
3555 
3556 	return (0);
3557 }
3558 
3559 static int
3560 vcxgbe_attach(device_t dev)
3561 {
3562 	struct vi_info *vi;
3563 	struct port_info *pi;
3564 	struct adapter *sc;
3565 	int rc;
3566 
3567 	vi = device_get_softc(dev);
3568 	pi = vi->pi;
3569 	sc = pi->adapter;
3570 
3571 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3572 	if (rc)
3573 		return (rc);
3574 	rc = alloc_extra_vi(sc, pi, vi);
3575 	end_synchronized_op(sc, 0);
3576 	if (rc)
3577 		return (rc);
3578 
3579 	cxgbe_vi_attach(dev, vi);
3580 
3581 	return (0);
3582 }
3583 
3584 static int
3585 vcxgbe_detach(device_t dev)
3586 {
3587 	struct vi_info *vi;
3588 	struct adapter *sc;
3589 
3590 	vi = device_get_softc(dev);
3591 	sc = vi->adapter;
3592 
3593 	begin_vi_detach(sc, vi);
3594 	cxgbe_vi_detach(vi);
3595 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3596 	end_vi_detach(sc, vi);
3597 
3598 	return (0);
3599 }
3600 
3601 static struct callout fatal_callout;
3602 static struct taskqueue *reset_tq;
3603 
3604 static void
3605 delayed_panic(void *arg)
3606 {
3607 	struct adapter *sc = arg;
3608 
3609 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3610 }
3611 
3612 static void
3613 fatal_error_task(void *arg, int pending)
3614 {
3615 	struct adapter *sc = arg;
3616 	int rc;
3617 
3618 #ifdef TCP_OFFLOAD
3619 	t4_async_event(sc);
3620 #endif
3621 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3622 		dump_cim_regs(sc);
3623 		dump_cimla(sc);
3624 		dump_devlog(sc);
3625 	}
3626 
3627 	if (t4_reset_on_fatal_err) {
3628 		CH_ALERT(sc, "resetting on fatal error.\n");
3629 		rc = reset_adapter(sc);
3630 		if (rc == 0 && t4_panic_on_fatal_err) {
3631 			CH_ALERT(sc, "reset was successful, "
3632 			    "system will NOT panic.\n");
3633 			return;
3634 		}
3635 	}
3636 
3637 	if (t4_panic_on_fatal_err) {
3638 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3639 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3640 	}
3641 }
3642 
3643 void
3644 t4_fatal_err(struct adapter *sc, bool fw_error)
3645 {
3646 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3647 
3648 	stop_adapter(sc);
3649 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3650 		return;
3651 	if (fw_error) {
3652 		/*
3653 		 * We are here because of a firmware error/timeout and not
3654 		 * because of a hardware interrupt.  It is possible (although
3655 		 * not very likely) that an error interrupt was also raised but
3656 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3657 		 * main INT_CAUSE registers here to make sure we haven't missed
3658 		 * anything interesting.
3659 		 */
3660 		t4_slow_intr_handler(sc, verbose);
3661 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3662 	}
3663 	t4_report_fw_error(sc);
3664 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3665 	    device_get_nameunit(sc->dev), fw_error);
3666 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3667 }
3668 
3669 void
3670 t4_add_adapter(struct adapter *sc)
3671 {
3672 	sx_xlock(&t4_list_lock);
3673 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3674 	sx_xunlock(&t4_list_lock);
3675 }
3676 
3677 int
3678 t4_map_bars_0_and_4(struct adapter *sc)
3679 {
3680 	sc->regs_rid = PCIR_BAR(0);
3681 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3682 	    &sc->regs_rid, RF_ACTIVE);
3683 	if (sc->regs_res == NULL) {
3684 		device_printf(sc->dev, "cannot map registers.\n");
3685 		return (ENXIO);
3686 	}
3687 	sc->bt = rman_get_bustag(sc->regs_res);
3688 	sc->bh = rman_get_bushandle(sc->regs_res);
3689 	sc->mmio_len = rman_get_size(sc->regs_res);
3690 	setbit(&sc->doorbells, DOORBELL_KDB);
3691 
3692 	sc->msix_rid = PCIR_BAR(4);
3693 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3694 	    &sc->msix_rid, RF_ACTIVE);
3695 	if (sc->msix_res == NULL) {
3696 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3697 		return (ENXIO);
3698 	}
3699 
3700 	return (0);
3701 }
3702 
3703 int
3704 t4_map_bar_2(struct adapter *sc)
3705 {
3706 
3707 	/*
3708 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3709 	 * to map it if RDMA is disabled.
3710 	 */
3711 	if (is_t4(sc) && sc->rdmacaps == 0)
3712 		return (0);
3713 
3714 	sc->udbs_rid = PCIR_BAR(2);
3715 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3716 	    &sc->udbs_rid, RF_ACTIVE);
3717 	if (sc->udbs_res == NULL) {
3718 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3719 		return (ENXIO);
3720 	}
3721 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3722 
3723 	if (chip_id(sc) >= CHELSIO_T5) {
3724 		setbit(&sc->doorbells, DOORBELL_UDB);
3725 #if defined(__i386__) || defined(__amd64__)
3726 		if (t5_write_combine) {
3727 			int rc, mode;
3728 
3729 			/*
3730 			 * Enable write combining on BAR2.  This is the
3731 			 * userspace doorbell BAR and is split into 128B
3732 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3733 			 * with an egress queue.  The first 64B has the doorbell
3734 			 * and the second 64B can be used to submit a tx work
3735 			 * request with an implicit doorbell.
3736 			 */
3737 
3738 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3739 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3740 			if (rc == 0) {
3741 				clrbit(&sc->doorbells, DOORBELL_UDB);
3742 				setbit(&sc->doorbells, DOORBELL_WCWR);
3743 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3744 			} else {
3745 				device_printf(sc->dev,
3746 				    "couldn't enable write combining: %d\n",
3747 				    rc);
3748 			}
3749 
3750 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3751 			t4_write_reg(sc, A_SGE_STAT_CFG,
3752 			    V_STATSOURCE_T5(7) | mode);
3753 		}
3754 #endif
3755 	}
3756 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3757 
3758 	return (0);
3759 }
3760 
3761 int
3762 t4_adj_doorbells(struct adapter *sc)
3763 {
3764 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3765 		sc->doorbells &= t4_doorbells_allowed;
3766 		return (0);
3767 	}
3768 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3769 	       sc->doorbells, t4_doorbells_allowed);
3770 	return (EINVAL);
3771 }
3772 
3773 struct memwin_init {
3774 	uint32_t base;
3775 	uint32_t aperture;
3776 };
3777 
3778 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3779 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3780 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3781 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3782 };
3783 
3784 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3785 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3786 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3787 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3788 };
3789 
3790 static void
3791 setup_memwin(struct adapter *sc)
3792 {
3793 	const struct memwin_init *mw_init;
3794 	struct memwin *mw;
3795 	int i;
3796 	uint32_t bar0;
3797 
3798 	if (is_t4(sc)) {
3799 		/*
3800 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3801 		 * mechanism.  Works from within PCI passthrough environments
3802 		 * too, where rman_get_start() can return a different value.  We
3803 		 * need to program the T4 memory window decoders with the actual
3804 		 * addresses that will be coming across the PCIe link.
3805 		 */
3806 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3807 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3808 
3809 		mw_init = &t4_memwin[0];
3810 	} else {
3811 		/* T5+ use the relative offset inside the PCIe BAR */
3812 		bar0 = 0;
3813 
3814 		mw_init = &t5_memwin[0];
3815 	}
3816 
3817 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3818 		if (!rw_initialized(&mw->mw_lock)) {
3819 			rw_init(&mw->mw_lock, "memory window access");
3820 			mw->mw_base = mw_init->base;
3821 			mw->mw_aperture = mw_init->aperture;
3822 			mw->mw_curpos = 0;
3823 		}
3824 		t4_write_reg(sc,
3825 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3826 		    (mw->mw_base + bar0) | V_BIR(0) |
3827 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3828 		rw_wlock(&mw->mw_lock);
3829 		position_memwin(sc, i, mw->mw_curpos);
3830 		rw_wunlock(&mw->mw_lock);
3831 	}
3832 
3833 	/* flush */
3834 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3835 }
3836 
3837 /*
3838  * Positions the memory window at the given address in the card's address space.
3839  * There are some alignment requirements and the actual position may be at an
3840  * address prior to the requested address.  mw->mw_curpos always has the actual
3841  * position of the window.
3842  */
3843 static void
3844 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3845 {
3846 	struct memwin *mw;
3847 	uint32_t pf;
3848 	uint32_t reg;
3849 
3850 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3851 	mw = &sc->memwin[idx];
3852 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3853 
3854 	if (is_t4(sc)) {
3855 		pf = 0;
3856 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3857 	} else {
3858 		pf = V_PFNUM(sc->pf);
3859 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3860 	}
3861 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3862 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3863 	t4_read_reg(sc, reg);	/* flush */
3864 }
3865 
3866 int
3867 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3868     int len, int rw)
3869 {
3870 	struct memwin *mw;
3871 	uint32_t mw_end, v;
3872 
3873 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3874 
3875 	/* Memory can only be accessed in naturally aligned 4 byte units */
3876 	if (addr & 3 || len & 3 || len <= 0)
3877 		return (EINVAL);
3878 
3879 	mw = &sc->memwin[idx];
3880 	while (len > 0) {
3881 		rw_rlock(&mw->mw_lock);
3882 		mw_end = mw->mw_curpos + mw->mw_aperture;
3883 		if (addr >= mw_end || addr < mw->mw_curpos) {
3884 			/* Will need to reposition the window */
3885 			if (!rw_try_upgrade(&mw->mw_lock)) {
3886 				rw_runlock(&mw->mw_lock);
3887 				rw_wlock(&mw->mw_lock);
3888 			}
3889 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3890 			position_memwin(sc, idx, addr);
3891 			rw_downgrade(&mw->mw_lock);
3892 			mw_end = mw->mw_curpos + mw->mw_aperture;
3893 		}
3894 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3895 		while (addr < mw_end && len > 0) {
3896 			if (rw == 0) {
3897 				v = t4_read_reg(sc, mw->mw_base + addr -
3898 				    mw->mw_curpos);
3899 				*val++ = le32toh(v);
3900 			} else {
3901 				v = *val++;
3902 				t4_write_reg(sc, mw->mw_base + addr -
3903 				    mw->mw_curpos, htole32(v));
3904 			}
3905 			addr += 4;
3906 			len -= 4;
3907 		}
3908 		rw_runlock(&mw->mw_lock);
3909 	}
3910 
3911 	return (0);
3912 }
3913 
3914 CTASSERT(M_TID_COOKIE == M_COOKIE);
3915 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3916 
3917 static void
3918 t4_init_atid_table(struct adapter *sc)
3919 {
3920 	struct tid_info *t;
3921 	int i;
3922 
3923 	t = &sc->tids;
3924 	if (t->natids == 0)
3925 		return;
3926 
3927 	MPASS(t->atid_tab == NULL);
3928 
3929 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3930 	    M_ZERO | M_WAITOK);
3931 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3932 	t->afree = t->atid_tab;
3933 	t->atids_in_use = 0;
3934 	for (i = 1; i < t->natids; i++)
3935 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3936 	t->atid_tab[t->natids - 1].next = NULL;
3937 }
3938 
3939 static void
3940 t4_free_atid_table(struct adapter *sc)
3941 {
3942 	struct tid_info *t;
3943 
3944 	t = &sc->tids;
3945 
3946 	KASSERT(t->atids_in_use == 0,
3947 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3948 
3949 	if (mtx_initialized(&t->atid_lock))
3950 		mtx_destroy(&t->atid_lock);
3951 	free(t->atid_tab, M_CXGBE);
3952 	t->atid_tab = NULL;
3953 }
3954 
3955 int
3956 alloc_atid(struct adapter *sc, void *ctx)
3957 {
3958 	struct tid_info *t = &sc->tids;
3959 	int atid = -1;
3960 
3961 	mtx_lock(&t->atid_lock);
3962 	if (t->afree) {
3963 		union aopen_entry *p = t->afree;
3964 
3965 		atid = p - t->atid_tab;
3966 		MPASS(atid <= M_TID_TID);
3967 		t->afree = p->next;
3968 		p->data = ctx;
3969 		t->atids_in_use++;
3970 	}
3971 	mtx_unlock(&t->atid_lock);
3972 	return (atid);
3973 }
3974 
3975 void *
3976 lookup_atid(struct adapter *sc, int atid)
3977 {
3978 	struct tid_info *t = &sc->tids;
3979 
3980 	return (t->atid_tab[atid].data);
3981 }
3982 
3983 void
3984 free_atid(struct adapter *sc, int atid)
3985 {
3986 	struct tid_info *t = &sc->tids;
3987 	union aopen_entry *p = &t->atid_tab[atid];
3988 
3989 	mtx_lock(&t->atid_lock);
3990 	p->next = t->afree;
3991 	t->afree = p;
3992 	t->atids_in_use--;
3993 	mtx_unlock(&t->atid_lock);
3994 }
3995 
3996 static void
3997 queue_tid_release(struct adapter *sc, int tid)
3998 {
3999 
4000 	CXGBE_UNIMPLEMENTED("deferred tid release");
4001 }
4002 
4003 void
4004 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4005 {
4006 	struct wrqe *wr;
4007 	struct cpl_tid_release *req;
4008 
4009 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4010 	if (wr == NULL) {
4011 		queue_tid_release(sc, tid);	/* defer */
4012 		return;
4013 	}
4014 	req = wrtod(wr);
4015 
4016 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4017 
4018 	t4_wrq_tx(sc, wr);
4019 }
4020 
4021 static int
4022 t4_range_cmp(const void *a, const void *b)
4023 {
4024 	return ((const struct t4_range *)a)->start -
4025 	       ((const struct t4_range *)b)->start;
4026 }
4027 
4028 /*
4029  * Verify that the memory range specified by the addr/len pair is valid within
4030  * the card's address space.
4031  */
4032 static int
4033 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4034 {
4035 	struct t4_range mem_ranges[4], *r, *next;
4036 	uint32_t em, addr_len;
4037 	int i, n, remaining;
4038 
4039 	/* Memory can only be accessed in naturally aligned 4 byte units */
4040 	if (addr & 3 || len & 3 || len == 0)
4041 		return (EINVAL);
4042 
4043 	/* Enabled memories */
4044 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4045 
4046 	r = &mem_ranges[0];
4047 	n = 0;
4048 	bzero(r, sizeof(mem_ranges));
4049 	if (em & F_EDRAM0_ENABLE) {
4050 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4051 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4052 		if (r->size > 0) {
4053 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4054 			if (addr >= r->start &&
4055 			    addr + len <= r->start + r->size)
4056 				return (0);
4057 			r++;
4058 			n++;
4059 		}
4060 	}
4061 	if (em & F_EDRAM1_ENABLE) {
4062 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4063 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4064 		if (r->size > 0) {
4065 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4066 			if (addr >= r->start &&
4067 			    addr + len <= r->start + r->size)
4068 				return (0);
4069 			r++;
4070 			n++;
4071 		}
4072 	}
4073 	if (em & F_EXT_MEM_ENABLE) {
4074 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4075 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4076 		if (r->size > 0) {
4077 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4078 			if (addr >= r->start &&
4079 			    addr + len <= r->start + r->size)
4080 				return (0);
4081 			r++;
4082 			n++;
4083 		}
4084 	}
4085 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4086 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4087 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4088 		if (r->size > 0) {
4089 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4090 			if (addr >= r->start &&
4091 			    addr + len <= r->start + r->size)
4092 				return (0);
4093 			r++;
4094 			n++;
4095 		}
4096 	}
4097 	MPASS(n <= nitems(mem_ranges));
4098 
4099 	if (n > 1) {
4100 		/* Sort and merge the ranges. */
4101 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4102 
4103 		/* Start from index 0 and examine the next n - 1 entries. */
4104 		r = &mem_ranges[0];
4105 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4106 
4107 			MPASS(r->size > 0);	/* r is a valid entry. */
4108 			next = r + 1;
4109 			MPASS(next->size > 0);	/* and so is the next one. */
4110 
4111 			while (r->start + r->size >= next->start) {
4112 				/* Merge the next one into the current entry. */
4113 				r->size = max(r->start + r->size,
4114 				    next->start + next->size) - r->start;
4115 				n--;	/* One fewer entry in total. */
4116 				if (--remaining == 0)
4117 					goto done;	/* short circuit */
4118 				next++;
4119 			}
4120 			if (next != r + 1) {
4121 				/*
4122 				 * Some entries were merged into r and next
4123 				 * points to the first valid entry that couldn't
4124 				 * be merged.
4125 				 */
4126 				MPASS(next->size > 0);	/* must be valid */
4127 				memcpy(r + 1, next, remaining * sizeof(*r));
4128 #ifdef INVARIANTS
4129 				/*
4130 				 * This so that the foo->size assertion in the
4131 				 * next iteration of the loop do the right
4132 				 * thing for entries that were pulled up and are
4133 				 * no longer valid.
4134 				 */
4135 				MPASS(n < nitems(mem_ranges));
4136 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4137 				    sizeof(struct t4_range));
4138 #endif
4139 			}
4140 		}
4141 done:
4142 		/* Done merging the ranges. */
4143 		MPASS(n > 0);
4144 		r = &mem_ranges[0];
4145 		for (i = 0; i < n; i++, r++) {
4146 			if (addr >= r->start &&
4147 			    addr + len <= r->start + r->size)
4148 				return (0);
4149 		}
4150 	}
4151 
4152 	return (EFAULT);
4153 }
4154 
4155 static int
4156 fwmtype_to_hwmtype(int mtype)
4157 {
4158 
4159 	switch (mtype) {
4160 	case FW_MEMTYPE_EDC0:
4161 		return (MEM_EDC0);
4162 	case FW_MEMTYPE_EDC1:
4163 		return (MEM_EDC1);
4164 	case FW_MEMTYPE_EXTMEM:
4165 		return (MEM_MC0);
4166 	case FW_MEMTYPE_EXTMEM1:
4167 		return (MEM_MC1);
4168 	default:
4169 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4170 	}
4171 }
4172 
4173 /*
4174  * Verify that the memory range specified by the memtype/offset/len pair is
4175  * valid and lies entirely within the memtype specified.  The global address of
4176  * the start of the range is returned in addr.
4177  */
4178 static int
4179 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4180     uint32_t *addr)
4181 {
4182 	uint32_t em, addr_len, maddr;
4183 
4184 	/* Memory can only be accessed in naturally aligned 4 byte units */
4185 	if (off & 3 || len & 3 || len == 0)
4186 		return (EINVAL);
4187 
4188 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4189 	switch (fwmtype_to_hwmtype(mtype)) {
4190 	case MEM_EDC0:
4191 		if (!(em & F_EDRAM0_ENABLE))
4192 			return (EINVAL);
4193 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4194 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4195 		break;
4196 	case MEM_EDC1:
4197 		if (!(em & F_EDRAM1_ENABLE))
4198 			return (EINVAL);
4199 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4200 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4201 		break;
4202 	case MEM_MC:
4203 		if (!(em & F_EXT_MEM_ENABLE))
4204 			return (EINVAL);
4205 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4206 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4207 		break;
4208 	case MEM_MC1:
4209 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4210 			return (EINVAL);
4211 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4212 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4213 		break;
4214 	default:
4215 		return (EINVAL);
4216 	}
4217 
4218 	*addr = maddr + off;	/* global address */
4219 	return (validate_mem_range(sc, *addr, len));
4220 }
4221 
4222 static int
4223 fixup_devlog_params(struct adapter *sc)
4224 {
4225 	struct devlog_params *dparams = &sc->params.devlog;
4226 	int rc;
4227 
4228 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4229 	    dparams->size, &dparams->addr);
4230 
4231 	return (rc);
4232 }
4233 
4234 static void
4235 update_nirq(struct intrs_and_queues *iaq, int nports)
4236 {
4237 
4238 	iaq->nirq = T4_EXTRA_INTR;
4239 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4240 	iaq->nirq += nports * iaq->nofldrxq;
4241 	iaq->nirq += nports * (iaq->num_vis - 1) *
4242 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4243 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4244 }
4245 
4246 /*
4247  * Adjust requirements to fit the number of interrupts available.
4248  */
4249 static void
4250 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4251     int navail)
4252 {
4253 	int old_nirq;
4254 	const int nports = sc->params.nports;
4255 
4256 	MPASS(nports > 0);
4257 	MPASS(navail > 0);
4258 
4259 	bzero(iaq, sizeof(*iaq));
4260 	iaq->intr_type = itype;
4261 	iaq->num_vis = t4_num_vis;
4262 	iaq->ntxq = t4_ntxq;
4263 	iaq->ntxq_vi = t4_ntxq_vi;
4264 	iaq->nrxq = t4_nrxq;
4265 	iaq->nrxq_vi = t4_nrxq_vi;
4266 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4267 	if (is_offload(sc) || is_ethoffload(sc)) {
4268 		iaq->nofldtxq = t4_nofldtxq;
4269 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4270 	}
4271 #endif
4272 #ifdef TCP_OFFLOAD
4273 	if (is_offload(sc)) {
4274 		iaq->nofldrxq = t4_nofldrxq;
4275 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4276 	}
4277 #endif
4278 #ifdef DEV_NETMAP
4279 	if (t4_native_netmap & NN_MAIN_VI) {
4280 		iaq->nnmtxq = t4_nnmtxq;
4281 		iaq->nnmrxq = t4_nnmrxq;
4282 	}
4283 	if (t4_native_netmap & NN_EXTRA_VI) {
4284 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4285 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4286 	}
4287 #endif
4288 
4289 	update_nirq(iaq, nports);
4290 	if (iaq->nirq <= navail &&
4291 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4292 		/*
4293 		 * This is the normal case -- there are enough interrupts for
4294 		 * everything.
4295 		 */
4296 		goto done;
4297 	}
4298 
4299 	/*
4300 	 * If extra VIs have been configured try reducing their count and see if
4301 	 * that works.
4302 	 */
4303 	while (iaq->num_vis > 1) {
4304 		iaq->num_vis--;
4305 		update_nirq(iaq, nports);
4306 		if (iaq->nirq <= navail &&
4307 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4308 			device_printf(sc->dev, "virtual interfaces per port "
4309 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4310 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4311 			    "itype %d, navail %u, nirq %d.\n",
4312 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4313 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4314 			    itype, navail, iaq->nirq);
4315 			goto done;
4316 		}
4317 	}
4318 
4319 	/*
4320 	 * Extra VIs will not be created.  Log a message if they were requested.
4321 	 */
4322 	MPASS(iaq->num_vis == 1);
4323 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4324 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4325 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4326 	if (iaq->num_vis != t4_num_vis) {
4327 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4328 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4329 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4330 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4331 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4332 	}
4333 
4334 	/*
4335 	 * Keep reducing the number of NIC rx queues to the next lower power of
4336 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4337 	 * if that works.
4338 	 */
4339 	do {
4340 		if (iaq->nrxq > 1) {
4341 			do {
4342 				iaq->nrxq--;
4343 			} while (!powerof2(iaq->nrxq));
4344 			if (iaq->nnmrxq > iaq->nrxq)
4345 				iaq->nnmrxq = iaq->nrxq;
4346 		}
4347 		if (iaq->nofldrxq > 1)
4348 			iaq->nofldrxq >>= 1;
4349 
4350 		old_nirq = iaq->nirq;
4351 		update_nirq(iaq, nports);
4352 		if (iaq->nirq <= navail &&
4353 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4354 			device_printf(sc->dev, "running with reduced number of "
4355 			    "rx queues because of shortage of interrupts.  "
4356 			    "nrxq=%u, nofldrxq=%u.  "
4357 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4358 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4359 			goto done;
4360 		}
4361 	} while (old_nirq != iaq->nirq);
4362 
4363 	/* One interrupt for everything.  Ugh. */
4364 	device_printf(sc->dev, "running with minimal number of queues.  "
4365 	    "itype %d, navail %u.\n", itype, navail);
4366 	iaq->nirq = 1;
4367 	iaq->nrxq = 1;
4368 	iaq->ntxq = 1;
4369 	if (iaq->nofldrxq > 0) {
4370 		iaq->nofldrxq = 1;
4371 		iaq->nofldtxq = 1;
4372 	}
4373 	iaq->nnmtxq = 0;
4374 	iaq->nnmrxq = 0;
4375 done:
4376 	MPASS(iaq->num_vis > 0);
4377 	if (iaq->num_vis > 1) {
4378 		MPASS(iaq->nrxq_vi > 0);
4379 		MPASS(iaq->ntxq_vi > 0);
4380 	}
4381 	MPASS(iaq->nirq > 0);
4382 	MPASS(iaq->nrxq > 0);
4383 	MPASS(iaq->ntxq > 0);
4384 	if (itype == INTR_MSI) {
4385 		MPASS(powerof2(iaq->nirq));
4386 	}
4387 }
4388 
4389 static int
4390 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4391 {
4392 	int rc, itype, navail, nalloc;
4393 
4394 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4395 
4396 		if ((itype & t4_intr_types) == 0)
4397 			continue;	/* not allowed */
4398 
4399 		if (itype == INTR_MSIX)
4400 			navail = pci_msix_count(sc->dev);
4401 		else if (itype == INTR_MSI)
4402 			navail = pci_msi_count(sc->dev);
4403 		else
4404 			navail = 1;
4405 restart:
4406 		if (navail == 0)
4407 			continue;
4408 
4409 		calculate_iaq(sc, iaq, itype, navail);
4410 		nalloc = iaq->nirq;
4411 		rc = 0;
4412 		if (itype == INTR_MSIX)
4413 			rc = pci_alloc_msix(sc->dev, &nalloc);
4414 		else if (itype == INTR_MSI)
4415 			rc = pci_alloc_msi(sc->dev, &nalloc);
4416 
4417 		if (rc == 0 && nalloc > 0) {
4418 			if (nalloc == iaq->nirq)
4419 				return (0);
4420 
4421 			/*
4422 			 * Didn't get the number requested.  Use whatever number
4423 			 * the kernel is willing to allocate.
4424 			 */
4425 			device_printf(sc->dev, "fewer vectors than requested, "
4426 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4427 			    itype, iaq->nirq, nalloc);
4428 			pci_release_msi(sc->dev);
4429 			navail = nalloc;
4430 			goto restart;
4431 		}
4432 
4433 		device_printf(sc->dev,
4434 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4435 		    itype, rc, iaq->nirq, nalloc);
4436 	}
4437 
4438 	device_printf(sc->dev,
4439 	    "failed to find a usable interrupt type.  "
4440 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4441 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4442 
4443 	return (ENXIO);
4444 }
4445 
4446 #define FW_VERSION(chip) ( \
4447     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4448     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4449     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4450     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4451 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4452 
4453 /* Just enough of fw_hdr to cover all version info. */
4454 struct fw_h {
4455 	__u8	ver;
4456 	__u8	chip;
4457 	__be16	len512;
4458 	__be32	fw_ver;
4459 	__be32	tp_microcode_ver;
4460 	__u8	intfver_nic;
4461 	__u8	intfver_vnic;
4462 	__u8	intfver_ofld;
4463 	__u8	intfver_ri;
4464 	__u8	intfver_iscsipdu;
4465 	__u8	intfver_iscsi;
4466 	__u8	intfver_fcoepdu;
4467 	__u8	intfver_fcoe;
4468 };
4469 /* Spot check a couple of fields. */
4470 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4471 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4472 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4473 
4474 struct fw_info {
4475 	uint8_t chip;
4476 	char *kld_name;
4477 	char *fw_mod_name;
4478 	struct fw_h fw_h;
4479 } fw_info[] = {
4480 	{
4481 		.chip = CHELSIO_T4,
4482 		.kld_name = "t4fw_cfg",
4483 		.fw_mod_name = "t4fw",
4484 		.fw_h = {
4485 			.chip = FW_HDR_CHIP_T4,
4486 			.fw_ver = htobe32(FW_VERSION(T4)),
4487 			.intfver_nic = FW_INTFVER(T4, NIC),
4488 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4489 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4490 			.intfver_ri = FW_INTFVER(T4, RI),
4491 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4492 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4493 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4494 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4495 		},
4496 	}, {
4497 		.chip = CHELSIO_T5,
4498 		.kld_name = "t5fw_cfg",
4499 		.fw_mod_name = "t5fw",
4500 		.fw_h = {
4501 			.chip = FW_HDR_CHIP_T5,
4502 			.fw_ver = htobe32(FW_VERSION(T5)),
4503 			.intfver_nic = FW_INTFVER(T5, NIC),
4504 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4505 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4506 			.intfver_ri = FW_INTFVER(T5, RI),
4507 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4508 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4509 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4510 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4511 		},
4512 	}, {
4513 		.chip = CHELSIO_T6,
4514 		.kld_name = "t6fw_cfg",
4515 		.fw_mod_name = "t6fw",
4516 		.fw_h = {
4517 			.chip = FW_HDR_CHIP_T6,
4518 			.fw_ver = htobe32(FW_VERSION(T6)),
4519 			.intfver_nic = FW_INTFVER(T6, NIC),
4520 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4521 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4522 			.intfver_ri = FW_INTFVER(T6, RI),
4523 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4524 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4525 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4526 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4527 		},
4528 	}
4529 };
4530 
4531 static struct fw_info *
4532 find_fw_info(int chip)
4533 {
4534 	int i;
4535 
4536 	for (i = 0; i < nitems(fw_info); i++) {
4537 		if (fw_info[i].chip == chip)
4538 			return (&fw_info[i]);
4539 	}
4540 	return (NULL);
4541 }
4542 
4543 /*
4544  * Is the given firmware API compatible with the one the driver was compiled
4545  * with?
4546  */
4547 static int
4548 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4549 {
4550 
4551 	/* short circuit if it's the exact same firmware version */
4552 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4553 		return (1);
4554 
4555 	/*
4556 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4557 	 * features that are supported in the driver.
4558 	 */
4559 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4560 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4561 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4562 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4563 		return (1);
4564 #undef SAME_INTF
4565 
4566 	return (0);
4567 }
4568 
4569 static int
4570 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4571     const struct firmware **fw)
4572 {
4573 	struct fw_info *fw_info;
4574 
4575 	*dcfg = NULL;
4576 	if (fw != NULL)
4577 		*fw = NULL;
4578 
4579 	fw_info = find_fw_info(chip_id(sc));
4580 	if (fw_info == NULL) {
4581 		device_printf(sc->dev,
4582 		    "unable to look up firmware information for chip %d.\n",
4583 		    chip_id(sc));
4584 		return (EINVAL);
4585 	}
4586 
4587 	*dcfg = firmware_get(fw_info->kld_name);
4588 	if (*dcfg != NULL) {
4589 		if (fw != NULL)
4590 			*fw = firmware_get(fw_info->fw_mod_name);
4591 		return (0);
4592 	}
4593 
4594 	return (ENOENT);
4595 }
4596 
4597 static void
4598 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4599     const struct firmware *fw)
4600 {
4601 
4602 	if (fw != NULL)
4603 		firmware_put(fw, FIRMWARE_UNLOAD);
4604 	if (dcfg != NULL)
4605 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4606 }
4607 
4608 /*
4609  * Return values:
4610  * 0 means no firmware install attempted.
4611  * ERESTART means a firmware install was attempted and was successful.
4612  * +ve errno means a firmware install was attempted but failed.
4613  */
4614 static int
4615 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4616     const struct fw_h *drv_fw, const char *reason, int *already)
4617 {
4618 	const struct firmware *cfg, *fw;
4619 	const uint32_t c = be32toh(card_fw->fw_ver);
4620 	uint32_t d, k;
4621 	int rc, fw_install;
4622 	struct fw_h bundled_fw;
4623 	bool load_attempted;
4624 
4625 	cfg = fw = NULL;
4626 	load_attempted = false;
4627 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4628 
4629 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4630 	if (t4_fw_install < 0) {
4631 		rc = load_fw_module(sc, &cfg, &fw);
4632 		if (rc != 0 || fw == NULL) {
4633 			device_printf(sc->dev,
4634 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4635 			    " will use compiled-in firmware version for"
4636 			    "hw.cxgbe.fw_install checks.\n",
4637 			    rc, cfg, fw);
4638 		} else {
4639 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4640 		}
4641 		load_attempted = true;
4642 	}
4643 	d = be32toh(bundled_fw.fw_ver);
4644 
4645 	if (reason != NULL)
4646 		goto install;
4647 
4648 	if ((sc->flags & FW_OK) == 0) {
4649 
4650 		if (c == 0xffffffff) {
4651 			reason = "missing";
4652 			goto install;
4653 		}
4654 
4655 		rc = 0;
4656 		goto done;
4657 	}
4658 
4659 	if (!fw_compatible(card_fw, &bundled_fw)) {
4660 		reason = "incompatible or unusable";
4661 		goto install;
4662 	}
4663 
4664 	if (d > c) {
4665 		reason = "older than the version bundled with this driver";
4666 		goto install;
4667 	}
4668 
4669 	if (fw_install == 2 && d != c) {
4670 		reason = "different than the version bundled with this driver";
4671 		goto install;
4672 	}
4673 
4674 	/* No reason to do anything to the firmware already on the card. */
4675 	rc = 0;
4676 	goto done;
4677 
4678 install:
4679 	rc = 0;
4680 	if ((*already)++)
4681 		goto done;
4682 
4683 	if (fw_install == 0) {
4684 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4685 		    "but the driver is prohibited from installing a firmware "
4686 		    "on the card.\n",
4687 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4688 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4689 
4690 		goto done;
4691 	}
4692 
4693 	/*
4694 	 * We'll attempt to install a firmware.  Load the module first (if it
4695 	 * hasn't been loaded already).
4696 	 */
4697 	if (!load_attempted) {
4698 		rc = load_fw_module(sc, &cfg, &fw);
4699 		if (rc != 0 || fw == NULL) {
4700 			device_printf(sc->dev,
4701 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4702 			    rc, cfg, fw);
4703 			/* carry on */
4704 		}
4705 	}
4706 	if (fw == NULL) {
4707 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4708 		    "but the driver cannot take corrective action because it "
4709 		    "is unable to load the firmware module.\n",
4710 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4711 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4712 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4713 		goto done;
4714 	}
4715 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4716 	if (k != d) {
4717 		MPASS(t4_fw_install > 0);
4718 		device_printf(sc->dev,
4719 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4720 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4721 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4722 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4723 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4724 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4725 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4726 		goto done;
4727 	}
4728 
4729 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4730 	    "installing firmware %u.%u.%u.%u on card.\n",
4731 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4732 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4733 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4734 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4735 
4736 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4737 	if (rc != 0) {
4738 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4739 	} else {
4740 		/* Installed successfully, update the cached header too. */
4741 		rc = ERESTART;
4742 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4743 	}
4744 done:
4745 	unload_fw_module(sc, cfg, fw);
4746 
4747 	return (rc);
4748 }
4749 
4750 /*
4751  * Establish contact with the firmware and attempt to become the master driver.
4752  *
4753  * A firmware will be installed to the card if needed (if the driver is allowed
4754  * to do so).
4755  */
4756 static int
4757 contact_firmware(struct adapter *sc)
4758 {
4759 	int rc, already = 0;
4760 	enum dev_state state;
4761 	struct fw_info *fw_info;
4762 	struct fw_hdr *card_fw;		/* fw on the card */
4763 	const struct fw_h *drv_fw;
4764 
4765 	fw_info = find_fw_info(chip_id(sc));
4766 	if (fw_info == NULL) {
4767 		device_printf(sc->dev,
4768 		    "unable to look up firmware information for chip %d.\n",
4769 		    chip_id(sc));
4770 		return (EINVAL);
4771 	}
4772 	drv_fw = &fw_info->fw_h;
4773 
4774 	/* Read the header of the firmware on the card */
4775 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4776 restart:
4777 	rc = -t4_get_fw_hdr(sc, card_fw);
4778 	if (rc != 0) {
4779 		device_printf(sc->dev,
4780 		    "unable to read firmware header from card's flash: %d\n",
4781 		    rc);
4782 		goto done;
4783 	}
4784 
4785 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4786 	    &already);
4787 	if (rc == ERESTART)
4788 		goto restart;
4789 	if (rc != 0)
4790 		goto done;
4791 
4792 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4793 	if (rc < 0 || state == DEV_STATE_ERR) {
4794 		rc = -rc;
4795 		device_printf(sc->dev,
4796 		    "failed to connect to the firmware: %d, %d.  "
4797 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4798 #if 0
4799 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4800 		    "not responding properly to HELLO", &already) == ERESTART)
4801 			goto restart;
4802 #endif
4803 		goto done;
4804 	}
4805 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4806 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4807 
4808 	if (rc == sc->pf) {
4809 		sc->flags |= MASTER_PF;
4810 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4811 		    NULL, &already);
4812 		if (rc == ERESTART)
4813 			rc = 0;
4814 		else if (rc != 0)
4815 			goto done;
4816 	} else if (state == DEV_STATE_UNINIT) {
4817 		/*
4818 		 * We didn't get to be the master so we definitely won't be
4819 		 * configuring the chip.  It's a bug if someone else hasn't
4820 		 * configured it already.
4821 		 */
4822 		device_printf(sc->dev, "couldn't be master(%d), "
4823 		    "device not already initialized either(%d).  "
4824 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4825 		rc = EPROTO;
4826 		goto done;
4827 	} else {
4828 		/*
4829 		 * Some other PF is the master and has configured the chip.
4830 		 * This is allowed but untested.
4831 		 */
4832 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4833 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4834 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4835 		sc->cfcsum = 0;
4836 		rc = 0;
4837 	}
4838 done:
4839 	if (rc != 0 && sc->flags & FW_OK) {
4840 		t4_fw_bye(sc, sc->mbox);
4841 		sc->flags &= ~FW_OK;
4842 	}
4843 	free(card_fw, M_CXGBE);
4844 	return (rc);
4845 }
4846 
4847 static int
4848 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4849     uint32_t mtype, uint32_t moff)
4850 {
4851 	struct fw_info *fw_info;
4852 	const struct firmware *dcfg, *rcfg = NULL;
4853 	const uint32_t *cfdata;
4854 	uint32_t cflen, addr;
4855 	int rc;
4856 
4857 	load_fw_module(sc, &dcfg, NULL);
4858 
4859 	/* Card specific interpretation of "default". */
4860 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4861 		if (pci_get_device(sc->dev) == 0x440a)
4862 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4863 		if (is_fpga(sc))
4864 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4865 	}
4866 
4867 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4868 		if (dcfg == NULL) {
4869 			device_printf(sc->dev,
4870 			    "KLD with default config is not available.\n");
4871 			rc = ENOENT;
4872 			goto done;
4873 		}
4874 		cfdata = dcfg->data;
4875 		cflen = dcfg->datasize & ~3;
4876 	} else {
4877 		char s[32];
4878 
4879 		fw_info = find_fw_info(chip_id(sc));
4880 		if (fw_info == NULL) {
4881 			device_printf(sc->dev,
4882 			    "unable to look up firmware information for chip %d.\n",
4883 			    chip_id(sc));
4884 			rc = EINVAL;
4885 			goto done;
4886 		}
4887 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4888 
4889 		rcfg = firmware_get(s);
4890 		if (rcfg == NULL) {
4891 			device_printf(sc->dev,
4892 			    "unable to load module \"%s\" for configuration "
4893 			    "profile \"%s\".\n", s, cfg_file);
4894 			rc = ENOENT;
4895 			goto done;
4896 		}
4897 		cfdata = rcfg->data;
4898 		cflen = rcfg->datasize & ~3;
4899 	}
4900 
4901 	if (cflen > FLASH_CFG_MAX_SIZE) {
4902 		device_printf(sc->dev,
4903 		    "config file too long (%d, max allowed is %d).\n",
4904 		    cflen, FLASH_CFG_MAX_SIZE);
4905 		rc = EINVAL;
4906 		goto done;
4907 	}
4908 
4909 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4910 	if (rc != 0) {
4911 		device_printf(sc->dev,
4912 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4913 		    __func__, mtype, moff, cflen, rc);
4914 		rc = EINVAL;
4915 		goto done;
4916 	}
4917 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4918 done:
4919 	if (rcfg != NULL)
4920 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4921 	unload_fw_module(sc, dcfg, NULL);
4922 	return (rc);
4923 }
4924 
4925 struct caps_allowed {
4926 	uint16_t nbmcaps;
4927 	uint16_t linkcaps;
4928 	uint16_t switchcaps;
4929 	uint16_t niccaps;
4930 	uint16_t toecaps;
4931 	uint16_t rdmacaps;
4932 	uint16_t cryptocaps;
4933 	uint16_t iscsicaps;
4934 	uint16_t fcoecaps;
4935 };
4936 
4937 #define FW_PARAM_DEV(param) \
4938 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4939 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4940 #define FW_PARAM_PFVF(param) \
4941 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4942 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4943 
4944 /*
4945  * Provide a configuration profile to the firmware and have it initialize the
4946  * chip accordingly.  This may involve uploading a configuration file to the
4947  * card.
4948  */
4949 static int
4950 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4951     const struct caps_allowed *caps_allowed)
4952 {
4953 	int rc;
4954 	struct fw_caps_config_cmd caps;
4955 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4956 
4957 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4958 	if (rc != 0) {
4959 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4960 		return (rc);
4961 	}
4962 
4963 	bzero(&caps, sizeof(caps));
4964 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4965 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4966 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4967 		mtype = 0;
4968 		moff = 0;
4969 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4970 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4971 		mtype = FW_MEMTYPE_FLASH;
4972 		moff = t4_flash_cfg_addr(sc);
4973 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4974 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4975 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4976 		    FW_LEN16(caps));
4977 	} else {
4978 		/*
4979 		 * Ask the firmware where it wants us to upload the config file.
4980 		 */
4981 		param = FW_PARAM_DEV(CF);
4982 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4983 		if (rc != 0) {
4984 			/* No support for config file?  Shouldn't happen. */
4985 			device_printf(sc->dev,
4986 			    "failed to query config file location: %d.\n", rc);
4987 			goto done;
4988 		}
4989 		mtype = G_FW_PARAMS_PARAM_Y(val);
4990 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4991 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4992 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4993 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4994 		    FW_LEN16(caps));
4995 
4996 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4997 		if (rc != 0) {
4998 			device_printf(sc->dev,
4999 			    "failed to upload config file to card: %d.\n", rc);
5000 			goto done;
5001 		}
5002 	}
5003 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5004 	if (rc != 0) {
5005 		device_printf(sc->dev, "failed to pre-process config file: %d "
5006 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5007 		goto done;
5008 	}
5009 
5010 	finicsum = be32toh(caps.finicsum);
5011 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5012 	if (finicsum != cfcsum) {
5013 		device_printf(sc->dev,
5014 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5015 		    finicsum, cfcsum);
5016 	}
5017 	sc->cfcsum = cfcsum;
5018 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5019 
5020 	/*
5021 	 * Let the firmware know what features will (not) be used so it can tune
5022 	 * things accordingly.
5023 	 */
5024 #define LIMIT_CAPS(x) do { \
5025 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5026 } while (0)
5027 	LIMIT_CAPS(nbm);
5028 	LIMIT_CAPS(link);
5029 	LIMIT_CAPS(switch);
5030 	LIMIT_CAPS(nic);
5031 	LIMIT_CAPS(toe);
5032 	LIMIT_CAPS(rdma);
5033 	LIMIT_CAPS(crypto);
5034 	LIMIT_CAPS(iscsi);
5035 	LIMIT_CAPS(fcoe);
5036 #undef LIMIT_CAPS
5037 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5038 		/*
5039 		 * TOE and hashfilters are mutually exclusive.  It is a config
5040 		 * file or firmware bug if both are reported as available.  Try
5041 		 * to cope with the situation in non-debug builds by disabling
5042 		 * TOE.
5043 		 */
5044 		MPASS(caps.toecaps == 0);
5045 
5046 		caps.toecaps = 0;
5047 		caps.rdmacaps = 0;
5048 		caps.iscsicaps = 0;
5049 	}
5050 
5051 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5052 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5053 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5054 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5055 	if (rc != 0) {
5056 		device_printf(sc->dev,
5057 		    "failed to process config file: %d.\n", rc);
5058 		goto done;
5059 	}
5060 
5061 	t4_tweak_chip_settings(sc);
5062 	set_params__pre_init(sc);
5063 
5064 	/* get basic stuff going */
5065 	rc = -t4_fw_initialize(sc, sc->mbox);
5066 	if (rc != 0) {
5067 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5068 		goto done;
5069 	}
5070 done:
5071 	return (rc);
5072 }
5073 
5074 /*
5075  * Partition chip resources for use between various PFs, VFs, etc.
5076  */
5077 static int
5078 partition_resources(struct adapter *sc)
5079 {
5080 	char cfg_file[sizeof(t4_cfg_file)];
5081 	struct caps_allowed caps_allowed;
5082 	int rc;
5083 	bool fallback;
5084 
5085 	/* Only the master driver gets to configure the chip resources. */
5086 	MPASS(sc->flags & MASTER_PF);
5087 
5088 #define COPY_CAPS(x) do { \
5089 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5090 } while (0)
5091 	bzero(&caps_allowed, sizeof(caps_allowed));
5092 	COPY_CAPS(nbm);
5093 	COPY_CAPS(link);
5094 	COPY_CAPS(switch);
5095 	COPY_CAPS(nic);
5096 	COPY_CAPS(toe);
5097 	COPY_CAPS(rdma);
5098 	COPY_CAPS(crypto);
5099 	COPY_CAPS(iscsi);
5100 	COPY_CAPS(fcoe);
5101 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5102 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5103 retry:
5104 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5105 	if (rc != 0 && fallback) {
5106 		dump_devlog(sc);
5107 		device_printf(sc->dev,
5108 		    "failed (%d) to configure card with \"%s\" profile, "
5109 		    "will fall back to a basic configuration and retry.\n",
5110 		    rc, cfg_file);
5111 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5112 		bzero(&caps_allowed, sizeof(caps_allowed));
5113 		COPY_CAPS(switch);
5114 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5115 		fallback = false;
5116 		goto retry;
5117 	}
5118 #undef COPY_CAPS
5119 	return (rc);
5120 }
5121 
5122 /*
5123  * Retrieve parameters that are needed (or nice to have) very early.
5124  */
5125 static int
5126 get_params__pre_init(struct adapter *sc)
5127 {
5128 	int rc;
5129 	uint32_t param[2], val[2];
5130 
5131 	t4_get_version_info(sc);
5132 
5133 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5134 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5135 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5136 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5137 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5138 
5139 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5140 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5141 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5142 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5143 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5144 
5145 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5146 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5147 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5148 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5149 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5150 
5151 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5152 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5153 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5154 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5155 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5156 
5157 	param[0] = FW_PARAM_DEV(PORTVEC);
5158 	param[1] = FW_PARAM_DEV(CCLK);
5159 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5160 	if (rc != 0) {
5161 		device_printf(sc->dev,
5162 		    "failed to query parameters (pre_init): %d.\n", rc);
5163 		return (rc);
5164 	}
5165 
5166 	sc->params.portvec = val[0];
5167 	sc->params.nports = bitcount32(val[0]);
5168 	sc->params.vpd.cclk = val[1];
5169 
5170 	/* Read device log parameters. */
5171 	rc = -t4_init_devlog_params(sc, 1);
5172 	if (rc == 0)
5173 		fixup_devlog_params(sc);
5174 	else {
5175 		device_printf(sc->dev,
5176 		    "failed to get devlog parameters: %d.\n", rc);
5177 		rc = 0;	/* devlog isn't critical for device operation */
5178 	}
5179 
5180 	return (rc);
5181 }
5182 
5183 /*
5184  * Any params that need to be set before FW_INITIALIZE.
5185  */
5186 static int
5187 set_params__pre_init(struct adapter *sc)
5188 {
5189 	int rc = 0;
5190 	uint32_t param, val;
5191 
5192 	if (chip_id(sc) >= CHELSIO_T6) {
5193 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5194 		val = 1;
5195 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5196 		/* firmwares < 1.20.1.0 do not have this param. */
5197 		if (rc == FW_EINVAL &&
5198 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5199 			rc = 0;
5200 		}
5201 		if (rc != 0) {
5202 			device_printf(sc->dev,
5203 			    "failed to enable high priority filters :%d.\n",
5204 			    rc);
5205 		}
5206 
5207 		param = FW_PARAM_DEV(PPOD_EDRAM);
5208 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5209 		if (rc == 0 && val == 1) {
5210 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5211 			    &val);
5212 			if (rc != 0) {
5213 				device_printf(sc->dev,
5214 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5215 			}
5216 		}
5217 	}
5218 
5219 	/* Enable opaque VIIDs with firmwares that support it. */
5220 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5221 	val = 1;
5222 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5223 	if (rc == 0 && val == 1)
5224 		sc->params.viid_smt_extn_support = true;
5225 	else
5226 		sc->params.viid_smt_extn_support = false;
5227 
5228 	return (rc);
5229 }
5230 
5231 /*
5232  * Retrieve various parameters that are of interest to the driver.  The device
5233  * has been initialized by the firmware at this point.
5234  */
5235 static int
5236 get_params__post_init(struct adapter *sc)
5237 {
5238 	int rc;
5239 	uint32_t param[7], val[7];
5240 	struct fw_caps_config_cmd caps;
5241 
5242 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5243 	param[1] = FW_PARAM_PFVF(EQ_START);
5244 	param[2] = FW_PARAM_PFVF(FILTER_START);
5245 	param[3] = FW_PARAM_PFVF(FILTER_END);
5246 	param[4] = FW_PARAM_PFVF(L2T_START);
5247 	param[5] = FW_PARAM_PFVF(L2T_END);
5248 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5249 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5250 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5251 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5252 	if (rc != 0) {
5253 		device_printf(sc->dev,
5254 		    "failed to query parameters (post_init): %d.\n", rc);
5255 		return (rc);
5256 	}
5257 
5258 	sc->sge.iq_start = val[0];
5259 	sc->sge.eq_start = val[1];
5260 	if ((int)val[3] > (int)val[2]) {
5261 		sc->tids.ftid_base = val[2];
5262 		sc->tids.ftid_end = val[3];
5263 		sc->tids.nftids = val[3] - val[2] + 1;
5264 	}
5265 	sc->vres.l2t.start = val[4];
5266 	sc->vres.l2t.size = val[5] - val[4] + 1;
5267 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5268 	    ("%s: L2 table size (%u) larger than expected (%u)",
5269 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5270 	sc->params.core_vdd = val[6];
5271 
5272 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5273 	param[1] = FW_PARAM_PFVF(EQ_END);
5274 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5275 	if (rc != 0) {
5276 		device_printf(sc->dev,
5277 		    "failed to query parameters (post_init2): %d.\n", rc);
5278 		return (rc);
5279 	}
5280 	MPASS((int)val[0] >= sc->sge.iq_start);
5281 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5282 	MPASS((int)val[1] >= sc->sge.eq_start);
5283 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5284 
5285 	if (chip_id(sc) >= CHELSIO_T6) {
5286 
5287 		sc->tids.tid_base = t4_read_reg(sc,
5288 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5289 
5290 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5291 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5292 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5293 		if (rc != 0) {
5294 			device_printf(sc->dev,
5295 			   "failed to query hpfilter parameters: %d.\n", rc);
5296 			return (rc);
5297 		}
5298 		if ((int)val[1] > (int)val[0]) {
5299 			sc->tids.hpftid_base = val[0];
5300 			sc->tids.hpftid_end = val[1];
5301 			sc->tids.nhpftids = val[1] - val[0] + 1;
5302 
5303 			/*
5304 			 * These should go off if the layout changes and the
5305 			 * driver needs to catch up.
5306 			 */
5307 			MPASS(sc->tids.hpftid_base == 0);
5308 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5309 		}
5310 
5311 		param[0] = FW_PARAM_PFVF(RAWF_START);
5312 		param[1] = FW_PARAM_PFVF(RAWF_END);
5313 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5314 		if (rc != 0) {
5315 			device_printf(sc->dev,
5316 			   "failed to query rawf parameters: %d.\n", rc);
5317 			return (rc);
5318 		}
5319 		if ((int)val[1] > (int)val[0]) {
5320 			sc->rawf_base = val[0];
5321 			sc->nrawf = val[1] - val[0] + 1;
5322 		}
5323 	}
5324 
5325 	/*
5326 	 * The parameters that follow may not be available on all firmwares.  We
5327 	 * query them individually rather than in a compound query because old
5328 	 * firmwares fail the entire query if an unknown parameter is queried.
5329 	 */
5330 
5331 	/*
5332 	 * MPS buffer group configuration.
5333 	 */
5334 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5335 	val[0] = 0;
5336 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5337 	if (rc == 0)
5338 		sc->params.mps_bg_map = val[0];
5339 	else
5340 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5341 
5342 	param[0] = FW_PARAM_DEV(TPCHMAP);
5343 	val[0] = 0;
5344 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5345 	if (rc == 0)
5346 		sc->params.tp_ch_map = val[0];
5347 	else
5348 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5349 
5350 	/*
5351 	 * Determine whether the firmware supports the filter2 work request.
5352 	 */
5353 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5354 	val[0] = 0;
5355 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5356 	if (rc == 0)
5357 		sc->params.filter2_wr_support = val[0] != 0;
5358 	else
5359 		sc->params.filter2_wr_support = 0;
5360 
5361 	/*
5362 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5363 	 */
5364 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5365 	val[0] = 0;
5366 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5367 	if (rc == 0)
5368 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5369 	else
5370 		sc->params.ulptx_memwrite_dsgl = false;
5371 
5372 	/* FW_RI_FR_NSMR_TPTE_WR support */
5373 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5374 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5375 	if (rc == 0)
5376 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5377 	else
5378 		sc->params.fr_nsmr_tpte_wr_support = false;
5379 
5380 	/* Support for 512 SGL entries per FR MR. */
5381 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5382 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5383 	if (rc == 0)
5384 		sc->params.dev_512sgl_mr = val[0] != 0;
5385 	else
5386 		sc->params.dev_512sgl_mr = false;
5387 
5388 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5389 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5390 	if (rc == 0)
5391 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5392 	else
5393 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5394 
5395 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5396 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5397 	if (rc == 0) {
5398 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5399 		sc->params.nsched_cls = val[0];
5400 	} else
5401 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5402 
5403 	/* get capabilites */
5404 	bzero(&caps, sizeof(caps));
5405 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5406 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5407 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5408 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5409 	if (rc != 0) {
5410 		device_printf(sc->dev,
5411 		    "failed to get card capabilities: %d.\n", rc);
5412 		return (rc);
5413 	}
5414 
5415 #define READ_CAPS(x) do { \
5416 	sc->x = htobe16(caps.x); \
5417 } while (0)
5418 	READ_CAPS(nbmcaps);
5419 	READ_CAPS(linkcaps);
5420 	READ_CAPS(switchcaps);
5421 	READ_CAPS(niccaps);
5422 	READ_CAPS(toecaps);
5423 	READ_CAPS(rdmacaps);
5424 	READ_CAPS(cryptocaps);
5425 	READ_CAPS(iscsicaps);
5426 	READ_CAPS(fcoecaps);
5427 
5428 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5429 		MPASS(chip_id(sc) > CHELSIO_T4);
5430 		MPASS(sc->toecaps == 0);
5431 		sc->toecaps = 0;
5432 
5433 		param[0] = FW_PARAM_DEV(NTID);
5434 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5435 		if (rc != 0) {
5436 			device_printf(sc->dev,
5437 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5438 			return (rc);
5439 		}
5440 		sc->tids.ntids = val[0];
5441 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5442 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5443 			sc->tids.ntids -= sc->tids.nhpftids;
5444 		}
5445 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5446 		sc->params.hash_filter = 1;
5447 	}
5448 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5449 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5450 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5451 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5452 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5453 		if (rc != 0) {
5454 			device_printf(sc->dev,
5455 			    "failed to query NIC parameters: %d.\n", rc);
5456 			return (rc);
5457 		}
5458 		if ((int)val[1] > (int)val[0]) {
5459 			sc->tids.etid_base = val[0];
5460 			sc->tids.etid_end = val[1];
5461 			sc->tids.netids = val[1] - val[0] + 1;
5462 			sc->params.eo_wr_cred = val[2];
5463 			sc->params.ethoffload = 1;
5464 		}
5465 	}
5466 	if (sc->toecaps) {
5467 		/* query offload-related parameters */
5468 		param[0] = FW_PARAM_DEV(NTID);
5469 		param[1] = FW_PARAM_PFVF(SERVER_START);
5470 		param[2] = FW_PARAM_PFVF(SERVER_END);
5471 		param[3] = FW_PARAM_PFVF(TDDP_START);
5472 		param[4] = FW_PARAM_PFVF(TDDP_END);
5473 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5474 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5475 		if (rc != 0) {
5476 			device_printf(sc->dev,
5477 			    "failed to query TOE parameters: %d.\n", rc);
5478 			return (rc);
5479 		}
5480 		sc->tids.ntids = val[0];
5481 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5482 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5483 			sc->tids.ntids -= sc->tids.nhpftids;
5484 		}
5485 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5486 		if ((int)val[2] > (int)val[1]) {
5487 			sc->tids.stid_base = val[1];
5488 			sc->tids.nstids = val[2] - val[1] + 1;
5489 		}
5490 		sc->vres.ddp.start = val[3];
5491 		sc->vres.ddp.size = val[4] - val[3] + 1;
5492 		sc->params.ofldq_wr_cred = val[5];
5493 		sc->params.offload = 1;
5494 	} else {
5495 		/*
5496 		 * The firmware attempts memfree TOE configuration for -SO cards
5497 		 * and will report toecaps=0 if it runs out of resources (this
5498 		 * depends on the config file).  It may not report 0 for other
5499 		 * capabilities dependent on the TOE in this case.  Set them to
5500 		 * 0 here so that the driver doesn't bother tracking resources
5501 		 * that will never be used.
5502 		 */
5503 		sc->iscsicaps = 0;
5504 		sc->rdmacaps = 0;
5505 	}
5506 	if (sc->rdmacaps) {
5507 		param[0] = FW_PARAM_PFVF(STAG_START);
5508 		param[1] = FW_PARAM_PFVF(STAG_END);
5509 		param[2] = FW_PARAM_PFVF(RQ_START);
5510 		param[3] = FW_PARAM_PFVF(RQ_END);
5511 		param[4] = FW_PARAM_PFVF(PBL_START);
5512 		param[5] = FW_PARAM_PFVF(PBL_END);
5513 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5514 		if (rc != 0) {
5515 			device_printf(sc->dev,
5516 			    "failed to query RDMA parameters(1): %d.\n", rc);
5517 			return (rc);
5518 		}
5519 		sc->vres.stag.start = val[0];
5520 		sc->vres.stag.size = val[1] - val[0] + 1;
5521 		sc->vres.rq.start = val[2];
5522 		sc->vres.rq.size = val[3] - val[2] + 1;
5523 		sc->vres.pbl.start = val[4];
5524 		sc->vres.pbl.size = val[5] - val[4] + 1;
5525 
5526 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5527 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5528 		param[2] = FW_PARAM_PFVF(CQ_START);
5529 		param[3] = FW_PARAM_PFVF(CQ_END);
5530 		param[4] = FW_PARAM_PFVF(OCQ_START);
5531 		param[5] = FW_PARAM_PFVF(OCQ_END);
5532 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5533 		if (rc != 0) {
5534 			device_printf(sc->dev,
5535 			    "failed to query RDMA parameters(2): %d.\n", rc);
5536 			return (rc);
5537 		}
5538 		sc->vres.qp.start = val[0];
5539 		sc->vres.qp.size = val[1] - val[0] + 1;
5540 		sc->vres.cq.start = val[2];
5541 		sc->vres.cq.size = val[3] - val[2] + 1;
5542 		sc->vres.ocq.start = val[4];
5543 		sc->vres.ocq.size = val[5] - val[4] + 1;
5544 
5545 		param[0] = FW_PARAM_PFVF(SRQ_START);
5546 		param[1] = FW_PARAM_PFVF(SRQ_END);
5547 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5548 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5549 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5550 		if (rc != 0) {
5551 			device_printf(sc->dev,
5552 			    "failed to query RDMA parameters(3): %d.\n", rc);
5553 			return (rc);
5554 		}
5555 		sc->vres.srq.start = val[0];
5556 		sc->vres.srq.size = val[1] - val[0] + 1;
5557 		sc->params.max_ordird_qp = val[2];
5558 		sc->params.max_ird_adapter = val[3];
5559 	}
5560 	if (sc->iscsicaps) {
5561 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5562 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5563 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5564 		if (rc != 0) {
5565 			device_printf(sc->dev,
5566 			    "failed to query iSCSI parameters: %d.\n", rc);
5567 			return (rc);
5568 		}
5569 		sc->vres.iscsi.start = val[0];
5570 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5571 	}
5572 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5573 		param[0] = FW_PARAM_PFVF(TLS_START);
5574 		param[1] = FW_PARAM_PFVF(TLS_END);
5575 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5576 		if (rc != 0) {
5577 			device_printf(sc->dev,
5578 			    "failed to query TLS parameters: %d.\n", rc);
5579 			return (rc);
5580 		}
5581 		sc->vres.key.start = val[0];
5582 		sc->vres.key.size = val[1] - val[0] + 1;
5583 	}
5584 
5585 	/*
5586 	 * We've got the params we wanted to query directly from the firmware.
5587 	 * Grab some others via other means.
5588 	 */
5589 	t4_init_sge_params(sc);
5590 	t4_init_tp_params(sc);
5591 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5592 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5593 
5594 	rc = t4_verify_chip_settings(sc);
5595 	if (rc != 0)
5596 		return (rc);
5597 	t4_init_rx_buf_info(sc);
5598 
5599 	return (rc);
5600 }
5601 
5602 #ifdef KERN_TLS
5603 static void
5604 ktls_tick(void *arg)
5605 {
5606 	struct adapter *sc;
5607 	uint32_t tstamp;
5608 
5609 	sc = arg;
5610 	tstamp = tcp_ts_getticks();
5611 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5612 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5613 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5614 }
5615 
5616 static int
5617 t6_config_kern_tls(struct adapter *sc, bool enable)
5618 {
5619 	int rc;
5620 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5621 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5622 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5623 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5624 
5625 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5626 	if (rc != 0) {
5627 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5628 		    enable ?  "enable" : "disable", rc);
5629 		return (rc);
5630 	}
5631 
5632 	if (enable) {
5633 		sc->flags |= KERN_TLS_ON;
5634 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5635 		    C_HARDCLOCK);
5636 	} else {
5637 		sc->flags &= ~KERN_TLS_ON;
5638 		callout_stop(&sc->ktls_tick);
5639 	}
5640 
5641 	return (rc);
5642 }
5643 #endif
5644 
5645 static int
5646 set_params__post_init(struct adapter *sc)
5647 {
5648 	uint32_t mask, param, val;
5649 #ifdef TCP_OFFLOAD
5650 	int i, v, shift;
5651 #endif
5652 
5653 	/* ask for encapsulated CPLs */
5654 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5655 	val = 1;
5656 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5657 
5658 	/* Enable 32b port caps if the firmware supports it. */
5659 	param = FW_PARAM_PFVF(PORT_CAPS32);
5660 	val = 1;
5661 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5662 		sc->params.port_caps32 = 1;
5663 
5664 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5665 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5666 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5667 	    V_MASKFILTER(val - 1));
5668 
5669 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5670 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5671 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5672 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5673 	val = 0;
5674 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5675 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5676 		    F_ATTACKFILTERENABLE);
5677 		val |= F_DROPERRORATTACK;
5678 	}
5679 	if (t4_drop_ip_fragments != 0) {
5680 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5681 		    F_FRAGMENTDROP);
5682 		val |= F_DROPERRORFRAG;
5683 	}
5684 	if (t4_drop_pkts_with_l2_errors != 0)
5685 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5686 	if (t4_drop_pkts_with_l3_errors != 0) {
5687 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5688 		    F_DROPERRORCSUMIP;
5689 	}
5690 	if (t4_drop_pkts_with_l4_errors != 0) {
5691 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5692 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5693 	}
5694 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5695 
5696 #ifdef TCP_OFFLOAD
5697 	/*
5698 	 * Override the TOE timers with user provided tunables.  This is not the
5699 	 * recommended way to change the timers (the firmware config file is) so
5700 	 * these tunables are not documented.
5701 	 *
5702 	 * All the timer tunables are in microseconds.
5703 	 */
5704 	if (t4_toe_keepalive_idle != 0) {
5705 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5706 		v &= M_KEEPALIVEIDLE;
5707 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5708 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5709 	}
5710 	if (t4_toe_keepalive_interval != 0) {
5711 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5712 		v &= M_KEEPALIVEINTVL;
5713 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5714 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5715 	}
5716 	if (t4_toe_keepalive_count != 0) {
5717 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5718 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5719 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5720 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5721 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5722 	}
5723 	if (t4_toe_rexmt_min != 0) {
5724 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5725 		v &= M_RXTMIN;
5726 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5727 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5728 	}
5729 	if (t4_toe_rexmt_max != 0) {
5730 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5731 		v &= M_RXTMAX;
5732 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5733 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5734 	}
5735 	if (t4_toe_rexmt_count != 0) {
5736 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5737 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5738 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5739 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5740 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5741 	}
5742 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5743 		if (t4_toe_rexmt_backoff[i] != -1) {
5744 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5745 			shift = (i & 3) << 3;
5746 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5747 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5748 		}
5749 	}
5750 #endif
5751 
5752 	/*
5753 	 * Limit TOE connections to 2 reassembly "islands".  This is
5754 	 * required to permit migrating TOE connections to either
5755 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5756 	 */
5757 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5758 	    V_PASSMODE(2));
5759 
5760 #ifdef KERN_TLS
5761 	if (is_ktls(sc)) {
5762 		sc->tlst.inline_keys = t4_tls_inline_keys;
5763 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5764 		if (t4_kern_tls != 0 && is_t6(sc))
5765 			t6_config_kern_tls(sc, true);
5766 	}
5767 #endif
5768 	return (0);
5769 }
5770 
5771 #undef FW_PARAM_PFVF
5772 #undef FW_PARAM_DEV
5773 
5774 static void
5775 t4_set_desc(struct adapter *sc)
5776 {
5777 	struct adapter_params *p = &sc->params;
5778 
5779 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5780 }
5781 
5782 static inline void
5783 ifmedia_add4(struct ifmedia *ifm, int m)
5784 {
5785 
5786 	ifmedia_add(ifm, m, 0, NULL);
5787 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5788 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5789 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5790 }
5791 
5792 /*
5793  * This is the selected media, which is not quite the same as the active media.
5794  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5795  * and active are not the same, and "media: Ethernet selected" otherwise.
5796  */
5797 static void
5798 set_current_media(struct port_info *pi)
5799 {
5800 	struct link_config *lc;
5801 	struct ifmedia *ifm;
5802 	int mword;
5803 	u_int speed;
5804 
5805 	PORT_LOCK_ASSERT_OWNED(pi);
5806 
5807 	/* Leave current media alone if it's already set to IFM_NONE. */
5808 	ifm = &pi->media;
5809 	if (ifm->ifm_cur != NULL &&
5810 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5811 		return;
5812 
5813 	lc = &pi->link_cfg;
5814 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5815 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5816 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5817 		return;
5818 	}
5819 	mword = IFM_ETHER | IFM_FDX;
5820 	if (lc->requested_fc & PAUSE_TX)
5821 		mword |= IFM_ETH_TXPAUSE;
5822 	if (lc->requested_fc & PAUSE_RX)
5823 		mword |= IFM_ETH_RXPAUSE;
5824 	if (lc->requested_speed == 0)
5825 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5826 	else
5827 		speed = lc->requested_speed;
5828 	mword |= port_mword(pi, speed_to_fwcap(speed));
5829 	ifmedia_set(ifm, mword);
5830 }
5831 
5832 /*
5833  * Returns true if the ifmedia list for the port cannot change.
5834  */
5835 static bool
5836 fixed_ifmedia(struct port_info *pi)
5837 {
5838 
5839 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5840 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5841 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5842 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5843 	    pi->port_type == FW_PORT_TYPE_KX ||
5844 	    pi->port_type == FW_PORT_TYPE_KR ||
5845 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5846 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5847 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5848 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5849 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5850 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5851 }
5852 
5853 static void
5854 build_medialist(struct port_info *pi)
5855 {
5856 	uint32_t ss, speed;
5857 	int unknown, mword, bit;
5858 	struct link_config *lc;
5859 	struct ifmedia *ifm;
5860 
5861 	PORT_LOCK_ASSERT_OWNED(pi);
5862 
5863 	if (pi->flags & FIXED_IFMEDIA)
5864 		return;
5865 
5866 	/*
5867 	 * Rebuild the ifmedia list.
5868 	 */
5869 	ifm = &pi->media;
5870 	ifmedia_removeall(ifm);
5871 	lc = &pi->link_cfg;
5872 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5873 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5874 		MPASS(ss != 0);
5875 no_media:
5876 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5877 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5878 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5879 		return;
5880 	}
5881 
5882 	unknown = 0;
5883 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5884 		speed = 1 << bit;
5885 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5886 		if (ss & speed) {
5887 			mword = port_mword(pi, speed);
5888 			if (mword == IFM_NONE) {
5889 				goto no_media;
5890 			} else if (mword == IFM_UNKNOWN)
5891 				unknown++;
5892 			else
5893 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5894 		}
5895 	}
5896 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5897 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5898 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5899 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5900 
5901 	set_current_media(pi);
5902 }
5903 
5904 /*
5905  * Initialize the requested fields in the link config based on driver tunables.
5906  */
5907 static void
5908 init_link_config(struct port_info *pi)
5909 {
5910 	struct link_config *lc = &pi->link_cfg;
5911 
5912 	PORT_LOCK_ASSERT_OWNED(pi);
5913 
5914 	lc->requested_caps = 0;
5915 	lc->requested_speed = 0;
5916 
5917 	if (t4_autoneg == 0)
5918 		lc->requested_aneg = AUTONEG_DISABLE;
5919 	else if (t4_autoneg == 1)
5920 		lc->requested_aneg = AUTONEG_ENABLE;
5921 	else
5922 		lc->requested_aneg = AUTONEG_AUTO;
5923 
5924 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5925 	    PAUSE_AUTONEG);
5926 
5927 	if (t4_fec & FEC_AUTO)
5928 		lc->requested_fec = FEC_AUTO;
5929 	else if (t4_fec == 0)
5930 		lc->requested_fec = FEC_NONE;
5931 	else {
5932 		/* -1 is handled by the FEC_AUTO block above and not here. */
5933 		lc->requested_fec = t4_fec &
5934 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5935 		if (lc->requested_fec == 0)
5936 			lc->requested_fec = FEC_AUTO;
5937 	}
5938 	if (t4_force_fec < 0)
5939 		lc->force_fec = -1;
5940 	else if (t4_force_fec > 0)
5941 		lc->force_fec = 1;
5942 	else
5943 		lc->force_fec = 0;
5944 }
5945 
5946 /*
5947  * Makes sure that all requested settings comply with what's supported by the
5948  * port.  Returns the number of settings that were invalid and had to be fixed.
5949  */
5950 static int
5951 fixup_link_config(struct port_info *pi)
5952 {
5953 	int n = 0;
5954 	struct link_config *lc = &pi->link_cfg;
5955 	uint32_t fwspeed;
5956 
5957 	PORT_LOCK_ASSERT_OWNED(pi);
5958 
5959 	/* Speed (when not autonegotiating) */
5960 	if (lc->requested_speed != 0) {
5961 		fwspeed = speed_to_fwcap(lc->requested_speed);
5962 		if ((fwspeed & lc->pcaps) == 0) {
5963 			n++;
5964 			lc->requested_speed = 0;
5965 		}
5966 	}
5967 
5968 	/* Link autonegotiation */
5969 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5970 	    lc->requested_aneg == AUTONEG_DISABLE ||
5971 	    lc->requested_aneg == AUTONEG_AUTO);
5972 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5973 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5974 		n++;
5975 		lc->requested_aneg = AUTONEG_AUTO;
5976 	}
5977 
5978 	/* Flow control */
5979 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5980 	if (lc->requested_fc & PAUSE_TX &&
5981 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5982 		n++;
5983 		lc->requested_fc &= ~PAUSE_TX;
5984 	}
5985 	if (lc->requested_fc & PAUSE_RX &&
5986 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5987 		n++;
5988 		lc->requested_fc &= ~PAUSE_RX;
5989 	}
5990 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5991 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5992 		n++;
5993 		lc->requested_fc |= PAUSE_AUTONEG;
5994 	}
5995 
5996 	/* FEC */
5997 	if ((lc->requested_fec & FEC_RS &&
5998 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5999 	    (lc->requested_fec & FEC_BASER_RS &&
6000 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6001 		n++;
6002 		lc->requested_fec = FEC_AUTO;
6003 	}
6004 
6005 	return (n);
6006 }
6007 
6008 /*
6009  * Apply the requested L1 settings, which are expected to be valid, to the
6010  * hardware.
6011  */
6012 static int
6013 apply_link_config(struct port_info *pi)
6014 {
6015 	struct adapter *sc = pi->adapter;
6016 	struct link_config *lc = &pi->link_cfg;
6017 	int rc;
6018 
6019 #ifdef INVARIANTS
6020 	ASSERT_SYNCHRONIZED_OP(sc);
6021 	PORT_LOCK_ASSERT_OWNED(pi);
6022 
6023 	if (lc->requested_aneg == AUTONEG_ENABLE)
6024 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6025 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6026 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6027 	if (lc->requested_fc & PAUSE_TX)
6028 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6029 	if (lc->requested_fc & PAUSE_RX)
6030 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6031 	if (lc->requested_fec & FEC_RS)
6032 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6033 	if (lc->requested_fec & FEC_BASER_RS)
6034 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6035 #endif
6036 	if (!(sc->flags & IS_VF)) {
6037 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6038 		if (rc != 0) {
6039 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6040 			return (rc);
6041 		}
6042 	}
6043 
6044 	/*
6045 	 * An L1_CFG will almost always result in a link-change event if the
6046 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6047 	 * the notification is processed.  If the link is down then the actual
6048 	 * settings are meaningless.
6049 	 *
6050 	 * This takes care of the case where a change in the L1 settings may not
6051 	 * result in a notification.
6052 	 */
6053 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6054 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6055 
6056 	return (0);
6057 }
6058 
6059 #define FW_MAC_EXACT_CHUNK	7
6060 struct mcaddr_ctx {
6061 	if_t ifp;
6062 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6063 	uint64_t hash;
6064 	int i;
6065 	int del;
6066 	int rc;
6067 };
6068 
6069 static u_int
6070 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6071 {
6072 	struct mcaddr_ctx *ctx = arg;
6073 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6074 	struct port_info *pi = vi->pi;
6075 	struct adapter *sc = pi->adapter;
6076 
6077 	if (ctx->rc < 0)
6078 		return (0);
6079 
6080 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6081 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6082 	ctx->i++;
6083 
6084 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6085 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6086 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6087 		if (ctx->rc < 0) {
6088 			int j;
6089 
6090 			for (j = 0; j < ctx->i; j++) {
6091 				if_printf(ctx->ifp,
6092 				    "failed to add mc address"
6093 				    " %02x:%02x:%02x:"
6094 				    "%02x:%02x:%02x rc=%d\n",
6095 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6096 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6097 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6098 				    -ctx->rc);
6099 			}
6100 			return (0);
6101 		}
6102 		ctx->del = 0;
6103 		ctx->i = 0;
6104 	}
6105 
6106 	return (1);
6107 }
6108 
6109 /*
6110  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6111  * indicates which parameters should be programmed (the rest are left alone).
6112  */
6113 int
6114 update_mac_settings(if_t ifp, int flags)
6115 {
6116 	int rc = 0;
6117 	struct vi_info *vi = if_getsoftc(ifp);
6118 	struct port_info *pi = vi->pi;
6119 	struct adapter *sc = pi->adapter;
6120 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6121 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6122 
6123 	ASSERT_SYNCHRONIZED_OP(sc);
6124 	KASSERT(flags, ("%s: not told what to update.", __func__));
6125 
6126 	if (flags & XGMAC_MTU)
6127 		mtu = if_getmtu(ifp);
6128 
6129 	if (flags & XGMAC_PROMISC)
6130 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6131 
6132 	if (flags & XGMAC_ALLMULTI)
6133 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6134 
6135 	if (flags & XGMAC_VLANEX)
6136 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6137 
6138 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6139 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6140 		    allmulti, 1, vlanex, false);
6141 		if (rc) {
6142 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6143 			    rc);
6144 			return (rc);
6145 		}
6146 	}
6147 
6148 	if (flags & XGMAC_UCADDR) {
6149 		uint8_t ucaddr[ETHER_ADDR_LEN];
6150 
6151 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6152 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6153 		    ucaddr, true, &vi->smt_idx);
6154 		if (rc < 0) {
6155 			rc = -rc;
6156 			if_printf(ifp, "change_mac failed: %d\n", rc);
6157 			return (rc);
6158 		} else {
6159 			vi->xact_addr_filt = rc;
6160 			rc = 0;
6161 		}
6162 	}
6163 
6164 	if (flags & XGMAC_MCADDRS) {
6165 		struct epoch_tracker et;
6166 		struct mcaddr_ctx ctx;
6167 		int j;
6168 
6169 		ctx.ifp = ifp;
6170 		ctx.hash = 0;
6171 		ctx.i = 0;
6172 		ctx.del = 1;
6173 		ctx.rc = 0;
6174 		/*
6175 		 * Unlike other drivers, we accumulate list of pointers into
6176 		 * interface address lists and we need to keep it safe even
6177 		 * after if_foreach_llmaddr() returns, thus we must enter the
6178 		 * network epoch.
6179 		 */
6180 		NET_EPOCH_ENTER(et);
6181 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6182 		if (ctx.rc < 0) {
6183 			NET_EPOCH_EXIT(et);
6184 			rc = -ctx.rc;
6185 			return (rc);
6186 		}
6187 		if (ctx.i > 0) {
6188 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6189 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6190 			NET_EPOCH_EXIT(et);
6191 			if (rc < 0) {
6192 				rc = -rc;
6193 				for (j = 0; j < ctx.i; j++) {
6194 					if_printf(ifp,
6195 					    "failed to add mcast address"
6196 					    " %02x:%02x:%02x:"
6197 					    "%02x:%02x:%02x rc=%d\n",
6198 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6199 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6200 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6201 					    rc);
6202 				}
6203 				return (rc);
6204 			}
6205 			ctx.del = 0;
6206 		} else
6207 			NET_EPOCH_EXIT(et);
6208 
6209 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6210 		if (rc != 0)
6211 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6212 			    rc);
6213 		if (ctx.del == 0) {
6214 			/* We clobbered the VXLAN entry if there was one. */
6215 			pi->vxlan_tcam_entry = false;
6216 		}
6217 	}
6218 
6219 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6220 	    pi->vxlan_tcam_entry == false) {
6221 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6222 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6223 		    true);
6224 		if (rc < 0) {
6225 			rc = -rc;
6226 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6227 			    rc);
6228 		} else {
6229 			MPASS(rc == sc->rawf_base + pi->port_id);
6230 			rc = 0;
6231 			pi->vxlan_tcam_entry = true;
6232 		}
6233 	}
6234 
6235 	return (rc);
6236 }
6237 
6238 /*
6239  * {begin|end}_synchronized_op must be called from the same thread.
6240  */
6241 int
6242 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6243     char *wmesg)
6244 {
6245 	int rc, pri;
6246 
6247 #ifdef WITNESS
6248 	/* the caller thinks it's ok to sleep, but is it really? */
6249 	if (flags & SLEEP_OK)
6250 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6251 		    "begin_synchronized_op");
6252 #endif
6253 
6254 	if (INTR_OK)
6255 		pri = PCATCH;
6256 	else
6257 		pri = 0;
6258 
6259 	ADAPTER_LOCK(sc);
6260 	for (;;) {
6261 
6262 		if (vi && IS_DETACHING(vi)) {
6263 			rc = ENXIO;
6264 			goto done;
6265 		}
6266 
6267 		if (!IS_BUSY(sc)) {
6268 			rc = 0;
6269 			break;
6270 		}
6271 
6272 		if (!(flags & SLEEP_OK)) {
6273 			rc = EBUSY;
6274 			goto done;
6275 		}
6276 
6277 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6278 			rc = EINTR;
6279 			goto done;
6280 		}
6281 	}
6282 
6283 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6284 	SET_BUSY(sc);
6285 #ifdef INVARIANTS
6286 	sc->last_op = wmesg;
6287 	sc->last_op_thr = curthread;
6288 	sc->last_op_flags = flags;
6289 #endif
6290 
6291 done:
6292 	if (!(flags & HOLD_LOCK) || rc)
6293 		ADAPTER_UNLOCK(sc);
6294 
6295 	return (rc);
6296 }
6297 
6298 /*
6299  * Tell if_ioctl and if_init that the VI is going away.  This is
6300  * special variant of begin_synchronized_op and must be paired with a
6301  * call to end_vi_detach.
6302  */
6303 void
6304 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6305 {
6306 	ADAPTER_LOCK(sc);
6307 	SET_DETACHING(vi);
6308 	wakeup(&sc->flags);
6309 	while (IS_BUSY(sc))
6310 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6311 	SET_BUSY(sc);
6312 #ifdef INVARIANTS
6313 	sc->last_op = "t4detach";
6314 	sc->last_op_thr = curthread;
6315 	sc->last_op_flags = 0;
6316 #endif
6317 	ADAPTER_UNLOCK(sc);
6318 }
6319 
6320 void
6321 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6322 {
6323 	ADAPTER_LOCK(sc);
6324 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6325 	CLR_BUSY(sc);
6326 	CLR_DETACHING(vi);
6327 	wakeup(&sc->flags);
6328 	ADAPTER_UNLOCK(sc);
6329 }
6330 
6331 /*
6332  * {begin|end}_synchronized_op must be called from the same thread.
6333  */
6334 void
6335 end_synchronized_op(struct adapter *sc, int flags)
6336 {
6337 
6338 	if (flags & LOCK_HELD)
6339 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6340 	else
6341 		ADAPTER_LOCK(sc);
6342 
6343 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6344 	CLR_BUSY(sc);
6345 	wakeup(&sc->flags);
6346 	ADAPTER_UNLOCK(sc);
6347 }
6348 
6349 static int
6350 cxgbe_init_synchronized(struct vi_info *vi)
6351 {
6352 	struct port_info *pi = vi->pi;
6353 	struct adapter *sc = pi->adapter;
6354 	if_t ifp = vi->ifp;
6355 	int rc = 0, i;
6356 	struct sge_txq *txq;
6357 
6358 	ASSERT_SYNCHRONIZED_OP(sc);
6359 
6360 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6361 		return (0);	/* already running */
6362 
6363 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6364 		return (rc);	/* error message displayed already */
6365 
6366 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6367 		return (rc); /* error message displayed already */
6368 
6369 	rc = update_mac_settings(ifp, XGMAC_ALL);
6370 	if (rc)
6371 		goto done;	/* error message displayed already */
6372 
6373 	PORT_LOCK(pi);
6374 	if (pi->up_vis == 0) {
6375 		t4_update_port_info(pi);
6376 		fixup_link_config(pi);
6377 		build_medialist(pi);
6378 		apply_link_config(pi);
6379 	}
6380 
6381 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6382 	if (rc != 0) {
6383 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6384 		PORT_UNLOCK(pi);
6385 		goto done;
6386 	}
6387 
6388 	/*
6389 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6390 	 * if this changes.
6391 	 */
6392 
6393 	for_each_txq(vi, i, txq) {
6394 		TXQ_LOCK(txq);
6395 		txq->eq.flags |= EQ_ENABLED;
6396 		TXQ_UNLOCK(txq);
6397 	}
6398 
6399 	/*
6400 	 * The first iq of the first port to come up is used for tracing.
6401 	 */
6402 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6403 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6404 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6405 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6406 		    V_QUEUENUMBER(sc->traceq));
6407 		pi->flags |= HAS_TRACEQ;
6408 	}
6409 
6410 	/* all ok */
6411 	pi->up_vis++;
6412 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6413 	if (pi->link_cfg.link_ok)
6414 		t4_os_link_changed(pi);
6415 	PORT_UNLOCK(pi);
6416 
6417 	mtx_lock(&vi->tick_mtx);
6418 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6419 		callout_reset(&vi->tick, hz, vi_tick, vi);
6420 	else
6421 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6422 	mtx_unlock(&vi->tick_mtx);
6423 done:
6424 	if (rc != 0)
6425 		cxgbe_uninit_synchronized(vi);
6426 
6427 	return (rc);
6428 }
6429 
6430 /*
6431  * Idempotent.
6432  */
6433 static int
6434 cxgbe_uninit_synchronized(struct vi_info *vi)
6435 {
6436 	struct port_info *pi = vi->pi;
6437 	struct adapter *sc = pi->adapter;
6438 	if_t ifp = vi->ifp;
6439 	int rc, i;
6440 	struct sge_txq *txq;
6441 
6442 	ASSERT_SYNCHRONIZED_OP(sc);
6443 
6444 	if (!(vi->flags & VI_INIT_DONE)) {
6445 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6446 			KASSERT(0, ("uninited VI is running"));
6447 			if_printf(ifp, "uninited VI with running ifnet.  "
6448 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6449 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6450 			    if_getdrvflags(ifp));
6451 		}
6452 		return (0);
6453 	}
6454 
6455 	/*
6456 	 * Disable the VI so that all its data in either direction is discarded
6457 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6458 	 * tick) intact as the TP can deliver negative advice or data that it's
6459 	 * holding in its RAM (for an offloaded connection) even after the VI is
6460 	 * disabled.
6461 	 */
6462 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6463 	if (rc) {
6464 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6465 		return (rc);
6466 	}
6467 
6468 	for_each_txq(vi, i, txq) {
6469 		TXQ_LOCK(txq);
6470 		txq->eq.flags &= ~EQ_ENABLED;
6471 		TXQ_UNLOCK(txq);
6472 	}
6473 
6474 	mtx_lock(&vi->tick_mtx);
6475 	callout_stop(&vi->tick);
6476 	mtx_unlock(&vi->tick_mtx);
6477 
6478 	PORT_LOCK(pi);
6479 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6480 		PORT_UNLOCK(pi);
6481 		return (0);
6482 	}
6483 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6484 	pi->up_vis--;
6485 	if (pi->up_vis > 0) {
6486 		PORT_UNLOCK(pi);
6487 		return (0);
6488 	}
6489 
6490 	pi->link_cfg.link_ok = false;
6491 	pi->link_cfg.speed = 0;
6492 	pi->link_cfg.link_down_rc = 255;
6493 	t4_os_link_changed(pi);
6494 	PORT_UNLOCK(pi);
6495 
6496 	return (0);
6497 }
6498 
6499 /*
6500  * It is ok for this function to fail midway and return right away.  t4_detach
6501  * will walk the entire sc->irq list and clean up whatever is valid.
6502  */
6503 int
6504 t4_setup_intr_handlers(struct adapter *sc)
6505 {
6506 	int rc, rid, p, q, v;
6507 	char s[8];
6508 	struct irq *irq;
6509 	struct port_info *pi;
6510 	struct vi_info *vi;
6511 	struct sge *sge = &sc->sge;
6512 	struct sge_rxq *rxq;
6513 #ifdef TCP_OFFLOAD
6514 	struct sge_ofld_rxq *ofld_rxq;
6515 #endif
6516 #ifdef DEV_NETMAP
6517 	struct sge_nm_rxq *nm_rxq;
6518 #endif
6519 #ifdef RSS
6520 	int nbuckets = rss_getnumbuckets();
6521 #endif
6522 
6523 	/*
6524 	 * Setup interrupts.
6525 	 */
6526 	irq = &sc->irq[0];
6527 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6528 	if (forwarding_intr_to_fwq(sc))
6529 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6530 
6531 	/* Multiple interrupts. */
6532 	if (sc->flags & IS_VF)
6533 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6534 		    ("%s: too few intr.", __func__));
6535 	else
6536 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6537 		    ("%s: too few intr.", __func__));
6538 
6539 	/* The first one is always error intr on PFs */
6540 	if (!(sc->flags & IS_VF)) {
6541 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6542 		if (rc != 0)
6543 			return (rc);
6544 		irq++;
6545 		rid++;
6546 	}
6547 
6548 	/* The second one is always the firmware event queue (first on VFs) */
6549 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6550 	if (rc != 0)
6551 		return (rc);
6552 	irq++;
6553 	rid++;
6554 
6555 	for_each_port(sc, p) {
6556 		pi = sc->port[p];
6557 		for_each_vi(pi, v, vi) {
6558 			vi->first_intr = rid - 1;
6559 
6560 			if (vi->nnmrxq > 0) {
6561 				int n = max(vi->nrxq, vi->nnmrxq);
6562 
6563 				rxq = &sge->rxq[vi->first_rxq];
6564 #ifdef DEV_NETMAP
6565 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6566 #endif
6567 				for (q = 0; q < n; q++) {
6568 					snprintf(s, sizeof(s), "%x%c%x", p,
6569 					    'a' + v, q);
6570 					if (q < vi->nrxq)
6571 						irq->rxq = rxq++;
6572 #ifdef DEV_NETMAP
6573 					if (q < vi->nnmrxq)
6574 						irq->nm_rxq = nm_rxq++;
6575 
6576 					if (irq->nm_rxq != NULL &&
6577 					    irq->rxq == NULL) {
6578 						/* Netmap rx only */
6579 						rc = t4_alloc_irq(sc, irq, rid,
6580 						    t4_nm_intr, irq->nm_rxq, s);
6581 					}
6582 					if (irq->nm_rxq != NULL &&
6583 					    irq->rxq != NULL) {
6584 						/* NIC and Netmap rx */
6585 						rc = t4_alloc_irq(sc, irq, rid,
6586 						    t4_vi_intr, irq, s);
6587 					}
6588 #endif
6589 					if (irq->rxq != NULL &&
6590 					    irq->nm_rxq == NULL) {
6591 						/* NIC rx only */
6592 						rc = t4_alloc_irq(sc, irq, rid,
6593 						    t4_intr, irq->rxq, s);
6594 					}
6595 					if (rc != 0)
6596 						return (rc);
6597 #ifdef RSS
6598 					if (q < vi->nrxq) {
6599 						bus_bind_intr(sc->dev, irq->res,
6600 						    rss_getcpu(q % nbuckets));
6601 					}
6602 #endif
6603 					irq++;
6604 					rid++;
6605 					vi->nintr++;
6606 				}
6607 			} else {
6608 				for_each_rxq(vi, q, rxq) {
6609 					snprintf(s, sizeof(s), "%x%c%x", p,
6610 					    'a' + v, q);
6611 					rc = t4_alloc_irq(sc, irq, rid,
6612 					    t4_intr, rxq, s);
6613 					if (rc != 0)
6614 						return (rc);
6615 #ifdef RSS
6616 					bus_bind_intr(sc->dev, irq->res,
6617 					    rss_getcpu(q % nbuckets));
6618 #endif
6619 					irq++;
6620 					rid++;
6621 					vi->nintr++;
6622 				}
6623 			}
6624 #ifdef TCP_OFFLOAD
6625 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6626 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6627 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6628 				    ofld_rxq, s);
6629 				if (rc != 0)
6630 					return (rc);
6631 				irq++;
6632 				rid++;
6633 				vi->nintr++;
6634 			}
6635 #endif
6636 		}
6637 	}
6638 	MPASS(irq == &sc->irq[sc->intr_count]);
6639 
6640 	return (0);
6641 }
6642 
6643 static void
6644 write_global_rss_key(struct adapter *sc)
6645 {
6646 #ifdef RSS
6647 	int i;
6648 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6649 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6650 
6651 	CTASSERT(RSS_KEYSIZE == 40);
6652 
6653 	rss_getkey((void *)&raw_rss_key[0]);
6654 	for (i = 0; i < nitems(rss_key); i++) {
6655 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6656 	}
6657 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6658 #endif
6659 }
6660 
6661 /*
6662  * Idempotent.
6663  */
6664 static int
6665 adapter_full_init(struct adapter *sc)
6666 {
6667 	int rc, i;
6668 
6669 	ASSERT_SYNCHRONIZED_OP(sc);
6670 
6671 	/*
6672 	 * queues that belong to the adapter (not any particular port).
6673 	 */
6674 	rc = t4_setup_adapter_queues(sc);
6675 	if (rc != 0)
6676 		return (rc);
6677 
6678 	MPASS(sc->params.nports <= nitems(sc->tq));
6679 	for (i = 0; i < sc->params.nports; i++) {
6680 		if (sc->tq[i] != NULL)
6681 			continue;
6682 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6683 		    taskqueue_thread_enqueue, &sc->tq[i]);
6684 		if (sc->tq[i] == NULL) {
6685 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6686 			return (ENOMEM);
6687 		}
6688 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6689 		    device_get_nameunit(sc->dev), i);
6690 	}
6691 
6692 	if (!(sc->flags & IS_VF)) {
6693 		write_global_rss_key(sc);
6694 		t4_intr_enable(sc);
6695 	}
6696 	return (0);
6697 }
6698 
6699 int
6700 adapter_init(struct adapter *sc)
6701 {
6702 	int rc;
6703 
6704 	ASSERT_SYNCHRONIZED_OP(sc);
6705 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6706 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6707 	    ("%s: FULL_INIT_DONE already", __func__));
6708 
6709 	rc = adapter_full_init(sc);
6710 	if (rc != 0)
6711 		adapter_full_uninit(sc);
6712 	else
6713 		sc->flags |= FULL_INIT_DONE;
6714 
6715 	return (rc);
6716 }
6717 
6718 /*
6719  * Idempotent.
6720  */
6721 static void
6722 adapter_full_uninit(struct adapter *sc)
6723 {
6724 	int i;
6725 
6726 	t4_teardown_adapter_queues(sc);
6727 
6728 	for (i = 0; i < nitems(sc->tq); i++) {
6729 		if (sc->tq[i] == NULL)
6730 			continue;
6731 		taskqueue_free(sc->tq[i]);
6732 		sc->tq[i] = NULL;
6733 	}
6734 
6735 	sc->flags &= ~FULL_INIT_DONE;
6736 }
6737 
6738 #ifdef RSS
6739 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6740     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6741     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6742     RSS_HASHTYPE_RSS_UDP_IPV6)
6743 
6744 /* Translates kernel hash types to hardware. */
6745 static int
6746 hashconfig_to_hashen(int hashconfig)
6747 {
6748 	int hashen = 0;
6749 
6750 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6751 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6752 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6753 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6754 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6755 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6756 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6757 	}
6758 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6759 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6760 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6761 	}
6762 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6763 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6764 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6765 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6766 
6767 	return (hashen);
6768 }
6769 
6770 /* Translates hardware hash types to kernel. */
6771 static int
6772 hashen_to_hashconfig(int hashen)
6773 {
6774 	int hashconfig = 0;
6775 
6776 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6777 		/*
6778 		 * If UDP hashing was enabled it must have been enabled for
6779 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6780 		 * enabling any 4-tuple hash is nonsense configuration.
6781 		 */
6782 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6783 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6784 
6785 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6786 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6787 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6788 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6789 	}
6790 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6791 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6792 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6793 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6794 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6795 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6796 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6797 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6798 
6799 	return (hashconfig);
6800 }
6801 #endif
6802 
6803 /*
6804  * Idempotent.
6805  */
6806 static int
6807 vi_full_init(struct vi_info *vi)
6808 {
6809 	struct adapter *sc = vi->adapter;
6810 	struct sge_rxq *rxq;
6811 	int rc, i, j;
6812 #ifdef RSS
6813 	int nbuckets = rss_getnumbuckets();
6814 	int hashconfig = rss_gethashconfig();
6815 	int extra;
6816 #endif
6817 
6818 	ASSERT_SYNCHRONIZED_OP(sc);
6819 
6820 	/*
6821 	 * Allocate tx/rx/fl queues for this VI.
6822 	 */
6823 	rc = t4_setup_vi_queues(vi);
6824 	if (rc != 0)
6825 		return (rc);
6826 
6827 	/*
6828 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6829 	 */
6830 	if (vi->nrxq > vi->rss_size) {
6831 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6832 		    "some queues will never receive traffic.\n", vi->nrxq,
6833 		    vi->rss_size);
6834 	} else if (vi->rss_size % vi->nrxq) {
6835 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6836 		    "expect uneven traffic distribution.\n", vi->nrxq,
6837 		    vi->rss_size);
6838 	}
6839 #ifdef RSS
6840 	if (vi->nrxq != nbuckets) {
6841 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6842 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6843 	}
6844 #endif
6845 	if (vi->rss == NULL)
6846 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6847 		    M_ZERO | M_WAITOK);
6848 	for (i = 0; i < vi->rss_size;) {
6849 #ifdef RSS
6850 		j = rss_get_indirection_to_bucket(i);
6851 		j %= vi->nrxq;
6852 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6853 		vi->rss[i++] = rxq->iq.abs_id;
6854 #else
6855 		for_each_rxq(vi, j, rxq) {
6856 			vi->rss[i++] = rxq->iq.abs_id;
6857 			if (i == vi->rss_size)
6858 				break;
6859 		}
6860 #endif
6861 	}
6862 
6863 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6864 	    vi->rss, vi->rss_size);
6865 	if (rc != 0) {
6866 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6867 		return (rc);
6868 	}
6869 
6870 #ifdef RSS
6871 	vi->hashen = hashconfig_to_hashen(hashconfig);
6872 
6873 	/*
6874 	 * We may have had to enable some hashes even though the global config
6875 	 * wants them disabled.  This is a potential problem that must be
6876 	 * reported to the user.
6877 	 */
6878 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6879 
6880 	/*
6881 	 * If we consider only the supported hash types, then the enabled hashes
6882 	 * are a superset of the requested hashes.  In other words, there cannot
6883 	 * be any supported hash that was requested but not enabled, but there
6884 	 * can be hashes that were not requested but had to be enabled.
6885 	 */
6886 	extra &= SUPPORTED_RSS_HASHTYPES;
6887 	MPASS((extra & hashconfig) == 0);
6888 
6889 	if (extra) {
6890 		CH_ALERT(vi,
6891 		    "global RSS config (0x%x) cannot be accommodated.\n",
6892 		    hashconfig);
6893 	}
6894 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6895 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6896 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6897 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6898 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6899 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6900 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6901 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6902 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6903 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6904 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6905 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6906 #else
6907 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6908 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6909 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6910 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6911 #endif
6912 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6913 	    0, 0);
6914 	if (rc != 0) {
6915 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6916 		return (rc);
6917 	}
6918 
6919 	return (0);
6920 }
6921 
6922 int
6923 vi_init(struct vi_info *vi)
6924 {
6925 	int rc;
6926 
6927 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6928 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6929 	    ("%s: VI_INIT_DONE already", __func__));
6930 
6931 	rc = vi_full_init(vi);
6932 	if (rc != 0)
6933 		vi_full_uninit(vi);
6934 	else
6935 		vi->flags |= VI_INIT_DONE;
6936 
6937 	return (rc);
6938 }
6939 
6940 /*
6941  * Idempotent.
6942  */
6943 static void
6944 vi_full_uninit(struct vi_info *vi)
6945 {
6946 
6947 	if (vi->flags & VI_INIT_DONE) {
6948 		quiesce_vi(vi);
6949 		free(vi->rss, M_CXGBE);
6950 		free(vi->nm_rss, M_CXGBE);
6951 	}
6952 
6953 	t4_teardown_vi_queues(vi);
6954 	vi->flags &= ~VI_INIT_DONE;
6955 }
6956 
6957 static void
6958 quiesce_txq(struct sge_txq *txq)
6959 {
6960 	struct sge_eq *eq = &txq->eq;
6961 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6962 
6963 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6964 	MPASS(!(eq->flags & EQ_ENABLED));
6965 
6966 	/* Wait for the mp_ring to empty. */
6967 	while (!mp_ring_is_idle(txq->r)) {
6968 		mp_ring_check_drainage(txq->r, 4096);
6969 		pause("rquiesce", 1);
6970 	}
6971 	MPASS(txq->txp.npkt == 0);
6972 
6973 	if (eq->flags & EQ_HW_ALLOCATED) {
6974 		/*
6975 		 * Hardware is alive and working normally.  Wait for it to
6976 		 * finish and then wait for the driver to catch up and reclaim
6977 		 * all descriptors.
6978 		 */
6979 		while (spg->cidx != htobe16(eq->pidx))
6980 			pause("equiesce", 1);
6981 		while (eq->cidx != eq->pidx)
6982 			pause("dquiesce", 1);
6983 	} else {
6984 		/*
6985 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6986 		 * descriptors directly.
6987 		 */
6988 		TXQ_LOCK(txq);
6989 		while (eq->cidx != eq->pidx) {
6990 			struct mbuf *m, *nextpkt;
6991 			struct tx_sdesc *txsd;
6992 
6993 			txsd = &txq->sdesc[eq->cidx];
6994 			for (m = txsd->m; m != NULL; m = nextpkt) {
6995 				nextpkt = m->m_nextpkt;
6996 				m->m_nextpkt = NULL;
6997 				m_freem(m);
6998 			}
6999 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7000 		}
7001 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7002 		TXQ_UNLOCK(txq);
7003 	}
7004 }
7005 
7006 static void
7007 quiesce_wrq(struct sge_wrq *wrq)
7008 {
7009 
7010 	/* XXXTX */
7011 }
7012 
7013 static void
7014 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7015 {
7016 	/* Synchronize with the interrupt handler */
7017 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7018 		pause("iqfree", 1);
7019 
7020 	if (fl != NULL) {
7021 		MPASS(iq->flags & IQ_HAS_FL);
7022 
7023 		mtx_lock(&sc->sfl_lock);
7024 		FL_LOCK(fl);
7025 		fl->flags |= FL_DOOMED;
7026 		FL_UNLOCK(fl);
7027 		callout_stop(&sc->sfl_callout);
7028 		mtx_unlock(&sc->sfl_lock);
7029 
7030 		KASSERT((fl->flags & FL_STARVING) == 0,
7031 		    ("%s: still starving", __func__));
7032 
7033 		/* Release all buffers if hardware is no longer available. */
7034 		if (!(iq->flags & IQ_HW_ALLOCATED))
7035 			free_fl_buffers(sc, fl);
7036 	}
7037 }
7038 
7039 /*
7040  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7041  * that no new work is being enqueued by the hardware or the driver.  That part
7042  * should be arranged before calling this function.
7043  */
7044 static void
7045 quiesce_vi(struct vi_info *vi)
7046 {
7047 	int i;
7048 	struct adapter *sc = vi->adapter;
7049 	struct sge_rxq *rxq;
7050 	struct sge_txq *txq;
7051 #ifdef TCP_OFFLOAD
7052 	struct sge_ofld_rxq *ofld_rxq;
7053 #endif
7054 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7055 	struct sge_ofld_txq *ofld_txq;
7056 #endif
7057 
7058 	if (!(vi->flags & VI_INIT_DONE))
7059 		return;
7060 
7061 	for_each_txq(vi, i, txq) {
7062 		quiesce_txq(txq);
7063 	}
7064 
7065 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7066 	for_each_ofld_txq(vi, i, ofld_txq) {
7067 		quiesce_wrq(&ofld_txq->wrq);
7068 	}
7069 #endif
7070 
7071 	for_each_rxq(vi, i, rxq) {
7072 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7073 	}
7074 
7075 #ifdef TCP_OFFLOAD
7076 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7077 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7078 	}
7079 #endif
7080 }
7081 
7082 static int
7083 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7084     driver_intr_t *handler, void *arg, char *name)
7085 {
7086 	int rc;
7087 
7088 	irq->rid = rid;
7089 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7090 	    RF_SHAREABLE | RF_ACTIVE);
7091 	if (irq->res == NULL) {
7092 		device_printf(sc->dev,
7093 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7094 		return (ENOMEM);
7095 	}
7096 
7097 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7098 	    NULL, handler, arg, &irq->tag);
7099 	if (rc != 0) {
7100 		device_printf(sc->dev,
7101 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7102 		    rid, name, rc);
7103 	} else if (name)
7104 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7105 
7106 	return (rc);
7107 }
7108 
7109 static int
7110 t4_free_irq(struct adapter *sc, struct irq *irq)
7111 {
7112 	if (irq->tag)
7113 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7114 	if (irq->res)
7115 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7116 
7117 	bzero(irq, sizeof(*irq));
7118 
7119 	return (0);
7120 }
7121 
7122 static void
7123 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7124 {
7125 
7126 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7127 	t4_get_regs(sc, buf, regs->len);
7128 }
7129 
7130 #define	A_PL_INDIR_CMD	0x1f8
7131 
7132 #define	S_PL_AUTOINC	31
7133 #define	M_PL_AUTOINC	0x1U
7134 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7135 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7136 
7137 #define	S_PL_VFID	20
7138 #define	M_PL_VFID	0xffU
7139 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7140 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7141 
7142 #define	S_PL_ADDR	0
7143 #define	M_PL_ADDR	0xfffffU
7144 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7145 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7146 
7147 #define	A_PL_INDIR_DATA	0x1fc
7148 
7149 static uint64_t
7150 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7151 {
7152 	u32 stats[2];
7153 
7154 	if (sc->flags & IS_VF) {
7155 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7156 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7157 	} else {
7158 		mtx_assert(&sc->reg_lock, MA_OWNED);
7159 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7160 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7161 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7162 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7163 	}
7164 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7165 }
7166 
7167 static void
7168 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7169 {
7170 
7171 #define GET_STAT(name) \
7172 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7173 
7174 	if (!(sc->flags & IS_VF))
7175 		mtx_lock(&sc->reg_lock);
7176 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7177 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7178 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7179 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7180 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7181 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7182 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7183 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7184 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7185 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7186 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7187 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7188 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7189 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7190 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7191 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7192 	if (!(sc->flags & IS_VF))
7193 		mtx_unlock(&sc->reg_lock);
7194 
7195 #undef GET_STAT
7196 }
7197 
7198 static void
7199 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7200 {
7201 	int reg;
7202 
7203 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7204 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7205 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7206 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7207 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7208 }
7209 
7210 static void
7211 vi_refresh_stats(struct vi_info *vi)
7212 {
7213 	struct timeval tv;
7214 	const struct timeval interval = {0, 250000};	/* 250ms */
7215 
7216 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7217 
7218 	if (vi->flags & VI_SKIP_STATS)
7219 		return;
7220 
7221 	getmicrotime(&tv);
7222 	timevalsub(&tv, &interval);
7223 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7224 		return;
7225 
7226 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7227 	getmicrotime(&vi->last_refreshed);
7228 }
7229 
7230 static void
7231 cxgbe_refresh_stats(struct vi_info *vi)
7232 {
7233 	u_int i, v, tnl_cong_drops, chan_map;
7234 	struct timeval tv;
7235 	const struct timeval interval = {0, 250000};	/* 250ms */
7236 	struct port_info *pi;
7237 	struct adapter *sc;
7238 
7239 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7240 
7241 	if (vi->flags & VI_SKIP_STATS)
7242 		return;
7243 
7244 	getmicrotime(&tv);
7245 	timevalsub(&tv, &interval);
7246 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7247 		return;
7248 
7249 	pi = vi->pi;
7250 	sc = vi->adapter;
7251 	tnl_cong_drops = 0;
7252 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7253 	chan_map = pi->rx_e_chan_map;
7254 	while (chan_map) {
7255 		i = ffs(chan_map) - 1;
7256 		mtx_lock(&sc->reg_lock);
7257 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7258 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7259 		mtx_unlock(&sc->reg_lock);
7260 		tnl_cong_drops += v;
7261 		chan_map &= ~(1 << i);
7262 	}
7263 	pi->tnl_cong_drops = tnl_cong_drops;
7264 	getmicrotime(&vi->last_refreshed);
7265 }
7266 
7267 static void
7268 cxgbe_tick(void *arg)
7269 {
7270 	struct vi_info *vi = arg;
7271 
7272 	MPASS(IS_MAIN_VI(vi));
7273 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7274 
7275 	cxgbe_refresh_stats(vi);
7276 	callout_schedule(&vi->tick, hz);
7277 }
7278 
7279 static void
7280 vi_tick(void *arg)
7281 {
7282 	struct vi_info *vi = arg;
7283 
7284 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7285 
7286 	vi_refresh_stats(vi);
7287 	callout_schedule(&vi->tick, hz);
7288 }
7289 
7290 /*
7291  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7292  */
7293 static char *caps_decoder[] = {
7294 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7295 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7296 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7297 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7298 	    "\006HASHFILTER\007ETHOFLD",
7299 	"\20\001TOE",					/* 4: TOE */
7300 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7301 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7302 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7303 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7304 	    "\007T10DIF"
7305 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7306 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7307 	    "\004TLS_HW",
7308 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7309 		    "\004PO_INITIATOR\005PO_TARGET",
7310 };
7311 
7312 void
7313 t4_sysctls(struct adapter *sc)
7314 {
7315 	struct sysctl_ctx_list *ctx = &sc->ctx;
7316 	struct sysctl_oid *oid;
7317 	struct sysctl_oid_list *children, *c0;
7318 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7319 
7320 	/*
7321 	 * dev.t4nex.X.
7322 	 */
7323 	oid = device_get_sysctl_tree(sc->dev);
7324 	c0 = children = SYSCTL_CHILDREN(oid);
7325 
7326 	sc->sc_do_rxcopy = 1;
7327 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7328 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7329 
7330 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7331 	    sc->params.nports, "# of ports");
7332 
7333 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7334 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7335 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7336 	    "available doorbells");
7337 
7338 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7339 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7340 
7341 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7342 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7343 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7344 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7345 
7346 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7347 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7348 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7349 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7350 
7351 	t4_sge_sysctls(sc, ctx, children);
7352 
7353 	sc->lro_timeout = 100;
7354 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7355 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7356 
7357 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7358 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7359 
7360 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7361 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7362 
7363 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7364 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7365 
7366 	if (sc->flags & IS_VF)
7367 		return;
7368 
7369 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7370 	    NULL, chip_rev(sc), "chip hardware revision");
7371 
7372 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7373 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7374 
7375 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7376 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7377 
7378 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7379 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7380 
7381 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7382 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7383 
7384 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7385 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7386 
7387 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7388 	    sc->er_version, 0, "expansion ROM version");
7389 
7390 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7391 	    sc->bs_version, 0, "bootstrap firmware version");
7392 
7393 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7394 	    NULL, sc->params.scfg_vers, "serial config version");
7395 
7396 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7397 	    NULL, sc->params.vpd_vers, "VPD version");
7398 
7399 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7400 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7401 
7402 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7403 	    sc->cfcsum, "config file checksum");
7404 
7405 #define SYSCTL_CAP(name, n, text) \
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7408 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7409 	    "available " text " capabilities")
7410 
7411 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7412 	SYSCTL_CAP(linkcaps, 1, "link");
7413 	SYSCTL_CAP(switchcaps, 2, "switch");
7414 	SYSCTL_CAP(niccaps, 3, "NIC");
7415 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7416 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7417 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7418 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7419 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7420 #undef SYSCTL_CAP
7421 
7422 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7423 	    NULL, sc->tids.nftids, "number of filters");
7424 
7425 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7426 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7427 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7428 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7429 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7430 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7431 
7432 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7433 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7434 	    sysctl_loadavg, "A",
7435 	    "microprocessor load averages (debug firmwares only)");
7436 
7437 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7438 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7439 	    "I", "core Vdd (in mV)");
7440 
7441 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7442 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7443 	    sysctl_cpus, "A", "local CPUs");
7444 
7445 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7446 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7447 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7448 
7449 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7450 	    &sc->swintr, 0, "software triggered interrupts");
7451 
7452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7453 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7454 	    "1 = reset adapter, 0 = zero reset counter");
7455 
7456 	/*
7457 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7458 	 */
7459 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7460 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7461 	    "logs and miscellaneous information");
7462 	children = SYSCTL_CHILDREN(oid);
7463 
7464 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7465 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7466 	    sysctl_cctrl, "A", "congestion control");
7467 
7468 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7469 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7470 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7471 
7472 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7473 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7474 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7475 
7476 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7477 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7478 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7479 
7480 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7481 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7482 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7483 
7484 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7485 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7486 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7487 
7488 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7489 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7490 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7491 
7492 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7493 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7494 	    sysctl_cim_la, "A", "CIM logic analyzer");
7495 
7496 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7497 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7498 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7499 
7500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7501 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7502 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7503 
7504 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7505 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7506 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7507 
7508 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7509 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7510 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7511 
7512 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7513 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7514 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7515 
7516 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7517 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7518 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7519 
7520 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7521 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7522 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7523 
7524 	if (chip_id(sc) > CHELSIO_T4) {
7525 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7526 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7527 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7528 		    "CIM OBQ 6 (SGE0-RX)");
7529 
7530 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7531 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7532 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7533 		    "CIM OBQ 7 (SGE1-RX)");
7534 	}
7535 
7536 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7537 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7538 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7539 
7540 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7541 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7542 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7543 
7544 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7545 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7546 	    sysctl_cpl_stats, "A", "CPL statistics");
7547 
7548 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7549 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7550 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7551 
7552 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7553 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7554 	    sysctl_tid_stats, "A", "tid stats");
7555 
7556 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7557 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7558 	    sysctl_devlog, "A", "firmware's device log");
7559 
7560 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7561 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7562 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7563 
7564 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7565 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7566 	    sysctl_hw_sched, "A", "hardware scheduler ");
7567 
7568 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7569 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7570 	    sysctl_l2t, "A", "hardware L2 table");
7571 
7572 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7573 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7574 	    sysctl_smt, "A", "hardware source MAC table");
7575 
7576 #ifdef INET6
7577 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7578 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7579 	    sysctl_clip, "A", "active CLIP table entries");
7580 #endif
7581 
7582 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7583 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7584 	    sysctl_lb_stats, "A", "loopback statistics");
7585 
7586 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7587 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7588 	    sysctl_meminfo, "A", "memory regions");
7589 
7590 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7591 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7592 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7593 	    "A", "MPS TCAM entries");
7594 
7595 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7596 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7597 	    sysctl_path_mtus, "A", "path MTUs");
7598 
7599 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7600 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7601 	    sysctl_pm_stats, "A", "PM statistics");
7602 
7603 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7604 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7605 	    sysctl_rdma_stats, "A", "RDMA statistics");
7606 
7607 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7608 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7609 	    sysctl_tcp_stats, "A", "TCP statistics");
7610 
7611 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7612 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7613 	    sysctl_tids, "A", "TID information");
7614 
7615 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7616 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7617 	    sysctl_tp_err_stats, "A", "TP error statistics");
7618 
7619 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7620 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7621 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7622 
7623 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7624 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7625 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7626 
7627 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7628 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7629 	    sysctl_tp_la, "A", "TP logic analyzer");
7630 
7631 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7632 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7633 	    sysctl_tx_rate, "A", "Tx rate");
7634 
7635 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7636 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7637 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7638 
7639 	if (chip_id(sc) >= CHELSIO_T5) {
7640 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7641 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7642 		    sysctl_wcwr_stats, "A", "write combined work requests");
7643 	}
7644 
7645 #ifdef KERN_TLS
7646 	if (is_ktls(sc)) {
7647 		/*
7648 		 * dev.t4nex.0.tls.
7649 		 */
7650 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7651 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7652 		children = SYSCTL_CHILDREN(oid);
7653 
7654 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7655 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7656 		    "keys in work requests (1) or attempt to store TLS keys "
7657 		    "in card memory.");
7658 
7659 		if (is_t6(sc))
7660 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7661 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7662 			    "combine TCB field updates with TLS record work "
7663 			    "requests.");
7664 	}
7665 #endif
7666 
7667 #ifdef TCP_OFFLOAD
7668 	if (is_offload(sc)) {
7669 		int i;
7670 		char s[4];
7671 
7672 		/*
7673 		 * dev.t4nex.X.toe.
7674 		 */
7675 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7676 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7677 		children = SYSCTL_CHILDREN(oid);
7678 
7679 		sc->tt.cong_algorithm = -1;
7680 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7681 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7682 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7683 		    "3 = highspeed)");
7684 
7685 		sc->tt.sndbuf = -1;
7686 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7687 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7688 
7689 		sc->tt.ddp = 0;
7690 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7691 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7692 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7693 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7694 
7695 		sc->tt.rx_coalesce = -1;
7696 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7697 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7698 
7699 		sc->tt.tls = 0;
7700 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7701 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7702 		    "Inline TLS allowed");
7703 
7704 		sc->tt.tx_align = -1;
7705 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7706 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7707 
7708 		sc->tt.tx_zcopy = 0;
7709 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7710 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7711 		    "Enable zero-copy aio_write(2)");
7712 
7713 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7714 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7715 		    "cop_managed_offloading", CTLFLAG_RW,
7716 		    &sc->tt.cop_managed_offloading, 0,
7717 		    "COP (Connection Offload Policy) controls all TOE offload");
7718 
7719 		sc->tt.autorcvbuf_inc = 16 * 1024;
7720 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7721 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7722 		    "autorcvbuf increment");
7723 
7724 		sc->tt.update_hc_on_pmtu_change = 1;
7725 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7726 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7727 		    &sc->tt.update_hc_on_pmtu_change, 0,
7728 		    "Update hostcache entry if the PMTU changes");
7729 
7730 		sc->tt.iso = 1;
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7732 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7733 
7734 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7735 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7736 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7737 
7738 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7739 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7740 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7741 
7742 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7743 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7744 		    sysctl_tp_tick, "A", "DACK tick (us)");
7745 
7746 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7747 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7748 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7749 
7750 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7751 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7752 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7753 		    "Minimum retransmit interval (us)");
7754 
7755 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7756 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7757 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7758 		    "Maximum retransmit interval (us)");
7759 
7760 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7761 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7762 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7763 		    "Persist timer min (us)");
7764 
7765 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7766 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7767 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7768 		    "Persist timer max (us)");
7769 
7770 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7771 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7772 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7773 		    "Keepalive idle timer (us)");
7774 
7775 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7776 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7777 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7778 		    "Keepalive interval timer (us)");
7779 
7780 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7781 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7782 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7783 
7784 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7785 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7786 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7787 		    "FINWAIT2 timer (us)");
7788 
7789 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7790 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7791 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7792 		    "Number of SYN retransmissions before abort");
7793 
7794 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7795 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7796 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7797 		    "Number of retransmissions before abort");
7798 
7799 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7800 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7801 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7802 		    "Number of keepalive probes before abort");
7803 
7804 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7805 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7806 		    "TOE retransmit backoffs");
7807 		children = SYSCTL_CHILDREN(oid);
7808 		for (i = 0; i < 16; i++) {
7809 			snprintf(s, sizeof(s), "%u", i);
7810 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7811 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7812 			    i, sysctl_tp_backoff, "IU",
7813 			    "TOE retransmit backoff");
7814 		}
7815 	}
7816 #endif
7817 }
7818 
7819 void
7820 vi_sysctls(struct vi_info *vi)
7821 {
7822 	struct sysctl_ctx_list *ctx = &vi->ctx;
7823 	struct sysctl_oid *oid;
7824 	struct sysctl_oid_list *children;
7825 
7826 	/*
7827 	 * dev.v?(cxgbe|cxl).X.
7828 	 */
7829 	oid = device_get_sysctl_tree(vi->dev);
7830 	children = SYSCTL_CHILDREN(oid);
7831 
7832 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7833 	    vi->viid, "VI identifer");
7834 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7835 	    &vi->nrxq, 0, "# of rx queues");
7836 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7837 	    &vi->ntxq, 0, "# of tx queues");
7838 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7839 	    &vi->first_rxq, 0, "index of first rx queue");
7840 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7841 	    &vi->first_txq, 0, "index of first tx queue");
7842 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7843 	    vi->rss_base, "start of RSS indirection table");
7844 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7845 	    vi->rss_size, "size of RSS indirection table");
7846 
7847 	if (IS_MAIN_VI(vi)) {
7848 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7849 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7850 		    sysctl_noflowq, "IU",
7851 		    "Reserve queue 0 for non-flowid packets");
7852 	}
7853 
7854 	if (vi->adapter->flags & IS_VF) {
7855 		MPASS(vi->flags & TX_USES_VM_WR);
7856 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7857 		    NULL, 1, "use VM work requests for transmit");
7858 	} else {
7859 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7860 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7861 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7862 	}
7863 
7864 #ifdef TCP_OFFLOAD
7865 	if (vi->nofldrxq != 0) {
7866 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7867 		    &vi->nofldrxq, 0,
7868 		    "# of rx queues for offloaded TCP connections");
7869 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7870 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7871 		    "index of first TOE rx queue");
7872 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7873 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7874 		    sysctl_holdoff_tmr_idx_ofld, "I",
7875 		    "holdoff timer index for TOE queues");
7876 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7877 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7878 		    sysctl_holdoff_pktc_idx_ofld, "I",
7879 		    "holdoff packet counter index for TOE queues");
7880 	}
7881 #endif
7882 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7883 	if (vi->nofldtxq != 0) {
7884 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7885 		    &vi->nofldtxq, 0,
7886 		    "# of tx queues for TOE/ETHOFLD");
7887 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7888 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7889 		    "index of first TOE/ETHOFLD tx queue");
7890 	}
7891 #endif
7892 #ifdef DEV_NETMAP
7893 	if (vi->nnmrxq != 0) {
7894 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7895 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7896 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7897 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7898 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7899 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7900 		    "index of first netmap rx queue");
7901 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7902 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7903 		    "index of first netmap tx queue");
7904 	}
7905 #endif
7906 
7907 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7908 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7909 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7910 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7911 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7912 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7913 
7914 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7915 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7916 	    sysctl_qsize_rxq, "I", "rx queue size");
7917 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7918 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7919 	    sysctl_qsize_txq, "I", "tx queue size");
7920 }
7921 
7922 static void
7923 cxgbe_sysctls(struct port_info *pi)
7924 {
7925 	struct sysctl_ctx_list *ctx = &pi->ctx;
7926 	struct sysctl_oid *oid;
7927 	struct sysctl_oid_list *children, *children2;
7928 	struct adapter *sc = pi->adapter;
7929 	int i;
7930 	char name[16];
7931 	static char *tc_flags = {"\20\1USER"};
7932 
7933 	/*
7934 	 * dev.cxgbe.X.
7935 	 */
7936 	oid = device_get_sysctl_tree(pi->dev);
7937 	children = SYSCTL_CHILDREN(oid);
7938 
7939 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7940 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7941 	    sysctl_linkdnrc, "A", "reason why link is down");
7942 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7943 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7944 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7945 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7946 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7947 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7948 		    sysctl_btphy, "I", "PHY firmware version");
7949 	}
7950 
7951 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7952 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7953 	    sysctl_pause_settings, "A",
7954 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7955 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7956 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7957 	    "FEC in use on the link");
7958 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7959 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7960 	    sysctl_requested_fec, "A",
7961 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7962 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7963 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7964 	    "FEC recommended by the cable/transceiver");
7965 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7966 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7967 	    sysctl_autoneg, "I",
7968 	    "autonegotiation (-1 = not supported)");
7969 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7970 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7971 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7972 
7973 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7974 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7975 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7976 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7977 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7978 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7979 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7980 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7981 
7982 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7983 	    port_top_speed(pi), "max speed (in Gbps)");
7984 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7985 	    pi->mps_bg_map, "MPS buffer group map");
7986 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7987 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7988 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
7989 	    pi->tx_chan, "TP tx c-channel");
7990 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
7991 	    pi->rx_chan, "TP rx c-channel");
7992 
7993 	if (sc->flags & IS_VF)
7994 		return;
7995 
7996 	/*
7997 	 * dev.(cxgbe|cxl).X.tc.
7998 	 */
7999 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8000 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8001 	    "Tx scheduler traffic classes (cl_rl)");
8002 	children2 = SYSCTL_CHILDREN(oid);
8003 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8004 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8005 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8006 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8007 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8008 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8009 	for (i = 0; i < sc->params.nsched_cls; i++) {
8010 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8011 
8012 		snprintf(name, sizeof(name), "%d", i);
8013 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8014 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8015 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8016 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8017 		    CTLFLAG_RD, &tc->state, 0, "current state");
8018 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8019 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8020 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8021 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8022 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8023 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8024 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8025 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8026 		    "traffic class parameters");
8027 	}
8028 
8029 	/*
8030 	 * dev.cxgbe.X.stats.
8031 	 */
8032 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8033 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8034 	children = SYSCTL_CHILDREN(oid);
8035 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8036 	    &pi->tx_parse_error, 0,
8037 	    "# of tx packets with invalid length or # of segments");
8038 
8039 #define T4_REGSTAT(name, stat, desc) \
8040     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8041 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8042 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8043         sysctl_handle_t4_reg64, "QU", desc)
8044 
8045 /* We get these from port_stats and they may be stale by up to 1s */
8046 #define T4_PORTSTAT(name, desc) \
8047 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8048 	    &pi->stats.name, desc)
8049 
8050 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8051 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8052 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8053 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8054 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8055 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8056 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8057 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8058 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8059 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8060 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8061 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8062 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8063 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8064 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8065 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8066 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8067 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8068 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8069 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8070 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8071 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8072 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8073 
8074 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8075 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8076 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8077 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8078 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8079 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8080 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8081 	if (is_t6(sc)) {
8082 		T4_PORTSTAT(rx_fcs_err,
8083 		    "# of frames received with bad FCS since last link up");
8084 	} else {
8085 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8086 		    "# of frames received with bad FCS");
8087 	}
8088 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8089 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8090 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8091 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8092 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8093 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8094 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8095 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8096 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8097 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8098 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8099 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8100 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8101 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8102 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8103 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8104 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8105 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8106 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8107 
8108 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8109 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8110 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8111 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8112 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8113 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8114 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8115 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8116 
8117 #undef T4_REGSTAT
8118 #undef T4_PORTSTAT
8119 }
8120 
8121 static int
8122 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8123 {
8124 	int rc, *i, space = 0;
8125 	struct sbuf sb;
8126 
8127 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8128 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8129 		if (space)
8130 			sbuf_printf(&sb, " ");
8131 		sbuf_printf(&sb, "%d", *i);
8132 		space = 1;
8133 	}
8134 	rc = sbuf_finish(&sb);
8135 	sbuf_delete(&sb);
8136 	return (rc);
8137 }
8138 
8139 static int
8140 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8141 {
8142 	int rc;
8143 	struct sbuf *sb;
8144 
8145 	rc = sysctl_wire_old_buffer(req, 0);
8146 	if (rc != 0)
8147 		return(rc);
8148 
8149 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8150 	if (sb == NULL)
8151 		return (ENOMEM);
8152 
8153 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8154 	rc = sbuf_finish(sb);
8155 	sbuf_delete(sb);
8156 
8157 	return (rc);
8158 }
8159 
8160 static int
8161 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8162 {
8163 	int rc;
8164 	struct sbuf *sb;
8165 
8166 	rc = sysctl_wire_old_buffer(req, 0);
8167 	if (rc != 0)
8168 		return(rc);
8169 
8170 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8171 	if (sb == NULL)
8172 		return (ENOMEM);
8173 
8174 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8175 	rc = sbuf_finish(sb);
8176 	sbuf_delete(sb);
8177 
8178 	return (rc);
8179 }
8180 
8181 static int
8182 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8183 {
8184 	struct port_info *pi = arg1;
8185 	int op = arg2;
8186 	struct adapter *sc = pi->adapter;
8187 	u_int v;
8188 	int rc;
8189 
8190 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8191 	if (rc)
8192 		return (rc);
8193 	if (hw_off_limits(sc))
8194 		rc = ENXIO;
8195 	else {
8196 		/* XXX: magic numbers */
8197 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8198 		    op ? 0x20 : 0xc820, &v);
8199 	}
8200 	end_synchronized_op(sc, 0);
8201 	if (rc)
8202 		return (rc);
8203 	if (op == 0)
8204 		v /= 256;
8205 
8206 	rc = sysctl_handle_int(oidp, &v, 0, req);
8207 	return (rc);
8208 }
8209 
8210 static int
8211 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8212 {
8213 	struct vi_info *vi = arg1;
8214 	int rc, val;
8215 
8216 	val = vi->rsrv_noflowq;
8217 	rc = sysctl_handle_int(oidp, &val, 0, req);
8218 	if (rc != 0 || req->newptr == NULL)
8219 		return (rc);
8220 
8221 	if ((val >= 1) && (vi->ntxq > 1))
8222 		vi->rsrv_noflowq = 1;
8223 	else
8224 		vi->rsrv_noflowq = 0;
8225 
8226 	return (rc);
8227 }
8228 
8229 static int
8230 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8231 {
8232 	struct vi_info *vi = arg1;
8233 	struct adapter *sc = vi->adapter;
8234 	int rc, val, i;
8235 
8236 	MPASS(!(sc->flags & IS_VF));
8237 
8238 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8239 	rc = sysctl_handle_int(oidp, &val, 0, req);
8240 	if (rc != 0 || req->newptr == NULL)
8241 		return (rc);
8242 
8243 	if (val != 0 && val != 1)
8244 		return (EINVAL);
8245 
8246 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8247 	    "t4txvm");
8248 	if (rc)
8249 		return (rc);
8250 	if (hw_off_limits(sc))
8251 		rc = ENXIO;
8252 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8253 		/*
8254 		 * We don't want parse_pkt to run with one setting (VF or PF)
8255 		 * and then eth_tx to see a different setting but still use
8256 		 * stale information calculated by parse_pkt.
8257 		 */
8258 		rc = EBUSY;
8259 	} else {
8260 		struct port_info *pi = vi->pi;
8261 		struct sge_txq *txq;
8262 		uint32_t ctrl0;
8263 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8264 
8265 		if (val) {
8266 			vi->flags |= TX_USES_VM_WR;
8267 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8268 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8269 			    V_TXPKT_INTF(pi->tx_chan));
8270 			if (!(sc->flags & IS_VF))
8271 				npkt--;
8272 		} else {
8273 			vi->flags &= ~TX_USES_VM_WR;
8274 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8275 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8276 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8277 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8278 		}
8279 		for_each_txq(vi, i, txq) {
8280 			txq->cpl_ctrl0 = ctrl0;
8281 			txq->txp.max_npkt = npkt;
8282 		}
8283 	}
8284 	end_synchronized_op(sc, LOCK_HELD);
8285 	return (rc);
8286 }
8287 
8288 static int
8289 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8290 {
8291 	struct vi_info *vi = arg1;
8292 	struct adapter *sc = vi->adapter;
8293 	int idx, rc, i;
8294 	struct sge_rxq *rxq;
8295 	uint8_t v;
8296 
8297 	idx = vi->tmr_idx;
8298 
8299 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8300 	if (rc != 0 || req->newptr == NULL)
8301 		return (rc);
8302 
8303 	if (idx < 0 || idx >= SGE_NTIMERS)
8304 		return (EINVAL);
8305 
8306 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8307 	    "t4tmr");
8308 	if (rc)
8309 		return (rc);
8310 
8311 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8312 	for_each_rxq(vi, i, rxq) {
8313 #ifdef atomic_store_rel_8
8314 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8315 #else
8316 		rxq->iq.intr_params = v;
8317 #endif
8318 	}
8319 	vi->tmr_idx = idx;
8320 
8321 	end_synchronized_op(sc, LOCK_HELD);
8322 	return (0);
8323 }
8324 
8325 static int
8326 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8327 {
8328 	struct vi_info *vi = arg1;
8329 	struct adapter *sc = vi->adapter;
8330 	int idx, rc;
8331 
8332 	idx = vi->pktc_idx;
8333 
8334 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8335 	if (rc != 0 || req->newptr == NULL)
8336 		return (rc);
8337 
8338 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8339 		return (EINVAL);
8340 
8341 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8342 	    "t4pktc");
8343 	if (rc)
8344 		return (rc);
8345 
8346 	if (vi->flags & VI_INIT_DONE)
8347 		rc = EBUSY; /* cannot be changed once the queues are created */
8348 	else
8349 		vi->pktc_idx = idx;
8350 
8351 	end_synchronized_op(sc, LOCK_HELD);
8352 	return (rc);
8353 }
8354 
8355 static int
8356 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8357 {
8358 	struct vi_info *vi = arg1;
8359 	struct adapter *sc = vi->adapter;
8360 	int qsize, rc;
8361 
8362 	qsize = vi->qsize_rxq;
8363 
8364 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8365 	if (rc != 0 || req->newptr == NULL)
8366 		return (rc);
8367 
8368 	if (qsize < 128 || (qsize & 7))
8369 		return (EINVAL);
8370 
8371 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8372 	    "t4rxqs");
8373 	if (rc)
8374 		return (rc);
8375 
8376 	if (vi->flags & VI_INIT_DONE)
8377 		rc = EBUSY; /* cannot be changed once the queues are created */
8378 	else
8379 		vi->qsize_rxq = qsize;
8380 
8381 	end_synchronized_op(sc, LOCK_HELD);
8382 	return (rc);
8383 }
8384 
8385 static int
8386 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8387 {
8388 	struct vi_info *vi = arg1;
8389 	struct adapter *sc = vi->adapter;
8390 	int qsize, rc;
8391 
8392 	qsize = vi->qsize_txq;
8393 
8394 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8395 	if (rc != 0 || req->newptr == NULL)
8396 		return (rc);
8397 
8398 	if (qsize < 128 || qsize > 65536)
8399 		return (EINVAL);
8400 
8401 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8402 	    "t4txqs");
8403 	if (rc)
8404 		return (rc);
8405 
8406 	if (vi->flags & VI_INIT_DONE)
8407 		rc = EBUSY; /* cannot be changed once the queues are created */
8408 	else
8409 		vi->qsize_txq = qsize;
8410 
8411 	end_synchronized_op(sc, LOCK_HELD);
8412 	return (rc);
8413 }
8414 
8415 static int
8416 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8417 {
8418 	struct port_info *pi = arg1;
8419 	struct adapter *sc = pi->adapter;
8420 	struct link_config *lc = &pi->link_cfg;
8421 	int rc;
8422 
8423 	if (req->newptr == NULL) {
8424 		struct sbuf *sb;
8425 		static char *bits = "\20\1RX\2TX\3AUTO";
8426 
8427 		rc = sysctl_wire_old_buffer(req, 0);
8428 		if (rc != 0)
8429 			return(rc);
8430 
8431 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8432 		if (sb == NULL)
8433 			return (ENOMEM);
8434 
8435 		if (lc->link_ok) {
8436 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8437 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8438 		} else {
8439 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8440 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8441 		}
8442 		rc = sbuf_finish(sb);
8443 		sbuf_delete(sb);
8444 	} else {
8445 		char s[2];
8446 		int n;
8447 
8448 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8449 		    PAUSE_AUTONEG));
8450 		s[1] = 0;
8451 
8452 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8453 		if (rc != 0)
8454 			return(rc);
8455 
8456 		if (s[1] != 0)
8457 			return (EINVAL);
8458 		if (s[0] < '0' || s[0] > '9')
8459 			return (EINVAL);	/* not a number */
8460 		n = s[0] - '0';
8461 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8462 			return (EINVAL);	/* some other bit is set too */
8463 
8464 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8465 		    "t4PAUSE");
8466 		if (rc)
8467 			return (rc);
8468 		if (!hw_off_limits(sc)) {
8469 			PORT_LOCK(pi);
8470 			lc->requested_fc = n;
8471 			fixup_link_config(pi);
8472 			if (pi->up_vis > 0)
8473 				rc = apply_link_config(pi);
8474 			set_current_media(pi);
8475 			PORT_UNLOCK(pi);
8476 		}
8477 		end_synchronized_op(sc, 0);
8478 	}
8479 
8480 	return (rc);
8481 }
8482 
8483 static int
8484 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8485 {
8486 	struct port_info *pi = arg1;
8487 	struct link_config *lc = &pi->link_cfg;
8488 	int rc;
8489 	struct sbuf *sb;
8490 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8491 
8492 	rc = sysctl_wire_old_buffer(req, 0);
8493 	if (rc != 0)
8494 		return(rc);
8495 
8496 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8497 	if (sb == NULL)
8498 		return (ENOMEM);
8499 	if (lc->link_ok)
8500 		sbuf_printf(sb, "%b", lc->fec, bits);
8501 	else
8502 		sbuf_printf(sb, "no link");
8503 	rc = sbuf_finish(sb);
8504 	sbuf_delete(sb);
8505 
8506 	return (rc);
8507 }
8508 
8509 static int
8510 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8511 {
8512 	struct port_info *pi = arg1;
8513 	struct adapter *sc = pi->adapter;
8514 	struct link_config *lc = &pi->link_cfg;
8515 	int rc;
8516 	int8_t old;
8517 
8518 	if (req->newptr == NULL) {
8519 		struct sbuf *sb;
8520 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8521 		    "\5RSVD3\6auto\7module";
8522 
8523 		rc = sysctl_wire_old_buffer(req, 0);
8524 		if (rc != 0)
8525 			return(rc);
8526 
8527 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8528 		if (sb == NULL)
8529 			return (ENOMEM);
8530 
8531 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8532 		rc = sbuf_finish(sb);
8533 		sbuf_delete(sb);
8534 	} else {
8535 		char s[8];
8536 		int n;
8537 
8538 		snprintf(s, sizeof(s), "%d",
8539 		    lc->requested_fec == FEC_AUTO ? -1 :
8540 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8541 
8542 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8543 		if (rc != 0)
8544 			return(rc);
8545 
8546 		n = strtol(&s[0], NULL, 0);
8547 		if (n < 0 || n & FEC_AUTO)
8548 			n = FEC_AUTO;
8549 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8550 			return (EINVAL);/* some other bit is set too */
8551 
8552 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8553 		    "t4reqf");
8554 		if (rc)
8555 			return (rc);
8556 		PORT_LOCK(pi);
8557 		old = lc->requested_fec;
8558 		if (n == FEC_AUTO)
8559 			lc->requested_fec = FEC_AUTO;
8560 		else if (n == 0 || n == FEC_NONE)
8561 			lc->requested_fec = FEC_NONE;
8562 		else {
8563 			if ((lc->pcaps |
8564 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8565 			    lc->pcaps) {
8566 				rc = ENOTSUP;
8567 				goto done;
8568 			}
8569 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8570 			    FEC_MODULE);
8571 		}
8572 		if (!hw_off_limits(sc)) {
8573 			fixup_link_config(pi);
8574 			if (pi->up_vis > 0) {
8575 				rc = apply_link_config(pi);
8576 				if (rc != 0) {
8577 					lc->requested_fec = old;
8578 					if (rc == FW_EPROTO)
8579 						rc = ENOTSUP;
8580 				}
8581 			}
8582 		}
8583 done:
8584 		PORT_UNLOCK(pi);
8585 		end_synchronized_op(sc, 0);
8586 	}
8587 
8588 	return (rc);
8589 }
8590 
8591 static int
8592 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8593 {
8594 	struct port_info *pi = arg1;
8595 	struct adapter *sc = pi->adapter;
8596 	struct link_config *lc = &pi->link_cfg;
8597 	int rc;
8598 	int8_t fec;
8599 	struct sbuf *sb;
8600 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8601 
8602 	rc = sysctl_wire_old_buffer(req, 0);
8603 	if (rc != 0)
8604 		return (rc);
8605 
8606 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8607 	if (sb == NULL)
8608 		return (ENOMEM);
8609 
8610 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8611 		rc = EBUSY;
8612 		goto done;
8613 	}
8614 	if (hw_off_limits(sc)) {
8615 		rc = ENXIO;
8616 		goto done;
8617 	}
8618 	PORT_LOCK(pi);
8619 	if (pi->up_vis == 0) {
8620 		/*
8621 		 * If all the interfaces are administratively down the firmware
8622 		 * does not report transceiver changes.  Refresh port info here.
8623 		 * This is the only reason we have a synchronized op in this
8624 		 * function.  Just PORT_LOCK would have been enough otherwise.
8625 		 */
8626 		t4_update_port_info(pi);
8627 	}
8628 
8629 	fec = lc->fec_hint;
8630 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8631 	    !fec_supported(lc->pcaps)) {
8632 		sbuf_printf(sb, "n/a");
8633 	} else {
8634 		if (fec == 0)
8635 			fec = FEC_NONE;
8636 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8637 	}
8638 	rc = sbuf_finish(sb);
8639 	PORT_UNLOCK(pi);
8640 done:
8641 	sbuf_delete(sb);
8642 	end_synchronized_op(sc, 0);
8643 
8644 	return (rc);
8645 }
8646 
8647 static int
8648 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8649 {
8650 	struct port_info *pi = arg1;
8651 	struct adapter *sc = pi->adapter;
8652 	struct link_config *lc = &pi->link_cfg;
8653 	int rc, val;
8654 
8655 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8656 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8657 	else
8658 		val = -1;
8659 	rc = sysctl_handle_int(oidp, &val, 0, req);
8660 	if (rc != 0 || req->newptr == NULL)
8661 		return (rc);
8662 	if (val == 0)
8663 		val = AUTONEG_DISABLE;
8664 	else if (val == 1)
8665 		val = AUTONEG_ENABLE;
8666 	else
8667 		val = AUTONEG_AUTO;
8668 
8669 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8670 	    "t4aneg");
8671 	if (rc)
8672 		return (rc);
8673 	PORT_LOCK(pi);
8674 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8675 		rc = ENOTSUP;
8676 		goto done;
8677 	}
8678 	lc->requested_aneg = val;
8679 	if (!hw_off_limits(sc)) {
8680 		fixup_link_config(pi);
8681 		if (pi->up_vis > 0)
8682 			rc = apply_link_config(pi);
8683 		set_current_media(pi);
8684 	}
8685 done:
8686 	PORT_UNLOCK(pi);
8687 	end_synchronized_op(sc, 0);
8688 	return (rc);
8689 }
8690 
8691 static int
8692 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8693 {
8694 	struct port_info *pi = arg1;
8695 	struct adapter *sc = pi->adapter;
8696 	struct link_config *lc = &pi->link_cfg;
8697 	int rc, val;
8698 
8699 	val = lc->force_fec;
8700 	MPASS(val >= -1 && val <= 1);
8701 	rc = sysctl_handle_int(oidp, &val, 0, req);
8702 	if (rc != 0 || req->newptr == NULL)
8703 		return (rc);
8704 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8705 		return (ENOTSUP);
8706 	if (val < -1 || val > 1)
8707 		return (EINVAL);
8708 
8709 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8710 	if (rc)
8711 		return (rc);
8712 	PORT_LOCK(pi);
8713 	lc->force_fec = val;
8714 	if (!hw_off_limits(sc)) {
8715 		fixup_link_config(pi);
8716 		if (pi->up_vis > 0)
8717 			rc = apply_link_config(pi);
8718 	}
8719 	PORT_UNLOCK(pi);
8720 	end_synchronized_op(sc, 0);
8721 	return (rc);
8722 }
8723 
8724 static int
8725 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8726 {
8727 	struct adapter *sc = arg1;
8728 	int rc, reg = arg2;
8729 	uint64_t val;
8730 
8731 	mtx_lock(&sc->reg_lock);
8732 	if (hw_off_limits(sc))
8733 		rc = ENXIO;
8734 	else {
8735 		rc = 0;
8736 		val = t4_read_reg64(sc, reg);
8737 	}
8738 	mtx_unlock(&sc->reg_lock);
8739 	if (rc == 0)
8740 		rc = sysctl_handle_64(oidp, &val, 0, req);
8741 	return (rc);
8742 }
8743 
8744 static int
8745 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8746 {
8747 	struct adapter *sc = arg1;
8748 	int rc, t;
8749 	uint32_t param, val;
8750 
8751 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8752 	if (rc)
8753 		return (rc);
8754 	if (hw_off_limits(sc))
8755 		rc = ENXIO;
8756 	else {
8757 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8758 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8759 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8760 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8761 	}
8762 	end_synchronized_op(sc, 0);
8763 	if (rc)
8764 		return (rc);
8765 
8766 	/* unknown is returned as 0 but we display -1 in that case */
8767 	t = val == 0 ? -1 : val;
8768 
8769 	rc = sysctl_handle_int(oidp, &t, 0, req);
8770 	return (rc);
8771 }
8772 
8773 static int
8774 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8775 {
8776 	struct adapter *sc = arg1;
8777 	int rc;
8778 	uint32_t param, val;
8779 
8780 	if (sc->params.core_vdd == 0) {
8781 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8782 		    "t4vdd");
8783 		if (rc)
8784 			return (rc);
8785 		if (hw_off_limits(sc))
8786 			rc = ENXIO;
8787 		else {
8788 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8789 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8790 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8791 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8792 			    &param, &val);
8793 		}
8794 		end_synchronized_op(sc, 0);
8795 		if (rc)
8796 			return (rc);
8797 		sc->params.core_vdd = val;
8798 	}
8799 
8800 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8801 }
8802 
8803 static int
8804 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8805 {
8806 	struct adapter *sc = arg1;
8807 	int rc, v;
8808 	uint32_t param, val;
8809 
8810 	v = sc->sensor_resets;
8811 	rc = sysctl_handle_int(oidp, &v, 0, req);
8812 	if (rc != 0 || req->newptr == NULL || v <= 0)
8813 		return (rc);
8814 
8815 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8816 	    chip_id(sc) < CHELSIO_T5)
8817 		return (ENOTSUP);
8818 
8819 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8820 	if (rc)
8821 		return (rc);
8822 	if (hw_off_limits(sc))
8823 		rc = ENXIO;
8824 	else {
8825 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8826 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8827 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8828 		val = 1;
8829 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8830 	}
8831 	end_synchronized_op(sc, 0);
8832 	if (rc == 0)
8833 		sc->sensor_resets++;
8834 	return (rc);
8835 }
8836 
8837 static int
8838 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8839 {
8840 	struct adapter *sc = arg1;
8841 	struct sbuf *sb;
8842 	int rc;
8843 	uint32_t param, val;
8844 
8845 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8846 	if (rc)
8847 		return (rc);
8848 	if (hw_off_limits(sc))
8849 		rc = ENXIO;
8850 	else {
8851 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8852 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8853 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8854 	}
8855 	end_synchronized_op(sc, 0);
8856 	if (rc)
8857 		return (rc);
8858 
8859 	rc = sysctl_wire_old_buffer(req, 0);
8860 	if (rc != 0)
8861 		return (rc);
8862 
8863 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8864 	if (sb == NULL)
8865 		return (ENOMEM);
8866 
8867 	if (val == 0xffffffff) {
8868 		/* Only debug and custom firmwares report load averages. */
8869 		sbuf_printf(sb, "not available");
8870 	} else {
8871 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8872 		    (val >> 16) & 0xff);
8873 	}
8874 	rc = sbuf_finish(sb);
8875 	sbuf_delete(sb);
8876 
8877 	return (rc);
8878 }
8879 
8880 static int
8881 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8882 {
8883 	struct adapter *sc = arg1;
8884 	struct sbuf *sb;
8885 	int rc, i;
8886 	uint16_t incr[NMTUS][NCCTRL_WIN];
8887 	static const char *dec_fac[] = {
8888 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8889 		"0.9375"
8890 	};
8891 
8892 	rc = sysctl_wire_old_buffer(req, 0);
8893 	if (rc != 0)
8894 		return (rc);
8895 
8896 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8897 	if (sb == NULL)
8898 		return (ENOMEM);
8899 
8900 	mtx_lock(&sc->reg_lock);
8901 	if (hw_off_limits(sc))
8902 		rc = ENXIO;
8903 	else
8904 		t4_read_cong_tbl(sc, incr);
8905 	mtx_unlock(&sc->reg_lock);
8906 	if (rc)
8907 		goto done;
8908 
8909 	for (i = 0; i < NCCTRL_WIN; ++i) {
8910 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8911 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8912 		    incr[5][i], incr[6][i], incr[7][i]);
8913 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8914 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8915 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8916 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8917 	}
8918 
8919 	rc = sbuf_finish(sb);
8920 done:
8921 	sbuf_delete(sb);
8922 	return (rc);
8923 }
8924 
8925 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8926 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8927 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8928 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8929 };
8930 
8931 static int
8932 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8933 {
8934 	struct adapter *sc = arg1;
8935 	struct sbuf *sb;
8936 	int rc, i, n, qid = arg2;
8937 	uint32_t *buf, *p;
8938 	char *qtype;
8939 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8940 
8941 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8942 	    ("%s: bad qid %d\n", __func__, qid));
8943 
8944 	if (qid < CIM_NUM_IBQ) {
8945 		/* inbound queue */
8946 		qtype = "IBQ";
8947 		n = 4 * CIM_IBQ_SIZE;
8948 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8949 		mtx_lock(&sc->reg_lock);
8950 		if (hw_off_limits(sc))
8951 			rc = -ENXIO;
8952 		else
8953 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8954 		mtx_unlock(&sc->reg_lock);
8955 	} else {
8956 		/* outbound queue */
8957 		qtype = "OBQ";
8958 		qid -= CIM_NUM_IBQ;
8959 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8960 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8961 		mtx_lock(&sc->reg_lock);
8962 		if (hw_off_limits(sc))
8963 			rc = -ENXIO;
8964 		else
8965 			rc = t4_read_cim_obq(sc, qid, buf, n);
8966 		mtx_unlock(&sc->reg_lock);
8967 	}
8968 
8969 	if (rc < 0) {
8970 		rc = -rc;
8971 		goto done;
8972 	}
8973 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8974 
8975 	rc = sysctl_wire_old_buffer(req, 0);
8976 	if (rc != 0)
8977 		goto done;
8978 
8979 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8980 	if (sb == NULL) {
8981 		rc = ENOMEM;
8982 		goto done;
8983 	}
8984 
8985 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8986 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8987 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8988 		    p[2], p[3]);
8989 
8990 	rc = sbuf_finish(sb);
8991 	sbuf_delete(sb);
8992 done:
8993 	free(buf, M_CXGBE);
8994 	return (rc);
8995 }
8996 
8997 static void
8998 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8999 {
9000 	uint32_t *p;
9001 
9002 	sbuf_printf(sb, "Status   Data      PC%s",
9003 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9004 	    "     LS0Stat  LS0Addr             LS0Data");
9005 
9006 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9007 		if (cfg & F_UPDBGLACAPTPCONLY) {
9008 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9009 			    p[6], p[7]);
9010 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9011 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9012 			    p[4] & 0xff, p[5] >> 8);
9013 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9014 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9015 			    p[1] & 0xf, p[2] >> 4);
9016 		} else {
9017 			sbuf_printf(sb,
9018 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9019 			    "%08x%08x%08x%08x",
9020 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9021 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9022 			    p[6], p[7]);
9023 		}
9024 	}
9025 }
9026 
9027 static void
9028 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9029 {
9030 	uint32_t *p;
9031 
9032 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9033 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9034 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9035 
9036 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9037 		if (cfg & F_UPDBGLACAPTPCONLY) {
9038 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9039 			    p[3] & 0xff, p[2], p[1], p[0]);
9040 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9041 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9042 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9043 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9044 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9045 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9046 			    p[6] >> 16);
9047 		} else {
9048 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9049 			    "%08x %08x %08x %08x %08x %08x",
9050 			    (p[9] >> 16) & 0xff,
9051 			    p[9] & 0xffff, p[8] >> 16,
9052 			    p[8] & 0xffff, p[7] >> 16,
9053 			    p[7] & 0xffff, p[6] >> 16,
9054 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9055 		}
9056 	}
9057 }
9058 
9059 static int
9060 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9061 {
9062 	uint32_t cfg, *buf;
9063 	int rc;
9064 
9065 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9066 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9067 	    M_ZERO | flags);
9068 	if (buf == NULL)
9069 		return (ENOMEM);
9070 
9071 	mtx_lock(&sc->reg_lock);
9072 	if (hw_off_limits(sc))
9073 		rc = ENXIO;
9074 	else {
9075 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9076 		if (rc == 0)
9077 			rc = -t4_cim_read_la(sc, buf, NULL);
9078 	}
9079 	mtx_unlock(&sc->reg_lock);
9080 	if (rc == 0) {
9081 		if (chip_id(sc) < CHELSIO_T6)
9082 			sbuf_cim_la4(sc, sb, buf, cfg);
9083 		else
9084 			sbuf_cim_la6(sc, sb, buf, cfg);
9085 	}
9086 	free(buf, M_CXGBE);
9087 	return (rc);
9088 }
9089 
9090 static int
9091 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9092 {
9093 	struct adapter *sc = arg1;
9094 	struct sbuf *sb;
9095 	int rc;
9096 
9097 	rc = sysctl_wire_old_buffer(req, 0);
9098 	if (rc != 0)
9099 		return (rc);
9100 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9101 	if (sb == NULL)
9102 		return (ENOMEM);
9103 
9104 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9105 	if (rc == 0)
9106 		rc = sbuf_finish(sb);
9107 	sbuf_delete(sb);
9108 	return (rc);
9109 }
9110 
9111 static void
9112 dump_cim_regs(struct adapter *sc)
9113 {
9114 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9115 	    device_get_nameunit(sc->dev),
9116 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9117 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9118 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9119 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9120 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9121 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9122 	    device_get_nameunit(sc->dev),
9123 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9124 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9125 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9126 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9127 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9128 }
9129 
9130 static void
9131 dump_cimla(struct adapter *sc)
9132 {
9133 	struct sbuf sb;
9134 	int rc;
9135 
9136 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9137 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9138 		    device_get_nameunit(sc->dev));
9139 		return;
9140 	}
9141 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9142 	if (rc == 0) {
9143 		rc = sbuf_finish(&sb);
9144 		if (rc == 0) {
9145 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9146 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9147 		}
9148 	}
9149 	sbuf_delete(&sb);
9150 }
9151 
9152 void
9153 t4_os_cim_err(struct adapter *sc)
9154 {
9155 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9156 }
9157 
9158 static int
9159 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9160 {
9161 	struct adapter *sc = arg1;
9162 	u_int i;
9163 	struct sbuf *sb;
9164 	uint32_t *buf, *p;
9165 	int rc;
9166 
9167 	rc = sysctl_wire_old_buffer(req, 0);
9168 	if (rc != 0)
9169 		return (rc);
9170 
9171 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9172 	if (sb == NULL)
9173 		return (ENOMEM);
9174 
9175 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9176 	    M_ZERO | M_WAITOK);
9177 
9178 	mtx_lock(&sc->reg_lock);
9179 	if (hw_off_limits(sc))
9180 		rc = ENXIO;
9181 	else
9182 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9183 	mtx_unlock(&sc->reg_lock);
9184 	if (rc)
9185 		goto done;
9186 
9187 	p = buf;
9188 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9189 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9190 		    p[1], p[0]);
9191 	}
9192 
9193 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9194 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9195 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9196 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9197 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9198 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9199 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9200 		    p[0] & 1);
9201 	}
9202 	rc = sbuf_finish(sb);
9203 done:
9204 	sbuf_delete(sb);
9205 	free(buf, M_CXGBE);
9206 	return (rc);
9207 }
9208 
9209 static int
9210 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9211 {
9212 	struct adapter *sc = arg1;
9213 	u_int i;
9214 	struct sbuf *sb;
9215 	uint32_t *buf, *p;
9216 	int rc;
9217 
9218 	rc = sysctl_wire_old_buffer(req, 0);
9219 	if (rc != 0)
9220 		return (rc);
9221 
9222 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9223 	if (sb == NULL)
9224 		return (ENOMEM);
9225 
9226 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9227 	    M_ZERO | M_WAITOK);
9228 
9229 	mtx_lock(&sc->reg_lock);
9230 	if (hw_off_limits(sc))
9231 		rc = ENXIO;
9232 	else
9233 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9234 	mtx_unlock(&sc->reg_lock);
9235 	if (rc)
9236 		goto done;
9237 
9238 	p = buf;
9239 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9240 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9241 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9242 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9243 		    p[4], p[3], p[2], p[1], p[0]);
9244 	}
9245 
9246 	sbuf_printf(sb, "\n\nCntl ID               Data");
9247 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9248 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9249 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9250 	}
9251 
9252 	rc = sbuf_finish(sb);
9253 done:
9254 	sbuf_delete(sb);
9255 	free(buf, M_CXGBE);
9256 	return (rc);
9257 }
9258 
9259 static int
9260 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9261 {
9262 	struct adapter *sc = arg1;
9263 	struct sbuf *sb;
9264 	int rc, i;
9265 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9266 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9267 	uint16_t thres[CIM_NUM_IBQ];
9268 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9269 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9270 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9271 
9272 	cim_num_obq = sc->chip_params->cim_num_obq;
9273 	if (is_t4(sc)) {
9274 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9275 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9276 	} else {
9277 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9278 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9279 	}
9280 	nq = CIM_NUM_IBQ + cim_num_obq;
9281 
9282 	mtx_lock(&sc->reg_lock);
9283 	if (hw_off_limits(sc))
9284 		rc = ENXIO;
9285 	else {
9286 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9287 		if (rc == 0) {
9288 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9289 			    obq_wr);
9290 			if (rc == 0)
9291 				t4_read_cimq_cfg(sc, base, size, thres);
9292 		}
9293 	}
9294 	mtx_unlock(&sc->reg_lock);
9295 	if (rc)
9296 		return (rc);
9297 
9298 	rc = sysctl_wire_old_buffer(req, 0);
9299 	if (rc != 0)
9300 		return (rc);
9301 
9302 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9303 	if (sb == NULL)
9304 		return (ENOMEM);
9305 
9306 	sbuf_printf(sb,
9307 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9308 
9309 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9310 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9311 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9312 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9313 		    G_QUEREMFLITS(p[2]) * 16);
9314 	for ( ; i < nq; i++, p += 4, wr += 2)
9315 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9316 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9317 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9318 		    G_QUEREMFLITS(p[2]) * 16);
9319 
9320 	rc = sbuf_finish(sb);
9321 	sbuf_delete(sb);
9322 
9323 	return (rc);
9324 }
9325 
9326 static int
9327 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9328 {
9329 	struct adapter *sc = arg1;
9330 	struct sbuf *sb;
9331 	int rc;
9332 	struct tp_cpl_stats stats;
9333 
9334 	rc = sysctl_wire_old_buffer(req, 0);
9335 	if (rc != 0)
9336 		return (rc);
9337 
9338 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9339 	if (sb == NULL)
9340 		return (ENOMEM);
9341 
9342 	mtx_lock(&sc->reg_lock);
9343 	if (hw_off_limits(sc))
9344 		rc = ENXIO;
9345 	else
9346 		t4_tp_get_cpl_stats(sc, &stats, 0);
9347 	mtx_unlock(&sc->reg_lock);
9348 	if (rc)
9349 		goto done;
9350 
9351 	if (sc->chip_params->nchan > 2) {
9352 		sbuf_printf(sb, "                 channel 0  channel 1"
9353 		    "  channel 2  channel 3");
9354 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9355 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9356 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9357 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9358 	} else {
9359 		sbuf_printf(sb, "                 channel 0  channel 1");
9360 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9361 		    stats.req[0], stats.req[1]);
9362 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9363 		    stats.rsp[0], stats.rsp[1]);
9364 	}
9365 
9366 	rc = sbuf_finish(sb);
9367 done:
9368 	sbuf_delete(sb);
9369 	return (rc);
9370 }
9371 
9372 static int
9373 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9374 {
9375 	struct adapter *sc = arg1;
9376 	struct sbuf *sb;
9377 	int rc;
9378 	struct tp_usm_stats stats;
9379 
9380 	rc = sysctl_wire_old_buffer(req, 0);
9381 	if (rc != 0)
9382 		return(rc);
9383 
9384 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9385 	if (sb == NULL)
9386 		return (ENOMEM);
9387 
9388 	mtx_lock(&sc->reg_lock);
9389 	if (hw_off_limits(sc))
9390 		rc = ENXIO;
9391 	else
9392 		t4_get_usm_stats(sc, &stats, 1);
9393 	mtx_unlock(&sc->reg_lock);
9394 	if (rc == 0) {
9395 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9396 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9397 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9398 		rc = sbuf_finish(sb);
9399 	}
9400 	sbuf_delete(sb);
9401 
9402 	return (rc);
9403 }
9404 
9405 static int
9406 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9407 {
9408 	struct adapter *sc = arg1;
9409 	struct sbuf *sb;
9410 	int rc;
9411 	struct tp_tid_stats stats;
9412 
9413 	rc = sysctl_wire_old_buffer(req, 0);
9414 	if (rc != 0)
9415 		return(rc);
9416 
9417 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9418 	if (sb == NULL)
9419 		return (ENOMEM);
9420 
9421 	mtx_lock(&sc->reg_lock);
9422 	if (hw_off_limits(sc))
9423 		rc = ENXIO;
9424 	else
9425 		t4_tp_get_tid_stats(sc, &stats, 1);
9426 	mtx_unlock(&sc->reg_lock);
9427 	if (rc == 0) {
9428 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9429 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9430 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9431 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9432 		rc = sbuf_finish(sb);
9433 	}
9434 	sbuf_delete(sb);
9435 
9436 	return (rc);
9437 }
9438 
9439 static const char * const devlog_level_strings[] = {
9440 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9441 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9442 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9443 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9444 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9445 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9446 };
9447 
9448 static const char * const devlog_facility_strings[] = {
9449 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9450 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9451 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9452 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9453 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9454 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9455 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9456 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9457 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9458 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9459 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9460 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9461 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9462 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9463 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9464 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9465 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9466 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9467 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9468 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9469 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9470 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9471 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9472 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9473 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9474 };
9475 
9476 static int
9477 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9478 {
9479 	int i, j, rc, nentries, first = 0;
9480 	struct devlog_params *dparams = &sc->params.devlog;
9481 	struct fw_devlog_e *buf, *e;
9482 	uint64_t ftstamp = UINT64_MAX;
9483 
9484 	if (dparams->addr == 0)
9485 		return (ENXIO);
9486 
9487 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9488 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9489 	if (buf == NULL)
9490 		return (ENOMEM);
9491 
9492 	mtx_lock(&sc->reg_lock);
9493 	if (hw_off_limits(sc))
9494 		rc = ENXIO;
9495 	else
9496 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9497 		    dparams->size);
9498 	mtx_unlock(&sc->reg_lock);
9499 	if (rc != 0)
9500 		goto done;
9501 
9502 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9503 	for (i = 0; i < nentries; i++) {
9504 		e = &buf[i];
9505 
9506 		if (e->timestamp == 0)
9507 			break;	/* end */
9508 
9509 		e->timestamp = be64toh(e->timestamp);
9510 		e->seqno = be32toh(e->seqno);
9511 		for (j = 0; j < 8; j++)
9512 			e->params[j] = be32toh(e->params[j]);
9513 
9514 		if (e->timestamp < ftstamp) {
9515 			ftstamp = e->timestamp;
9516 			first = i;
9517 		}
9518 	}
9519 
9520 	if (buf[first].timestamp == 0)
9521 		goto done;	/* nothing in the log */
9522 
9523 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9524 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9525 
9526 	i = first;
9527 	do {
9528 		e = &buf[i];
9529 		if (e->timestamp == 0)
9530 			break;	/* end */
9531 
9532 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9533 		    e->seqno, e->timestamp,
9534 		    (e->level < nitems(devlog_level_strings) ?
9535 			devlog_level_strings[e->level] : "UNKNOWN"),
9536 		    (e->facility < nitems(devlog_facility_strings) ?
9537 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9538 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9539 		    e->params[2], e->params[3], e->params[4],
9540 		    e->params[5], e->params[6], e->params[7]);
9541 
9542 		if (++i == nentries)
9543 			i = 0;
9544 	} while (i != first);
9545 done:
9546 	free(buf, M_CXGBE);
9547 	return (rc);
9548 }
9549 
9550 static int
9551 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9552 {
9553 	struct adapter *sc = arg1;
9554 	int rc;
9555 	struct sbuf *sb;
9556 
9557 	rc = sysctl_wire_old_buffer(req, 0);
9558 	if (rc != 0)
9559 		return (rc);
9560 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9561 	if (sb == NULL)
9562 		return (ENOMEM);
9563 
9564 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9565 	if (rc == 0)
9566 		rc = sbuf_finish(sb);
9567 	sbuf_delete(sb);
9568 	return (rc);
9569 }
9570 
9571 static void
9572 dump_devlog(struct adapter *sc)
9573 {
9574 	int rc;
9575 	struct sbuf sb;
9576 
9577 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9578 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9579 		    device_get_nameunit(sc->dev));
9580 		return;
9581 	}
9582 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9583 	if (rc == 0) {
9584 		rc = sbuf_finish(&sb);
9585 		if (rc == 0) {
9586 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9587 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9588 		}
9589 	}
9590 	sbuf_delete(&sb);
9591 }
9592 
9593 static int
9594 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9595 {
9596 	struct adapter *sc = arg1;
9597 	struct sbuf *sb;
9598 	int rc;
9599 	struct tp_fcoe_stats stats[MAX_NCHAN];
9600 	int i, nchan = sc->chip_params->nchan;
9601 
9602 	rc = sysctl_wire_old_buffer(req, 0);
9603 	if (rc != 0)
9604 		return (rc);
9605 
9606 	mtx_lock(&sc->reg_lock);
9607 	if (hw_off_limits(sc))
9608 		rc = ENXIO;
9609 	else {
9610 		for (i = 0; i < nchan; i++)
9611 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9612 	}
9613 	mtx_unlock(&sc->reg_lock);
9614 	if (rc != 0)
9615 		return (rc);
9616 
9617 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9618 	if (sb == NULL)
9619 		return (ENOMEM);
9620 
9621 	if (nchan > 2) {
9622 		sbuf_printf(sb, "                   channel 0        channel 1"
9623 		    "        channel 2        channel 3");
9624 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9625 		    stats[0].octets_ddp, stats[1].octets_ddp,
9626 		    stats[2].octets_ddp, stats[3].octets_ddp);
9627 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9628 		    stats[0].frames_ddp, stats[1].frames_ddp,
9629 		    stats[2].frames_ddp, stats[3].frames_ddp);
9630 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9631 		    stats[0].frames_drop, stats[1].frames_drop,
9632 		    stats[2].frames_drop, stats[3].frames_drop);
9633 	} else {
9634 		sbuf_printf(sb, "                   channel 0        channel 1");
9635 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9636 		    stats[0].octets_ddp, stats[1].octets_ddp);
9637 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9638 		    stats[0].frames_ddp, stats[1].frames_ddp);
9639 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9640 		    stats[0].frames_drop, stats[1].frames_drop);
9641 	}
9642 
9643 	rc = sbuf_finish(sb);
9644 	sbuf_delete(sb);
9645 
9646 	return (rc);
9647 }
9648 
9649 static int
9650 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9651 {
9652 	struct adapter *sc = arg1;
9653 	struct sbuf *sb;
9654 	int rc, i;
9655 	unsigned int map, kbps, ipg, mode;
9656 	unsigned int pace_tab[NTX_SCHED];
9657 
9658 	rc = sysctl_wire_old_buffer(req, 0);
9659 	if (rc != 0)
9660 		return (rc);
9661 
9662 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9663 	if (sb == NULL)
9664 		return (ENOMEM);
9665 
9666 	mtx_lock(&sc->reg_lock);
9667 	if (hw_off_limits(sc)) {
9668 		rc = ENXIO;
9669 		goto done;
9670 	}
9671 
9672 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9673 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9674 	t4_read_pace_tbl(sc, pace_tab);
9675 
9676 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9677 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9678 
9679 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9680 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9681 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9682 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9683 		if (kbps)
9684 			sbuf_printf(sb, "%9u     ", kbps);
9685 		else
9686 			sbuf_printf(sb, " disabled     ");
9687 
9688 		if (ipg)
9689 			sbuf_printf(sb, "%13u        ", ipg);
9690 		else
9691 			sbuf_printf(sb, "     disabled        ");
9692 
9693 		if (pace_tab[i])
9694 			sbuf_printf(sb, "%10u", pace_tab[i]);
9695 		else
9696 			sbuf_printf(sb, "  disabled");
9697 	}
9698 	rc = sbuf_finish(sb);
9699 done:
9700 	mtx_unlock(&sc->reg_lock);
9701 	sbuf_delete(sb);
9702 	return (rc);
9703 }
9704 
9705 static int
9706 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9707 {
9708 	struct adapter *sc = arg1;
9709 	struct sbuf *sb;
9710 	int rc, i, j;
9711 	uint64_t *p0, *p1;
9712 	struct lb_port_stats s[2];
9713 	static const char *stat_name[] = {
9714 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9715 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9716 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9717 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9718 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9719 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9720 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9721 	};
9722 
9723 	rc = sysctl_wire_old_buffer(req, 0);
9724 	if (rc != 0)
9725 		return (rc);
9726 
9727 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9728 	if (sb == NULL)
9729 		return (ENOMEM);
9730 
9731 	memset(s, 0, sizeof(s));
9732 
9733 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9734 		mtx_lock(&sc->reg_lock);
9735 		if (hw_off_limits(sc))
9736 			rc = ENXIO;
9737 		else {
9738 			t4_get_lb_stats(sc, i, &s[0]);
9739 			t4_get_lb_stats(sc, i + 1, &s[1]);
9740 		}
9741 		mtx_unlock(&sc->reg_lock);
9742 		if (rc != 0)
9743 			break;
9744 
9745 		p0 = &s[0].octets;
9746 		p1 = &s[1].octets;
9747 		sbuf_printf(sb, "%s                       Loopback %u"
9748 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9749 
9750 		for (j = 0; j < nitems(stat_name); j++)
9751 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9752 				   *p0++, *p1++);
9753 	}
9754 
9755 	rc = sbuf_finish(sb);
9756 	sbuf_delete(sb);
9757 
9758 	return (rc);
9759 }
9760 
9761 static int
9762 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9763 {
9764 	int rc = 0;
9765 	struct port_info *pi = arg1;
9766 	struct link_config *lc = &pi->link_cfg;
9767 	struct sbuf *sb;
9768 
9769 	rc = sysctl_wire_old_buffer(req, 0);
9770 	if (rc != 0)
9771 		return(rc);
9772 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9773 	if (sb == NULL)
9774 		return (ENOMEM);
9775 
9776 	if (lc->link_ok || lc->link_down_rc == 255)
9777 		sbuf_printf(sb, "n/a");
9778 	else
9779 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9780 
9781 	rc = sbuf_finish(sb);
9782 	sbuf_delete(sb);
9783 
9784 	return (rc);
9785 }
9786 
9787 struct mem_desc {
9788 	u_int base;
9789 	u_int limit;
9790 	u_int idx;
9791 };
9792 
9793 static int
9794 mem_desc_cmp(const void *a, const void *b)
9795 {
9796 	const u_int v1 = ((const struct mem_desc *)a)->base;
9797 	const u_int v2 = ((const struct mem_desc *)b)->base;
9798 
9799 	if (v1 < v2)
9800 		return (-1);
9801 	else if (v1 > v2)
9802 		return (1);
9803 
9804 	return (0);
9805 }
9806 
9807 static void
9808 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9809     unsigned int to)
9810 {
9811 	unsigned int size;
9812 
9813 	if (from == to)
9814 		return;
9815 
9816 	size = to - from + 1;
9817 	if (size == 0)
9818 		return;
9819 
9820 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9821 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9822 }
9823 
9824 static int
9825 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9826 {
9827 	struct adapter *sc = arg1;
9828 	struct sbuf *sb;
9829 	int rc, i, n;
9830 	uint32_t lo, hi, used, free, alloc;
9831 	static const char *memory[] = {
9832 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9833 	};
9834 	static const char *region[] = {
9835 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9836 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9837 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9838 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9839 		"RQUDP region:", "PBL region:", "TXPBL region:",
9840 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9841 		"ULPTX state:", "On-chip queues:",
9842 	};
9843 	struct mem_desc avail[4];
9844 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9845 	struct mem_desc *md = mem;
9846 
9847 	rc = sysctl_wire_old_buffer(req, 0);
9848 	if (rc != 0)
9849 		return (rc);
9850 
9851 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9852 	if (sb == NULL)
9853 		return (ENOMEM);
9854 
9855 	for (i = 0; i < nitems(mem); i++) {
9856 		mem[i].limit = 0;
9857 		mem[i].idx = i;
9858 	}
9859 
9860 	mtx_lock(&sc->reg_lock);
9861 	if (hw_off_limits(sc)) {
9862 		rc = ENXIO;
9863 		goto done;
9864 	}
9865 
9866 	/* Find and sort the populated memory ranges */
9867 	i = 0;
9868 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9869 	if (lo & F_EDRAM0_ENABLE) {
9870 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9871 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9872 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9873 		avail[i].idx = 0;
9874 		i++;
9875 	}
9876 	if (lo & F_EDRAM1_ENABLE) {
9877 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9878 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9879 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9880 		avail[i].idx = 1;
9881 		i++;
9882 	}
9883 	if (lo & F_EXT_MEM_ENABLE) {
9884 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9885 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9886 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9887 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9888 		i++;
9889 	}
9890 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9891 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9892 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9893 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9894 		avail[i].idx = 4;
9895 		i++;
9896 	}
9897 	if (is_t6(sc) && lo & F_HMA_MUX) {
9898 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9899 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9900 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9901 		avail[i].idx = 5;
9902 		i++;
9903 	}
9904 	MPASS(i <= nitems(avail));
9905 	if (!i)                                    /* no memory available */
9906 		goto done;
9907 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9908 
9909 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9910 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9911 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9912 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9913 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9914 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9915 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9916 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9917 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9918 
9919 	/* the next few have explicit upper bounds */
9920 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9921 	md->limit = md->base - 1 +
9922 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9923 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9924 	md++;
9925 
9926 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9927 	md->limit = md->base - 1 +
9928 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9929 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9930 	md++;
9931 
9932 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9933 		if (chip_id(sc) <= CHELSIO_T5)
9934 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9935 		else
9936 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9937 		md->limit = 0;
9938 	} else {
9939 		md->base = 0;
9940 		md->idx = nitems(region);  /* hide it */
9941 	}
9942 	md++;
9943 
9944 #define ulp_region(reg) \
9945 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9946 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9947 
9948 	ulp_region(RX_ISCSI);
9949 	ulp_region(RX_TDDP);
9950 	ulp_region(TX_TPT);
9951 	ulp_region(RX_STAG);
9952 	ulp_region(RX_RQ);
9953 	ulp_region(RX_RQUDP);
9954 	ulp_region(RX_PBL);
9955 	ulp_region(TX_PBL);
9956 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9957 		ulp_region(RX_TLS_KEY);
9958 	}
9959 #undef ulp_region
9960 
9961 	md->base = 0;
9962 	if (is_t4(sc))
9963 		md->idx = nitems(region);
9964 	else {
9965 		uint32_t size = 0;
9966 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9967 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9968 
9969 		if (is_t5(sc)) {
9970 			if (sge_ctrl & F_VFIFO_ENABLE)
9971 				size = fifo_size << 2;
9972 		} else
9973 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9974 
9975 		if (size) {
9976 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9977 			md->limit = md->base + size - 1;
9978 		} else
9979 			md->idx = nitems(region);
9980 	}
9981 	md++;
9982 
9983 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9984 	md->limit = 0;
9985 	md++;
9986 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9987 	md->limit = 0;
9988 	md++;
9989 
9990 	md->base = sc->vres.ocq.start;
9991 	if (sc->vres.ocq.size)
9992 		md->limit = md->base + sc->vres.ocq.size - 1;
9993 	else
9994 		md->idx = nitems(region);  /* hide it */
9995 	md++;
9996 
9997 	/* add any address-space holes, there can be up to 3 */
9998 	for (n = 0; n < i - 1; n++)
9999 		if (avail[n].limit < avail[n + 1].base)
10000 			(md++)->base = avail[n].limit;
10001 	if (avail[n].limit)
10002 		(md++)->base = avail[n].limit;
10003 
10004 	n = md - mem;
10005 	MPASS(n <= nitems(mem));
10006 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10007 
10008 	for (lo = 0; lo < i; lo++)
10009 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10010 				avail[lo].limit - 1);
10011 
10012 	sbuf_printf(sb, "\n");
10013 	for (i = 0; i < n; i++) {
10014 		if (mem[i].idx >= nitems(region))
10015 			continue;                        /* skip holes */
10016 		if (!mem[i].limit)
10017 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10018 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10019 				mem[i].limit);
10020 	}
10021 
10022 	sbuf_printf(sb, "\n");
10023 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10024 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10025 	mem_region_show(sb, "uP RAM:", lo, hi);
10026 
10027 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10028 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10029 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10030 
10031 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10032 	for (i = 0, free = 0; i < 2; i++)
10033 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10034 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10035 		   G_PMRXMAXPAGE(lo), free,
10036 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10037 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10038 
10039 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10040 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10041 	for (i = 0, free = 0; i < 4; i++)
10042 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10043 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10044 		   G_PMTXMAXPAGE(lo), free,
10045 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10046 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10047 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10048 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10049 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10050 
10051 	for (i = 0; i < 4; i++) {
10052 		if (chip_id(sc) > CHELSIO_T5)
10053 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10054 		else
10055 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10056 		if (is_t5(sc)) {
10057 			used = G_T5_USED(lo);
10058 			alloc = G_T5_ALLOC(lo);
10059 		} else {
10060 			used = G_USED(lo);
10061 			alloc = G_ALLOC(lo);
10062 		}
10063 		/* For T6 these are MAC buffer groups */
10064 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10065 		    i, used, alloc);
10066 	}
10067 	for (i = 0; i < sc->chip_params->nchan; i++) {
10068 		if (chip_id(sc) > CHELSIO_T5)
10069 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10070 		else
10071 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10072 		if (is_t5(sc)) {
10073 			used = G_T5_USED(lo);
10074 			alloc = G_T5_ALLOC(lo);
10075 		} else {
10076 			used = G_USED(lo);
10077 			alloc = G_ALLOC(lo);
10078 		}
10079 		/* For T6 these are MAC buffer groups */
10080 		sbuf_printf(sb,
10081 		    "\nLoopback %d using %u pages out of %u allocated",
10082 		    i, used, alloc);
10083 	}
10084 done:
10085 	mtx_unlock(&sc->reg_lock);
10086 	if (rc == 0)
10087 		rc = sbuf_finish(sb);
10088 	sbuf_delete(sb);
10089 	return (rc);
10090 }
10091 
10092 static inline void
10093 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10094 {
10095 	*mask = x | y;
10096 	y = htobe64(y);
10097 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10098 }
10099 
10100 static int
10101 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10102 {
10103 	struct adapter *sc = arg1;
10104 	struct sbuf *sb;
10105 	int rc, i;
10106 
10107 	MPASS(chip_id(sc) <= CHELSIO_T5);
10108 
10109 	rc = sysctl_wire_old_buffer(req, 0);
10110 	if (rc != 0)
10111 		return (rc);
10112 
10113 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10114 	if (sb == NULL)
10115 		return (ENOMEM);
10116 
10117 	sbuf_printf(sb,
10118 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10119 	    "  VF              Replication             P0 P1 P2 P3  ML");
10120 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10121 		uint64_t tcamx, tcamy, mask;
10122 		uint32_t cls_lo, cls_hi;
10123 		uint8_t addr[ETHER_ADDR_LEN];
10124 
10125 		mtx_lock(&sc->reg_lock);
10126 		if (hw_off_limits(sc))
10127 			rc = ENXIO;
10128 		else {
10129 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10130 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10131 		}
10132 		mtx_unlock(&sc->reg_lock);
10133 		if (rc != 0)
10134 			break;
10135 		if (tcamx & tcamy)
10136 			continue;
10137 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10138 		mtx_lock(&sc->reg_lock);
10139 		if (hw_off_limits(sc))
10140 			rc = ENXIO;
10141 		else {
10142 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10143 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10144 		}
10145 		mtx_unlock(&sc->reg_lock);
10146 		if (rc != 0)
10147 			break;
10148 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10149 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10150 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10151 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10152 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10153 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10154 
10155 		if (cls_lo & F_REPLICATE) {
10156 			struct fw_ldst_cmd ldst_cmd;
10157 
10158 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10159 			ldst_cmd.op_to_addrspace =
10160 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10161 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10162 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10163 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10164 			ldst_cmd.u.mps.rplc.fid_idx =
10165 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10166 				V_FW_LDST_CMD_IDX(i));
10167 
10168 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10169 			    "t4mps");
10170 			if (rc)
10171 				break;
10172 			if (hw_off_limits(sc))
10173 				rc = ENXIO;
10174 			else
10175 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10176 				    sizeof(ldst_cmd), &ldst_cmd);
10177 			end_synchronized_op(sc, 0);
10178 			if (rc != 0)
10179 				break;
10180 			else {
10181 				sbuf_printf(sb, " %08x %08x %08x %08x",
10182 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10183 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10184 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10185 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10186 			}
10187 		} else
10188 			sbuf_printf(sb, "%36s", "");
10189 
10190 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10191 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10192 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10193 	}
10194 
10195 	if (rc)
10196 		(void) sbuf_finish(sb);
10197 	else
10198 		rc = sbuf_finish(sb);
10199 	sbuf_delete(sb);
10200 
10201 	return (rc);
10202 }
10203 
10204 static int
10205 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10206 {
10207 	struct adapter *sc = arg1;
10208 	struct sbuf *sb;
10209 	int rc, i;
10210 
10211 	MPASS(chip_id(sc) > CHELSIO_T5);
10212 
10213 	rc = sysctl_wire_old_buffer(req, 0);
10214 	if (rc != 0)
10215 		return (rc);
10216 
10217 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10218 	if (sb == NULL)
10219 		return (ENOMEM);
10220 
10221 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10222 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10223 	    "                           Replication"
10224 	    "                                    P0 P1 P2 P3  ML\n");
10225 
10226 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10227 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10228 		uint16_t ivlan;
10229 		uint64_t tcamx, tcamy, val, mask;
10230 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10231 		uint8_t addr[ETHER_ADDR_LEN];
10232 
10233 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10234 		if (i < 256)
10235 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10236 		else
10237 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10238 		mtx_lock(&sc->reg_lock);
10239 		if (hw_off_limits(sc))
10240 			rc = ENXIO;
10241 		else {
10242 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10243 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10244 			tcamy = G_DMACH(val) << 32;
10245 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10246 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10247 		}
10248 		mtx_unlock(&sc->reg_lock);
10249 		if (rc != 0)
10250 			break;
10251 
10252 		lookup_type = G_DATALKPTYPE(data2);
10253 		port_num = G_DATAPORTNUM(data2);
10254 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10255 			/* Inner header VNI */
10256 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10257 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10258 			dip_hit = data2 & F_DATADIPHIT;
10259 			vlan_vld = 0;
10260 		} else {
10261 			vniy = 0;
10262 			dip_hit = 0;
10263 			vlan_vld = data2 & F_DATAVIDH2;
10264 			ivlan = G_VIDL(val);
10265 		}
10266 
10267 		ctl |= V_CTLXYBITSEL(1);
10268 		mtx_lock(&sc->reg_lock);
10269 		if (hw_off_limits(sc))
10270 			rc = ENXIO;
10271 		else {
10272 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10273 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10274 			tcamx = G_DMACH(val) << 32;
10275 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10276 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10277 		}
10278 		mtx_unlock(&sc->reg_lock);
10279 		if (rc != 0)
10280 			break;
10281 
10282 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10283 			/* Inner header VNI mask */
10284 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10285 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10286 		} else
10287 			vnix = 0;
10288 
10289 		if (tcamx & tcamy)
10290 			continue;
10291 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10292 
10293 		mtx_lock(&sc->reg_lock);
10294 		if (hw_off_limits(sc))
10295 			rc = ENXIO;
10296 		else {
10297 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10298 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10299 		}
10300 		mtx_unlock(&sc->reg_lock);
10301 		if (rc != 0)
10302 			break;
10303 
10304 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10305 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10306 			    "%012jx %06x %06x    -    -   %3c"
10307 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10308 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10309 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10310 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10311 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10312 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10313 		} else {
10314 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10315 			    "%012jx    -       -   ", i, addr[0], addr[1],
10316 			    addr[2], addr[3], addr[4], addr[5],
10317 			    (uintmax_t)mask);
10318 
10319 			if (vlan_vld)
10320 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10321 			else
10322 				sbuf_printf(sb, "  -    N     ");
10323 
10324 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10325 			    lookup_type ? 'I' : 'O', port_num,
10326 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10327 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10328 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10329 		}
10330 
10331 
10332 		if (cls_lo & F_T6_REPLICATE) {
10333 			struct fw_ldst_cmd ldst_cmd;
10334 
10335 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10336 			ldst_cmd.op_to_addrspace =
10337 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10338 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10339 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10340 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10341 			ldst_cmd.u.mps.rplc.fid_idx =
10342 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10343 				V_FW_LDST_CMD_IDX(i));
10344 
10345 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10346 			    "t6mps");
10347 			if (rc)
10348 				break;
10349 			if (hw_off_limits(sc))
10350 				rc = ENXIO;
10351 			else
10352 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10353 				    sizeof(ldst_cmd), &ldst_cmd);
10354 			end_synchronized_op(sc, 0);
10355 			if (rc != 0)
10356 				break;
10357 			else {
10358 				sbuf_printf(sb, " %08x %08x %08x %08x"
10359 				    " %08x %08x %08x %08x",
10360 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10361 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10362 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10363 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10364 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10365 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10366 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10367 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10368 			}
10369 		} else
10370 			sbuf_printf(sb, "%72s", "");
10371 
10372 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10373 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10374 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10375 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10376 	}
10377 
10378 	if (rc)
10379 		(void) sbuf_finish(sb);
10380 	else
10381 		rc = sbuf_finish(sb);
10382 	sbuf_delete(sb);
10383 
10384 	return (rc);
10385 }
10386 
10387 static int
10388 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10389 {
10390 	struct adapter *sc = arg1;
10391 	struct sbuf *sb;
10392 	int rc;
10393 	uint16_t mtus[NMTUS];
10394 
10395 	rc = sysctl_wire_old_buffer(req, 0);
10396 	if (rc != 0)
10397 		return (rc);
10398 
10399 	mtx_lock(&sc->reg_lock);
10400 	if (hw_off_limits(sc))
10401 		rc = ENXIO;
10402 	else
10403 		t4_read_mtu_tbl(sc, mtus, NULL);
10404 	mtx_unlock(&sc->reg_lock);
10405 	if (rc != 0)
10406 		return (rc);
10407 
10408 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10409 	if (sb == NULL)
10410 		return (ENOMEM);
10411 
10412 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10413 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10414 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10415 	    mtus[14], mtus[15]);
10416 
10417 	rc = sbuf_finish(sb);
10418 	sbuf_delete(sb);
10419 
10420 	return (rc);
10421 }
10422 
10423 static int
10424 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10425 {
10426 	struct adapter *sc = arg1;
10427 	struct sbuf *sb;
10428 	int rc, i;
10429 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10430 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10431 	static const char *tx_stats[MAX_PM_NSTATS] = {
10432 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10433 		"Tx FIFO wait", NULL, "Tx latency"
10434 	};
10435 	static const char *rx_stats[MAX_PM_NSTATS] = {
10436 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10437 		"Rx FIFO wait", NULL, "Rx latency"
10438 	};
10439 
10440 	rc = sysctl_wire_old_buffer(req, 0);
10441 	if (rc != 0)
10442 		return (rc);
10443 
10444 	mtx_lock(&sc->reg_lock);
10445 	if (hw_off_limits(sc))
10446 		rc = ENXIO;
10447 	else {
10448 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10449 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10450 	}
10451 	mtx_unlock(&sc->reg_lock);
10452 	if (rc != 0)
10453 		return (rc);
10454 
10455 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10456 	if (sb == NULL)
10457 		return (ENOMEM);
10458 
10459 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10460 	for (i = 0; i < 4; i++) {
10461 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10462 		    tx_cyc[i]);
10463 	}
10464 
10465 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10466 	for (i = 0; i < 4; i++) {
10467 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10468 		    rx_cyc[i]);
10469 	}
10470 
10471 	if (chip_id(sc) > CHELSIO_T5) {
10472 		sbuf_printf(sb,
10473 		    "\n              Total wait      Total occupancy");
10474 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10475 		    tx_cyc[i]);
10476 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10477 		    rx_cyc[i]);
10478 
10479 		i += 2;
10480 		MPASS(i < nitems(tx_stats));
10481 
10482 		sbuf_printf(sb,
10483 		    "\n                   Reads           Total wait");
10484 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10485 		    tx_cyc[i]);
10486 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10487 		    rx_cyc[i]);
10488 	}
10489 
10490 	rc = sbuf_finish(sb);
10491 	sbuf_delete(sb);
10492 
10493 	return (rc);
10494 }
10495 
10496 static int
10497 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10498 {
10499 	struct adapter *sc = arg1;
10500 	struct sbuf *sb;
10501 	int rc;
10502 	struct tp_rdma_stats stats;
10503 
10504 	rc = sysctl_wire_old_buffer(req, 0);
10505 	if (rc != 0)
10506 		return (rc);
10507 
10508 	mtx_lock(&sc->reg_lock);
10509 	if (hw_off_limits(sc))
10510 		rc = ENXIO;
10511 	else
10512 		t4_tp_get_rdma_stats(sc, &stats, 0);
10513 	mtx_unlock(&sc->reg_lock);
10514 	if (rc != 0)
10515 		return (rc);
10516 
10517 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10518 	if (sb == NULL)
10519 		return (ENOMEM);
10520 
10521 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10522 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10523 
10524 	rc = sbuf_finish(sb);
10525 	sbuf_delete(sb);
10526 
10527 	return (rc);
10528 }
10529 
10530 static int
10531 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10532 {
10533 	struct adapter *sc = arg1;
10534 	struct sbuf *sb;
10535 	int rc;
10536 	struct tp_tcp_stats v4, v6;
10537 
10538 	rc = sysctl_wire_old_buffer(req, 0);
10539 	if (rc != 0)
10540 		return (rc);
10541 
10542 	mtx_lock(&sc->reg_lock);
10543 	if (hw_off_limits(sc))
10544 		rc = ENXIO;
10545 	else
10546 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10547 	mtx_unlock(&sc->reg_lock);
10548 	if (rc != 0)
10549 		return (rc);
10550 
10551 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10552 	if (sb == NULL)
10553 		return (ENOMEM);
10554 
10555 	sbuf_printf(sb,
10556 	    "                                IP                 IPv6\n");
10557 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10558 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10559 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10560 	    v4.tcp_in_segs, v6.tcp_in_segs);
10561 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10562 	    v4.tcp_out_segs, v6.tcp_out_segs);
10563 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10564 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10565 
10566 	rc = sbuf_finish(sb);
10567 	sbuf_delete(sb);
10568 
10569 	return (rc);
10570 }
10571 
10572 static int
10573 sysctl_tids(SYSCTL_HANDLER_ARGS)
10574 {
10575 	struct adapter *sc = arg1;
10576 	struct sbuf *sb;
10577 	int rc;
10578 	uint32_t x, y;
10579 	struct tid_info *t = &sc->tids;
10580 
10581 	rc = sysctl_wire_old_buffer(req, 0);
10582 	if (rc != 0)
10583 		return (rc);
10584 
10585 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10586 	if (sb == NULL)
10587 		return (ENOMEM);
10588 
10589 	if (t->natids) {
10590 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10591 		    t->atids_in_use);
10592 	}
10593 
10594 	if (t->nhpftids) {
10595 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10596 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10597 	}
10598 
10599 	if (t->ntids) {
10600 		bool hashen = false;
10601 
10602 		mtx_lock(&sc->reg_lock);
10603 		if (hw_off_limits(sc))
10604 			rc = ENXIO;
10605 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10606 			hashen = true;
10607 			if (chip_id(sc) <= CHELSIO_T5) {
10608 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10609 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10610 			} else {
10611 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10612 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10613 			}
10614 		}
10615 		mtx_unlock(&sc->reg_lock);
10616 		if (rc != 0)
10617 			goto done;
10618 
10619 		sbuf_printf(sb, "TID range: ");
10620 		if (hashen) {
10621 			if (x)
10622 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10623 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10624 		} else {
10625 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10626 			    t->ntids - 1);
10627 		}
10628 		sbuf_printf(sb, ", in use: %u\n",
10629 		    atomic_load_acq_int(&t->tids_in_use));
10630 	}
10631 
10632 	if (t->nstids) {
10633 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10634 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10635 	}
10636 
10637 	if (t->nftids) {
10638 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10639 		    t->ftid_end, t->ftids_in_use);
10640 	}
10641 
10642 	if (t->netids) {
10643 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10644 		    t->etid_base + t->netids - 1, t->etids_in_use);
10645 	}
10646 
10647 	mtx_lock(&sc->reg_lock);
10648 	if (hw_off_limits(sc))
10649 		rc = ENXIO;
10650 	else {
10651 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10652 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10653 	}
10654 	mtx_unlock(&sc->reg_lock);
10655 	if (rc != 0)
10656 		goto done;
10657 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10658 done:
10659 	if (rc == 0)
10660 		rc = sbuf_finish(sb);
10661 	else
10662 		(void)sbuf_finish(sb);
10663 	sbuf_delete(sb);
10664 
10665 	return (rc);
10666 }
10667 
10668 static int
10669 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10670 {
10671 	struct adapter *sc = arg1;
10672 	struct sbuf *sb;
10673 	int rc;
10674 	struct tp_err_stats stats;
10675 
10676 	rc = sysctl_wire_old_buffer(req, 0);
10677 	if (rc != 0)
10678 		return (rc);
10679 
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 = sysctl_wire_old_buffer(req, 0);
10758 	if (rc != 0)
10759 		return(rc);
10760 
10761 	mtx_lock(&sc->reg_lock);
10762 	if (hw_off_limits(sc))
10763 		rc = ENXIO;
10764 	else
10765 		t4_tp_get_tnl_stats(sc, &stats, 1);
10766 	mtx_unlock(&sc->reg_lock);
10767 	if (rc != 0)
10768 		return (rc);
10769 
10770 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10771 	if (sb == NULL)
10772 		return (ENOMEM);
10773 
10774 	if (sc->chip_params->nchan > 2) {
10775 		sbuf_printf(sb, "           channel 0  channel 1"
10776 		    "  channel 2  channel 3\n");
10777 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10778 		    stats.out_pkt[0], stats.out_pkt[1],
10779 		    stats.out_pkt[2], stats.out_pkt[3]);
10780 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10781 		    stats.in_pkt[0], stats.in_pkt[1],
10782 		    stats.in_pkt[2], stats.in_pkt[3]);
10783 	} else {
10784 		sbuf_printf(sb, "           channel 0  channel 1\n");
10785 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10786 		    stats.out_pkt[0], stats.out_pkt[1]);
10787 		sbuf_printf(sb, "InPkts:   %10u %10u",
10788 		    stats.in_pkt[0], stats.in_pkt[1]);
10789 	}
10790 
10791 	rc = sbuf_finish(sb);
10792 	sbuf_delete(sb);
10793 
10794 	return (rc);
10795 }
10796 
10797 static int
10798 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10799 {
10800 	struct adapter *sc = arg1;
10801 	struct tp_params *tpp = &sc->params.tp;
10802 	u_int mask;
10803 	int rc;
10804 
10805 	mask = tpp->la_mask >> 16;
10806 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10807 	if (rc != 0 || req->newptr == NULL)
10808 		return (rc);
10809 	if (mask > 0xffff)
10810 		return (EINVAL);
10811 	mtx_lock(&sc->reg_lock);
10812 	if (hw_off_limits(sc))
10813 		rc = ENXIO;
10814 	else {
10815 		tpp->la_mask = mask << 16;
10816 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10817 		    tpp->la_mask);
10818 	}
10819 	mtx_unlock(&sc->reg_lock);
10820 
10821 	return (rc);
10822 }
10823 
10824 struct field_desc {
10825 	const char *name;
10826 	u_int start;
10827 	u_int width;
10828 };
10829 
10830 static void
10831 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10832 {
10833 	char buf[32];
10834 	int line_size = 0;
10835 
10836 	while (f->name) {
10837 		uint64_t mask = (1ULL << f->width) - 1;
10838 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10839 		    ((uintmax_t)v >> f->start) & mask);
10840 
10841 		if (line_size + len >= 79) {
10842 			line_size = 8;
10843 			sbuf_printf(sb, "\n        ");
10844 		}
10845 		sbuf_printf(sb, "%s ", buf);
10846 		line_size += len + 1;
10847 		f++;
10848 	}
10849 	sbuf_printf(sb, "\n");
10850 }
10851 
10852 static const struct field_desc tp_la0[] = {
10853 	{ "RcfOpCodeOut", 60, 4 },
10854 	{ "State", 56, 4 },
10855 	{ "WcfState", 52, 4 },
10856 	{ "RcfOpcSrcOut", 50, 2 },
10857 	{ "CRxError", 49, 1 },
10858 	{ "ERxError", 48, 1 },
10859 	{ "SanityFailed", 47, 1 },
10860 	{ "SpuriousMsg", 46, 1 },
10861 	{ "FlushInputMsg", 45, 1 },
10862 	{ "FlushInputCpl", 44, 1 },
10863 	{ "RssUpBit", 43, 1 },
10864 	{ "RssFilterHit", 42, 1 },
10865 	{ "Tid", 32, 10 },
10866 	{ "InitTcb", 31, 1 },
10867 	{ "LineNumber", 24, 7 },
10868 	{ "Emsg", 23, 1 },
10869 	{ "EdataOut", 22, 1 },
10870 	{ "Cmsg", 21, 1 },
10871 	{ "CdataOut", 20, 1 },
10872 	{ "EreadPdu", 19, 1 },
10873 	{ "CreadPdu", 18, 1 },
10874 	{ "TunnelPkt", 17, 1 },
10875 	{ "RcfPeerFin", 16, 1 },
10876 	{ "RcfReasonOut", 12, 4 },
10877 	{ "TxCchannel", 10, 2 },
10878 	{ "RcfTxChannel", 8, 2 },
10879 	{ "RxEchannel", 6, 2 },
10880 	{ "RcfRxChannel", 5, 1 },
10881 	{ "RcfDataOutSrdy", 4, 1 },
10882 	{ "RxDvld", 3, 1 },
10883 	{ "RxOoDvld", 2, 1 },
10884 	{ "RxCongestion", 1, 1 },
10885 	{ "TxCongestion", 0, 1 },
10886 	{ NULL }
10887 };
10888 
10889 static const struct field_desc tp_la1[] = {
10890 	{ "CplCmdIn", 56, 8 },
10891 	{ "CplCmdOut", 48, 8 },
10892 	{ "ESynOut", 47, 1 },
10893 	{ "EAckOut", 46, 1 },
10894 	{ "EFinOut", 45, 1 },
10895 	{ "ERstOut", 44, 1 },
10896 	{ "SynIn", 43, 1 },
10897 	{ "AckIn", 42, 1 },
10898 	{ "FinIn", 41, 1 },
10899 	{ "RstIn", 40, 1 },
10900 	{ "DataIn", 39, 1 },
10901 	{ "DataInVld", 38, 1 },
10902 	{ "PadIn", 37, 1 },
10903 	{ "RxBufEmpty", 36, 1 },
10904 	{ "RxDdp", 35, 1 },
10905 	{ "RxFbCongestion", 34, 1 },
10906 	{ "TxFbCongestion", 33, 1 },
10907 	{ "TxPktSumSrdy", 32, 1 },
10908 	{ "RcfUlpType", 28, 4 },
10909 	{ "Eread", 27, 1 },
10910 	{ "Ebypass", 26, 1 },
10911 	{ "Esave", 25, 1 },
10912 	{ "Static0", 24, 1 },
10913 	{ "Cread", 23, 1 },
10914 	{ "Cbypass", 22, 1 },
10915 	{ "Csave", 21, 1 },
10916 	{ "CPktOut", 20, 1 },
10917 	{ "RxPagePoolFull", 18, 2 },
10918 	{ "RxLpbkPkt", 17, 1 },
10919 	{ "TxLpbkPkt", 16, 1 },
10920 	{ "RxVfValid", 15, 1 },
10921 	{ "SynLearned", 14, 1 },
10922 	{ "SetDelEntry", 13, 1 },
10923 	{ "SetInvEntry", 12, 1 },
10924 	{ "CpcmdDvld", 11, 1 },
10925 	{ "CpcmdSave", 10, 1 },
10926 	{ "RxPstructsFull", 8, 2 },
10927 	{ "EpcmdDvld", 7, 1 },
10928 	{ "EpcmdFlush", 6, 1 },
10929 	{ "EpcmdTrimPrefix", 5, 1 },
10930 	{ "EpcmdTrimPostfix", 4, 1 },
10931 	{ "ERssIp4Pkt", 3, 1 },
10932 	{ "ERssIp6Pkt", 2, 1 },
10933 	{ "ERssTcpUdpPkt", 1, 1 },
10934 	{ "ERssFceFipPkt", 0, 1 },
10935 	{ NULL }
10936 };
10937 
10938 static const struct field_desc tp_la2[] = {
10939 	{ "CplCmdIn", 56, 8 },
10940 	{ "MpsVfVld", 55, 1 },
10941 	{ "MpsPf", 52, 3 },
10942 	{ "MpsVf", 44, 8 },
10943 	{ "SynIn", 43, 1 },
10944 	{ "AckIn", 42, 1 },
10945 	{ "FinIn", 41, 1 },
10946 	{ "RstIn", 40, 1 },
10947 	{ "DataIn", 39, 1 },
10948 	{ "DataInVld", 38, 1 },
10949 	{ "PadIn", 37, 1 },
10950 	{ "RxBufEmpty", 36, 1 },
10951 	{ "RxDdp", 35, 1 },
10952 	{ "RxFbCongestion", 34, 1 },
10953 	{ "TxFbCongestion", 33, 1 },
10954 	{ "TxPktSumSrdy", 32, 1 },
10955 	{ "RcfUlpType", 28, 4 },
10956 	{ "Eread", 27, 1 },
10957 	{ "Ebypass", 26, 1 },
10958 	{ "Esave", 25, 1 },
10959 	{ "Static0", 24, 1 },
10960 	{ "Cread", 23, 1 },
10961 	{ "Cbypass", 22, 1 },
10962 	{ "Csave", 21, 1 },
10963 	{ "CPktOut", 20, 1 },
10964 	{ "RxPagePoolFull", 18, 2 },
10965 	{ "RxLpbkPkt", 17, 1 },
10966 	{ "TxLpbkPkt", 16, 1 },
10967 	{ "RxVfValid", 15, 1 },
10968 	{ "SynLearned", 14, 1 },
10969 	{ "SetDelEntry", 13, 1 },
10970 	{ "SetInvEntry", 12, 1 },
10971 	{ "CpcmdDvld", 11, 1 },
10972 	{ "CpcmdSave", 10, 1 },
10973 	{ "RxPstructsFull", 8, 2 },
10974 	{ "EpcmdDvld", 7, 1 },
10975 	{ "EpcmdFlush", 6, 1 },
10976 	{ "EpcmdTrimPrefix", 5, 1 },
10977 	{ "EpcmdTrimPostfix", 4, 1 },
10978 	{ "ERssIp4Pkt", 3, 1 },
10979 	{ "ERssIp6Pkt", 2, 1 },
10980 	{ "ERssTcpUdpPkt", 1, 1 },
10981 	{ "ERssFceFipPkt", 0, 1 },
10982 	{ NULL }
10983 };
10984 
10985 static void
10986 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10987 {
10988 
10989 	field_desc_show(sb, *p, tp_la0);
10990 }
10991 
10992 static void
10993 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10994 {
10995 
10996 	if (idx)
10997 		sbuf_printf(sb, "\n");
10998 	field_desc_show(sb, p[0], tp_la0);
10999 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11000 		field_desc_show(sb, p[1], tp_la0);
11001 }
11002 
11003 static void
11004 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
11005 {
11006 
11007 	if (idx)
11008 		sbuf_printf(sb, "\n");
11009 	field_desc_show(sb, p[0], tp_la0);
11010 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
11011 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
11012 }
11013 
11014 static int
11015 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
11016 {
11017 	struct adapter *sc = arg1;
11018 	struct sbuf *sb;
11019 	uint64_t *buf, *p;
11020 	int rc;
11021 	u_int i, inc;
11022 	void (*show_func)(struct sbuf *, uint64_t *, int);
11023 
11024 	rc = sysctl_wire_old_buffer(req, 0);
11025 	if (rc != 0)
11026 		return (rc);
11027 
11028 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11029 	if (sb == NULL)
11030 		return (ENOMEM);
11031 
11032 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11033 
11034 	mtx_lock(&sc->reg_lock);
11035 	if (hw_off_limits(sc))
11036 		rc = ENXIO;
11037 	else {
11038 		t4_tp_read_la(sc, buf, NULL);
11039 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11040 		case 2:
11041 			inc = 2;
11042 			show_func = tp_la_show2;
11043 			break;
11044 		case 3:
11045 			inc = 2;
11046 			show_func = tp_la_show3;
11047 			break;
11048 		default:
11049 			inc = 1;
11050 			show_func = tp_la_show;
11051 		}
11052 	}
11053 	mtx_unlock(&sc->reg_lock);
11054 	if (rc != 0)
11055 		goto done;
11056 
11057 	p = buf;
11058 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11059 		(*show_func)(sb, p, i);
11060 	rc = sbuf_finish(sb);
11061 done:
11062 	sbuf_delete(sb);
11063 	free(buf, M_CXGBE);
11064 	return (rc);
11065 }
11066 
11067 static int
11068 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11069 {
11070 	struct adapter *sc = arg1;
11071 	struct sbuf *sb;
11072 	int rc;
11073 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11074 
11075 	rc = sysctl_wire_old_buffer(req, 0);
11076 	if (rc != 0)
11077 		return (rc);
11078 
11079 	mtx_lock(&sc->reg_lock);
11080 	if (hw_off_limits(sc))
11081 		rc = ENXIO;
11082 	else
11083 		t4_get_chan_txrate(sc, nrate, orate);
11084 	mtx_unlock(&sc->reg_lock);
11085 	if (rc != 0)
11086 		return (rc);
11087 
11088 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11089 	if (sb == NULL)
11090 		return (ENOMEM);
11091 
11092 	if (sc->chip_params->nchan > 2) {
11093 		sbuf_printf(sb, "              channel 0   channel 1"
11094 		    "   channel 2   channel 3\n");
11095 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11096 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11097 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11098 		    orate[0], orate[1], orate[2], orate[3]);
11099 	} else {
11100 		sbuf_printf(sb, "              channel 0   channel 1\n");
11101 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11102 		    nrate[0], nrate[1]);
11103 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11104 		    orate[0], orate[1]);
11105 	}
11106 
11107 	rc = sbuf_finish(sb);
11108 	sbuf_delete(sb);
11109 
11110 	return (rc);
11111 }
11112 
11113 static int
11114 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11115 {
11116 	struct adapter *sc = arg1;
11117 	struct sbuf *sb;
11118 	uint32_t *buf, *p;
11119 	int rc, i;
11120 
11121 	rc = sysctl_wire_old_buffer(req, 0);
11122 	if (rc != 0)
11123 		return (rc);
11124 
11125 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11126 	if (sb == NULL)
11127 		return (ENOMEM);
11128 
11129 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11130 	    M_ZERO | M_WAITOK);
11131 
11132 	mtx_lock(&sc->reg_lock);
11133 	if (hw_off_limits(sc))
11134 		rc = ENXIO;
11135 	else
11136 		t4_ulprx_read_la(sc, buf);
11137 	mtx_unlock(&sc->reg_lock);
11138 	if (rc != 0)
11139 		goto done;
11140 
11141 	p = buf;
11142 	sbuf_printf(sb, "      Pcmd        Type   Message"
11143 	    "                Data");
11144 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11145 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11146 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11147 	}
11148 	rc = sbuf_finish(sb);
11149 done:
11150 	sbuf_delete(sb);
11151 	free(buf, M_CXGBE);
11152 	return (rc);
11153 }
11154 
11155 static int
11156 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11157 {
11158 	struct adapter *sc = arg1;
11159 	struct sbuf *sb;
11160 	int rc;
11161 	uint32_t cfg, s1, s2;
11162 
11163 	MPASS(chip_id(sc) >= CHELSIO_T5);
11164 
11165 	rc = sysctl_wire_old_buffer(req, 0);
11166 	if (rc != 0)
11167 		return (rc);
11168 
11169 	mtx_lock(&sc->reg_lock);
11170 	if (hw_off_limits(sc))
11171 		rc = ENXIO;
11172 	else {
11173 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11174 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11175 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11176 	}
11177 	mtx_unlock(&sc->reg_lock);
11178 	if (rc != 0)
11179 		return (rc);
11180 
11181 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11182 	if (sb == NULL)
11183 		return (ENOMEM);
11184 
11185 	if (G_STATSOURCE_T5(cfg) == 7) {
11186 		int mode;
11187 
11188 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11189 		if (mode == 0)
11190 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11191 		else if (mode == 1)
11192 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11193 		else
11194 			sbuf_printf(sb, "unknown mode %d", mode);
11195 	}
11196 	rc = sbuf_finish(sb);
11197 	sbuf_delete(sb);
11198 
11199 	return (rc);
11200 }
11201 
11202 static int
11203 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11204 {
11205 	struct adapter *sc = arg1;
11206 	enum cpu_sets op = arg2;
11207 	cpuset_t cpuset;
11208 	struct sbuf *sb;
11209 	int i, rc;
11210 
11211 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11212 
11213 	CPU_ZERO(&cpuset);
11214 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11215 	if (rc != 0)
11216 		return (rc);
11217 
11218 	rc = sysctl_wire_old_buffer(req, 0);
11219 	if (rc != 0)
11220 		return (rc);
11221 
11222 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11223 	if (sb == NULL)
11224 		return (ENOMEM);
11225 
11226 	CPU_FOREACH(i)
11227 		sbuf_printf(sb, "%d ", i);
11228 	rc = sbuf_finish(sb);
11229 	sbuf_delete(sb);
11230 
11231 	return (rc);
11232 }
11233 
11234 static int
11235 sysctl_reset(SYSCTL_HANDLER_ARGS)
11236 {
11237 	struct adapter *sc = arg1;
11238 	u_int val;
11239 	int rc;
11240 
11241 	val = atomic_load_int(&sc->num_resets);
11242 	rc = sysctl_handle_int(oidp, &val, 0, req);
11243 	if (rc != 0 || req->newptr == NULL)
11244 		return (rc);
11245 
11246 	if (val == 0) {
11247 		/* Zero out the counter that tracks reset. */
11248 		atomic_store_int(&sc->num_resets, 0);
11249 		return (0);
11250 	}
11251 
11252 	if (val != 1)
11253 		return (EINVAL);	/* 0 or 1 are the only legal values */
11254 
11255 	if (hw_off_limits(sc))		/* harmless race */
11256 		return (EALREADY);
11257 
11258 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11259 	return (0);
11260 }
11261 
11262 #ifdef TCP_OFFLOAD
11263 static int
11264 sysctl_tls(SYSCTL_HANDLER_ARGS)
11265 {
11266 	struct adapter *sc = arg1;
11267 	int i, j, v, rc;
11268 	struct vi_info *vi;
11269 
11270 	v = sc->tt.tls;
11271 	rc = sysctl_handle_int(oidp, &v, 0, req);
11272 	if (rc != 0 || req->newptr == NULL)
11273 		return (rc);
11274 
11275 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11276 		return (ENOTSUP);
11277 
11278 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11279 	if (rc)
11280 		return (rc);
11281 	if (hw_off_limits(sc))
11282 		rc = ENXIO;
11283 	else {
11284 		sc->tt.tls = !!v;
11285 		for_each_port(sc, i) {
11286 			for_each_vi(sc->port[i], j, vi) {
11287 				if (vi->flags & VI_INIT_DONE)
11288 					t4_update_fl_bufsize(vi->ifp);
11289 			}
11290 		}
11291 	}
11292 	end_synchronized_op(sc, 0);
11293 
11294 	return (rc);
11295 
11296 }
11297 
11298 static void
11299 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11300 {
11301 	u_int rem = val % factor;
11302 
11303 	if (rem == 0)
11304 		snprintf(buf, len, "%u", val / factor);
11305 	else {
11306 		while (rem % 10 == 0)
11307 			rem /= 10;
11308 		snprintf(buf, len, "%u.%u", val / factor, rem);
11309 	}
11310 }
11311 
11312 static int
11313 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11314 {
11315 	struct adapter *sc = arg1;
11316 	char buf[16];
11317 	u_int res, re;
11318 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11319 
11320 	mtx_lock(&sc->reg_lock);
11321 	if (hw_off_limits(sc))
11322 		res = (u_int)-1;
11323 	else
11324 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11325 	mtx_unlock(&sc->reg_lock);
11326 	if (res == (u_int)-1)
11327 		return (ENXIO);
11328 
11329 	switch (arg2) {
11330 	case 0:
11331 		/* timer_tick */
11332 		re = G_TIMERRESOLUTION(res);
11333 		break;
11334 	case 1:
11335 		/* TCP timestamp tick */
11336 		re = G_TIMESTAMPRESOLUTION(res);
11337 		break;
11338 	case 2:
11339 		/* DACK tick */
11340 		re = G_DELAYEDACKRESOLUTION(res);
11341 		break;
11342 	default:
11343 		return (EDOOFUS);
11344 	}
11345 
11346 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11347 
11348 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11349 }
11350 
11351 static int
11352 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11353 {
11354 	struct adapter *sc = arg1;
11355 	int rc;
11356 	u_int dack_tmr, dack_re, v;
11357 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11358 
11359 	mtx_lock(&sc->reg_lock);
11360 	if (hw_off_limits(sc))
11361 		rc = ENXIO;
11362 	else {
11363 		rc = 0;
11364 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11365 		    A_TP_TIMER_RESOLUTION));
11366 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11367 	}
11368 	mtx_unlock(&sc->reg_lock);
11369 	if (rc != 0)
11370 		return (rc);
11371 
11372 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11373 
11374 	return (sysctl_handle_int(oidp, &v, 0, req));
11375 }
11376 
11377 static int
11378 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11379 {
11380 	struct adapter *sc = arg1;
11381 	int rc, reg = arg2;
11382 	u_int tre;
11383 	u_long tp_tick_us, v;
11384 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11385 
11386 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11387 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11388 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11389 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11390 
11391 	mtx_lock(&sc->reg_lock);
11392 	if (hw_off_limits(sc))
11393 		rc = ENXIO;
11394 	else {
11395 		rc = 0;
11396 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11397 		tp_tick_us = (cclk_ps << tre) / 1000000;
11398 		if (reg == A_TP_INIT_SRTT)
11399 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11400 		else
11401 			v = tp_tick_us * t4_read_reg(sc, reg);
11402 	}
11403 	mtx_unlock(&sc->reg_lock);
11404 	if (rc != 0)
11405 		return (rc);
11406 	else
11407 		return (sysctl_handle_long(oidp, &v, 0, req));
11408 }
11409 
11410 /*
11411  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11412  * passed to this function.
11413  */
11414 static int
11415 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11416 {
11417 	struct adapter *sc = arg1;
11418 	int rc, idx = arg2;
11419 	u_int v;
11420 
11421 	MPASS(idx >= 0 && idx <= 24);
11422 
11423 	mtx_lock(&sc->reg_lock);
11424 	if (hw_off_limits(sc))
11425 		rc = ENXIO;
11426 	else {
11427 		rc = 0;
11428 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11429 	}
11430 	mtx_unlock(&sc->reg_lock);
11431 	if (rc != 0)
11432 		return (rc);
11433 	else
11434 		return (sysctl_handle_int(oidp, &v, 0, req));
11435 }
11436 
11437 static int
11438 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11439 {
11440 	struct adapter *sc = arg1;
11441 	int rc, idx = arg2;
11442 	u_int shift, v, r;
11443 
11444 	MPASS(idx >= 0 && idx < 16);
11445 
11446 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11447 	shift = (idx & 3) << 3;
11448 	mtx_lock(&sc->reg_lock);
11449 	if (hw_off_limits(sc))
11450 		rc = ENXIO;
11451 	else {
11452 		rc = 0;
11453 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11454 	}
11455 	mtx_unlock(&sc->reg_lock);
11456 	if (rc != 0)
11457 		return (rc);
11458 	else
11459 		return (sysctl_handle_int(oidp, &v, 0, req));
11460 }
11461 
11462 static int
11463 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11464 {
11465 	struct vi_info *vi = arg1;
11466 	struct adapter *sc = vi->adapter;
11467 	int idx, rc, i;
11468 	struct sge_ofld_rxq *ofld_rxq;
11469 	uint8_t v;
11470 
11471 	idx = vi->ofld_tmr_idx;
11472 
11473 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11474 	if (rc != 0 || req->newptr == NULL)
11475 		return (rc);
11476 
11477 	if (idx < 0 || idx >= SGE_NTIMERS)
11478 		return (EINVAL);
11479 
11480 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11481 	    "t4otmr");
11482 	if (rc)
11483 		return (rc);
11484 
11485 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11486 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11487 #ifdef atomic_store_rel_8
11488 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11489 #else
11490 		ofld_rxq->iq.intr_params = v;
11491 #endif
11492 	}
11493 	vi->ofld_tmr_idx = idx;
11494 
11495 	end_synchronized_op(sc, LOCK_HELD);
11496 	return (0);
11497 }
11498 
11499 static int
11500 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11501 {
11502 	struct vi_info *vi = arg1;
11503 	struct adapter *sc = vi->adapter;
11504 	int idx, rc;
11505 
11506 	idx = vi->ofld_pktc_idx;
11507 
11508 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11509 	if (rc != 0 || req->newptr == NULL)
11510 		return (rc);
11511 
11512 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11513 		return (EINVAL);
11514 
11515 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11516 	    "t4opktc");
11517 	if (rc)
11518 		return (rc);
11519 
11520 	if (vi->flags & VI_INIT_DONE)
11521 		rc = EBUSY; /* cannot be changed once the queues are created */
11522 	else
11523 		vi->ofld_pktc_idx = idx;
11524 
11525 	end_synchronized_op(sc, LOCK_HELD);
11526 	return (rc);
11527 }
11528 #endif
11529 
11530 static int
11531 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11532 {
11533 	int rc;
11534 
11535 	if (cntxt->cid > M_CTXTQID)
11536 		return (EINVAL);
11537 
11538 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11539 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11540 		return (EINVAL);
11541 
11542 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11543 	if (rc)
11544 		return (rc);
11545 
11546 	if (hw_off_limits(sc)) {
11547 		rc = ENXIO;
11548 		goto done;
11549 	}
11550 
11551 	if (sc->flags & FW_OK) {
11552 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11553 		    &cntxt->data[0]);
11554 		if (rc == 0)
11555 			goto done;
11556 	}
11557 
11558 	/*
11559 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11560 	 * the backdoor.
11561 	 */
11562 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11563 done:
11564 	end_synchronized_op(sc, 0);
11565 	return (rc);
11566 }
11567 
11568 static int
11569 load_fw(struct adapter *sc, struct t4_data *fw)
11570 {
11571 	int rc;
11572 	uint8_t *fw_data;
11573 
11574 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11575 	if (rc)
11576 		return (rc);
11577 
11578 	if (hw_off_limits(sc)) {
11579 		rc = ENXIO;
11580 		goto done;
11581 	}
11582 
11583 	/*
11584 	 * The firmware, with the sole exception of the memory parity error
11585 	 * handler, runs from memory and not flash.  It is almost always safe to
11586 	 * install a new firmware on a running system.  Just set bit 1 in
11587 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11588 	 */
11589 	if (sc->flags & FULL_INIT_DONE &&
11590 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11591 		rc = EBUSY;
11592 		goto done;
11593 	}
11594 
11595 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11596 
11597 	rc = copyin(fw->data, fw_data, fw->len);
11598 	if (rc == 0)
11599 		rc = -t4_load_fw(sc, fw_data, fw->len);
11600 
11601 	free(fw_data, M_CXGBE);
11602 done:
11603 	end_synchronized_op(sc, 0);
11604 	return (rc);
11605 }
11606 
11607 static int
11608 load_cfg(struct adapter *sc, struct t4_data *cfg)
11609 {
11610 	int rc;
11611 	uint8_t *cfg_data = NULL;
11612 
11613 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11614 	if (rc)
11615 		return (rc);
11616 
11617 	if (hw_off_limits(sc)) {
11618 		rc = ENXIO;
11619 		goto done;
11620 	}
11621 
11622 	if (cfg->len == 0) {
11623 		/* clear */
11624 		rc = -t4_load_cfg(sc, NULL, 0);
11625 		goto done;
11626 	}
11627 
11628 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11629 
11630 	rc = copyin(cfg->data, cfg_data, cfg->len);
11631 	if (rc == 0)
11632 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11633 
11634 	free(cfg_data, M_CXGBE);
11635 done:
11636 	end_synchronized_op(sc, 0);
11637 	return (rc);
11638 }
11639 
11640 static int
11641 load_boot(struct adapter *sc, struct t4_bootrom *br)
11642 {
11643 	int rc;
11644 	uint8_t *br_data = NULL;
11645 	u_int offset;
11646 
11647 	if (br->len > 1024 * 1024)
11648 		return (EFBIG);
11649 
11650 	if (br->pf_offset == 0) {
11651 		/* pfidx */
11652 		if (br->pfidx_addr > 7)
11653 			return (EINVAL);
11654 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11655 		    A_PCIE_PF_EXPROM_OFST)));
11656 	} else if (br->pf_offset == 1) {
11657 		/* offset */
11658 		offset = G_OFFSET(br->pfidx_addr);
11659 	} else {
11660 		return (EINVAL);
11661 	}
11662 
11663 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11664 	if (rc)
11665 		return (rc);
11666 
11667 	if (hw_off_limits(sc)) {
11668 		rc = ENXIO;
11669 		goto done;
11670 	}
11671 
11672 	if (br->len == 0) {
11673 		/* clear */
11674 		rc = -t4_load_boot(sc, NULL, offset, 0);
11675 		goto done;
11676 	}
11677 
11678 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11679 
11680 	rc = copyin(br->data, br_data, br->len);
11681 	if (rc == 0)
11682 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11683 
11684 	free(br_data, M_CXGBE);
11685 done:
11686 	end_synchronized_op(sc, 0);
11687 	return (rc);
11688 }
11689 
11690 static int
11691 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11692 {
11693 	int rc;
11694 	uint8_t *bc_data = NULL;
11695 
11696 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11697 	if (rc)
11698 		return (rc);
11699 
11700 	if (hw_off_limits(sc)) {
11701 		rc = ENXIO;
11702 		goto done;
11703 	}
11704 
11705 	if (bc->len == 0) {
11706 		/* clear */
11707 		rc = -t4_load_bootcfg(sc, NULL, 0);
11708 		goto done;
11709 	}
11710 
11711 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11712 
11713 	rc = copyin(bc->data, bc_data, bc->len);
11714 	if (rc == 0)
11715 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11716 
11717 	free(bc_data, M_CXGBE);
11718 done:
11719 	end_synchronized_op(sc, 0);
11720 	return (rc);
11721 }
11722 
11723 static int
11724 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11725 {
11726 	int rc;
11727 	struct cudbg_init *cudbg;
11728 	void *handle, *buf;
11729 
11730 	/* buf is large, don't block if no memory is available */
11731 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11732 	if (buf == NULL)
11733 		return (ENOMEM);
11734 
11735 	handle = cudbg_alloc_handle();
11736 	if (handle == NULL) {
11737 		rc = ENOMEM;
11738 		goto done;
11739 	}
11740 
11741 	cudbg = cudbg_get_init(handle);
11742 	cudbg->adap = sc;
11743 	cudbg->print = (cudbg_print_cb)printf;
11744 
11745 #ifndef notyet
11746 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11747 	    __func__, dump->wr_flash, dump->len, dump->data);
11748 #endif
11749 
11750 	if (dump->wr_flash)
11751 		cudbg->use_flash = 1;
11752 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11753 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11754 
11755 	rc = cudbg_collect(handle, buf, &dump->len);
11756 	if (rc != 0)
11757 		goto done;
11758 
11759 	rc = copyout(buf, dump->data, dump->len);
11760 done:
11761 	cudbg_free_handle(handle);
11762 	free(buf, M_CXGBE);
11763 	return (rc);
11764 }
11765 
11766 static void
11767 free_offload_policy(struct t4_offload_policy *op)
11768 {
11769 	struct offload_rule *r;
11770 	int i;
11771 
11772 	if (op == NULL)
11773 		return;
11774 
11775 	r = &op->rule[0];
11776 	for (i = 0; i < op->nrules; i++, r++) {
11777 		free(r->bpf_prog.bf_insns, M_CXGBE);
11778 	}
11779 	free(op->rule, M_CXGBE);
11780 	free(op, M_CXGBE);
11781 }
11782 
11783 static int
11784 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11785 {
11786 	int i, rc, len;
11787 	struct t4_offload_policy *op, *old;
11788 	struct bpf_program *bf;
11789 	const struct offload_settings *s;
11790 	struct offload_rule *r;
11791 	void *u;
11792 
11793 	if (!is_offload(sc))
11794 		return (ENODEV);
11795 
11796 	if (uop->nrules == 0) {
11797 		/* Delete installed policies. */
11798 		op = NULL;
11799 		goto set_policy;
11800 	} else if (uop->nrules > 256) { /* arbitrary */
11801 		return (E2BIG);
11802 	}
11803 
11804 	/* Copy userspace offload policy to kernel */
11805 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11806 	op->nrules = uop->nrules;
11807 	len = op->nrules * sizeof(struct offload_rule);
11808 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11809 	rc = copyin(uop->rule, op->rule, len);
11810 	if (rc) {
11811 		free(op->rule, M_CXGBE);
11812 		free(op, M_CXGBE);
11813 		return (rc);
11814 	}
11815 
11816 	r = &op->rule[0];
11817 	for (i = 0; i < op->nrules; i++, r++) {
11818 
11819 		/* Validate open_type */
11820 		if (r->open_type != OPEN_TYPE_LISTEN &&
11821 		    r->open_type != OPEN_TYPE_ACTIVE &&
11822 		    r->open_type != OPEN_TYPE_PASSIVE &&
11823 		    r->open_type != OPEN_TYPE_DONTCARE) {
11824 error:
11825 			/*
11826 			 * Rules 0 to i have malloc'd filters that need to be
11827 			 * freed.  Rules i+1 to nrules have userspace pointers
11828 			 * and should be left alone.
11829 			 */
11830 			op->nrules = i;
11831 			free_offload_policy(op);
11832 			return (rc);
11833 		}
11834 
11835 		/* Validate settings */
11836 		s = &r->settings;
11837 		if ((s->offload != 0 && s->offload != 1) ||
11838 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11839 		    s->sched_class < -1 ||
11840 		    s->sched_class >= sc->params.nsched_cls) {
11841 			rc = EINVAL;
11842 			goto error;
11843 		}
11844 
11845 		bf = &r->bpf_prog;
11846 		u = bf->bf_insns;	/* userspace ptr */
11847 		bf->bf_insns = NULL;
11848 		if (bf->bf_len == 0) {
11849 			/* legal, matches everything */
11850 			continue;
11851 		}
11852 		len = bf->bf_len * sizeof(*bf->bf_insns);
11853 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11854 		rc = copyin(u, bf->bf_insns, len);
11855 		if (rc != 0)
11856 			goto error;
11857 
11858 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11859 			rc = EINVAL;
11860 			goto error;
11861 		}
11862 	}
11863 set_policy:
11864 	rw_wlock(&sc->policy_lock);
11865 	old = sc->policy;
11866 	sc->policy = op;
11867 	rw_wunlock(&sc->policy_lock);
11868 	free_offload_policy(old);
11869 
11870 	return (0);
11871 }
11872 
11873 #define MAX_READ_BUF_SIZE (128 * 1024)
11874 static int
11875 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11876 {
11877 	uint32_t addr, remaining, n;
11878 	uint32_t *buf;
11879 	int rc;
11880 	uint8_t *dst;
11881 
11882 	mtx_lock(&sc->reg_lock);
11883 	if (hw_off_limits(sc))
11884 		rc = ENXIO;
11885 	else
11886 		rc = validate_mem_range(sc, mr->addr, mr->len);
11887 	mtx_unlock(&sc->reg_lock);
11888 	if (rc != 0)
11889 		return (rc);
11890 
11891 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11892 	addr = mr->addr;
11893 	remaining = mr->len;
11894 	dst = (void *)mr->data;
11895 
11896 	while (remaining) {
11897 		n = min(remaining, MAX_READ_BUF_SIZE);
11898 		mtx_lock(&sc->reg_lock);
11899 		if (hw_off_limits(sc))
11900 			rc = ENXIO;
11901 		else
11902 			read_via_memwin(sc, 2, addr, buf, n);
11903 		mtx_unlock(&sc->reg_lock);
11904 		if (rc != 0)
11905 			break;
11906 
11907 		rc = copyout(buf, dst, n);
11908 		if (rc != 0)
11909 			break;
11910 
11911 		dst += n;
11912 		remaining -= n;
11913 		addr += n;
11914 	}
11915 
11916 	free(buf, M_CXGBE);
11917 	return (rc);
11918 }
11919 #undef MAX_READ_BUF_SIZE
11920 
11921 static int
11922 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11923 {
11924 	int rc;
11925 
11926 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11927 		return (EINVAL);
11928 
11929 	if (i2cd->len > sizeof(i2cd->data))
11930 		return (EFBIG);
11931 
11932 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11933 	if (rc)
11934 		return (rc);
11935 	if (hw_off_limits(sc))
11936 		rc = ENXIO;
11937 	else
11938 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11939 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11940 	end_synchronized_op(sc, 0);
11941 
11942 	return (rc);
11943 }
11944 
11945 static int
11946 clear_stats(struct adapter *sc, u_int port_id)
11947 {
11948 	int i, v, chan_map;
11949 	struct port_info *pi;
11950 	struct vi_info *vi;
11951 	struct sge_rxq *rxq;
11952 	struct sge_txq *txq;
11953 	struct sge_wrq *wrq;
11954 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11955 	struct sge_ofld_txq *ofld_txq;
11956 #endif
11957 #ifdef TCP_OFFLOAD
11958 	struct sge_ofld_rxq *ofld_rxq;
11959 #endif
11960 
11961 	if (port_id >= sc->params.nports)
11962 		return (EINVAL);
11963 	pi = sc->port[port_id];
11964 	if (pi == NULL)
11965 		return (EIO);
11966 
11967 	mtx_lock(&sc->reg_lock);
11968 	if (!hw_off_limits(sc)) {
11969 		/* MAC stats */
11970 		t4_clr_port_stats(sc, pi->tx_chan);
11971 		if (is_t6(sc)) {
11972 			if (pi->fcs_reg != -1)
11973 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11974 			else
11975 				pi->stats.rx_fcs_err = 0;
11976 		}
11977 		for_each_vi(pi, v, vi) {
11978 			if (vi->flags & VI_INIT_DONE)
11979 				t4_clr_vi_stats(sc, vi->vin);
11980 		}
11981 		chan_map = pi->rx_e_chan_map;
11982 		v = 0;	/* reuse */
11983 		while (chan_map) {
11984 			i = ffs(chan_map) - 1;
11985 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11986 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11987 			chan_map &= ~(1 << i);
11988 		}
11989 	}
11990 	mtx_unlock(&sc->reg_lock);
11991 	pi->tx_parse_error = 0;
11992 	pi->tnl_cong_drops = 0;
11993 
11994 	/*
11995 	 * Since this command accepts a port, clear stats for
11996 	 * all VIs on this port.
11997 	 */
11998 	for_each_vi(pi, v, vi) {
11999 		if (vi->flags & VI_INIT_DONE) {
12000 
12001 			for_each_rxq(vi, i, rxq) {
12002 #if defined(INET) || defined(INET6)
12003 				rxq->lro.lro_queued = 0;
12004 				rxq->lro.lro_flushed = 0;
12005 #endif
12006 				rxq->rxcsum = 0;
12007 				rxq->vlan_extraction = 0;
12008 				rxq->vxlan_rxcsum = 0;
12009 
12010 				rxq->fl.cl_allocated = 0;
12011 				rxq->fl.cl_recycled = 0;
12012 				rxq->fl.cl_fast_recycled = 0;
12013 			}
12014 
12015 			for_each_txq(vi, i, txq) {
12016 				txq->txcsum = 0;
12017 				txq->tso_wrs = 0;
12018 				txq->vlan_insertion = 0;
12019 				txq->imm_wrs = 0;
12020 				txq->sgl_wrs = 0;
12021 				txq->txpkt_wrs = 0;
12022 				txq->txpkts0_wrs = 0;
12023 				txq->txpkts1_wrs = 0;
12024 				txq->txpkts0_pkts = 0;
12025 				txq->txpkts1_pkts = 0;
12026 				txq->txpkts_flush = 0;
12027 				txq->raw_wrs = 0;
12028 				txq->vxlan_tso_wrs = 0;
12029 				txq->vxlan_txcsum = 0;
12030 				txq->kern_tls_records = 0;
12031 				txq->kern_tls_short = 0;
12032 				txq->kern_tls_partial = 0;
12033 				txq->kern_tls_full = 0;
12034 				txq->kern_tls_octets = 0;
12035 				txq->kern_tls_waste = 0;
12036 				txq->kern_tls_options = 0;
12037 				txq->kern_tls_header = 0;
12038 				txq->kern_tls_fin = 0;
12039 				txq->kern_tls_fin_short = 0;
12040 				txq->kern_tls_cbc = 0;
12041 				txq->kern_tls_gcm = 0;
12042 				mp_ring_reset_stats(txq->r);
12043 			}
12044 
12045 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12046 			for_each_ofld_txq(vi, i, ofld_txq) {
12047 				ofld_txq->wrq.tx_wrs_direct = 0;
12048 				ofld_txq->wrq.tx_wrs_copied = 0;
12049 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12050 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12051 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12052 				counter_u64_zero(ofld_txq->tx_aio_jobs);
12053 				counter_u64_zero(ofld_txq->tx_aio_octets);
12054 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12055 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12056 			}
12057 #endif
12058 #ifdef TCP_OFFLOAD
12059 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12060 				ofld_rxq->fl.cl_allocated = 0;
12061 				ofld_rxq->fl.cl_recycled = 0;
12062 				ofld_rxq->fl.cl_fast_recycled = 0;
12063 				counter_u64_zero(
12064 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12065 				counter_u64_zero(
12066 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12067 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12068 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12069 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12070 				ofld_rxq->rx_iscsi_fl_octets = 0;
12071 				ofld_rxq->rx_aio_ddp_jobs = 0;
12072 				ofld_rxq->rx_aio_ddp_octets = 0;
12073 				ofld_rxq->rx_toe_tls_records = 0;
12074 				ofld_rxq->rx_toe_tls_octets = 0;
12075 				ofld_rxq->rx_toe_ddp_octets = 0;
12076 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12077 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12078 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12079 			}
12080 #endif
12081 
12082 			if (IS_MAIN_VI(vi)) {
12083 				wrq = &sc->sge.ctrlq[pi->port_id];
12084 				wrq->tx_wrs_direct = 0;
12085 				wrq->tx_wrs_copied = 0;
12086 			}
12087 		}
12088 	}
12089 
12090 	return (0);
12091 }
12092 
12093 static int
12094 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12095 {
12096 #ifdef INET6
12097 	struct in6_addr in6;
12098 
12099 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12100 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12101 		return (0);
12102 	else
12103 		return (EIO);
12104 #else
12105 	return (ENOTSUP);
12106 #endif
12107 }
12108 
12109 static int
12110 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12111 {
12112 #ifdef INET6
12113 	struct in6_addr in6;
12114 
12115 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12116 	return (t4_release_clip_addr(sc, &in6));
12117 #else
12118 	return (ENOTSUP);
12119 #endif
12120 }
12121 
12122 int
12123 t4_os_find_pci_capability(struct adapter *sc, int cap)
12124 {
12125 	int i;
12126 
12127 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12128 }
12129 
12130 int
12131 t4_os_pci_save_state(struct adapter *sc)
12132 {
12133 	device_t dev;
12134 	struct pci_devinfo *dinfo;
12135 
12136 	dev = sc->dev;
12137 	dinfo = device_get_ivars(dev);
12138 
12139 	pci_cfg_save(dev, dinfo, 0);
12140 	return (0);
12141 }
12142 
12143 int
12144 t4_os_pci_restore_state(struct adapter *sc)
12145 {
12146 	device_t dev;
12147 	struct pci_devinfo *dinfo;
12148 
12149 	dev = sc->dev;
12150 	dinfo = device_get_ivars(dev);
12151 
12152 	pci_cfg_restore(dev, dinfo);
12153 	return (0);
12154 }
12155 
12156 void
12157 t4_os_portmod_changed(struct port_info *pi)
12158 {
12159 	struct adapter *sc = pi->adapter;
12160 	struct vi_info *vi;
12161 	if_t ifp;
12162 	static const char *mod_str[] = {
12163 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12164 	};
12165 
12166 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12167 	    ("%s: port_type %u", __func__, pi->port_type));
12168 
12169 	vi = &pi->vi[0];
12170 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12171 		PORT_LOCK(pi);
12172 		build_medialist(pi);
12173 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12174 			fixup_link_config(pi);
12175 			apply_link_config(pi);
12176 		}
12177 		PORT_UNLOCK(pi);
12178 		end_synchronized_op(sc, LOCK_HELD);
12179 	}
12180 
12181 	ifp = vi->ifp;
12182 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12183 		if_printf(ifp, "transceiver unplugged.\n");
12184 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12185 		if_printf(ifp, "unknown transceiver inserted.\n");
12186 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12187 		if_printf(ifp, "unsupported transceiver inserted.\n");
12188 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12189 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12190 		    port_top_speed(pi), mod_str[pi->mod_type]);
12191 	} else {
12192 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12193 		    pi->mod_type);
12194 	}
12195 }
12196 
12197 void
12198 t4_os_link_changed(struct port_info *pi)
12199 {
12200 	struct vi_info *vi;
12201 	if_t ifp;
12202 	struct link_config *lc = &pi->link_cfg;
12203 	struct adapter *sc = pi->adapter;
12204 	int v;
12205 
12206 	PORT_LOCK_ASSERT_OWNED(pi);
12207 
12208 	if (is_t6(sc)) {
12209 		if (lc->link_ok) {
12210 			if (lc->speed > 25000 ||
12211 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12212 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12213 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12214 			} else {
12215 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12216 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12217 			}
12218 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12219 			pi->stats.rx_fcs_err = 0;
12220 		} else {
12221 			pi->fcs_reg = -1;
12222 		}
12223 	} else {
12224 		MPASS(pi->fcs_reg != -1);
12225 		MPASS(pi->fcs_base == 0);
12226 	}
12227 
12228 	for_each_vi(pi, v, vi) {
12229 		ifp = vi->ifp;
12230 		if (ifp == NULL || IS_DETACHING(vi))
12231 			continue;
12232 
12233 		if (lc->link_ok) {
12234 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12235 			if_link_state_change(ifp, LINK_STATE_UP);
12236 		} else {
12237 			if_link_state_change(ifp, LINK_STATE_DOWN);
12238 		}
12239 	}
12240 }
12241 
12242 void
12243 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12244 {
12245 	struct adapter *sc;
12246 
12247 	sx_slock(&t4_list_lock);
12248 	SLIST_FOREACH(sc, &t4_list, link) {
12249 		/*
12250 		 * func should not make any assumptions about what state sc is
12251 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12252 		 */
12253 		func(sc, arg);
12254 	}
12255 	sx_sunlock(&t4_list_lock);
12256 }
12257 
12258 static int
12259 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12260     struct thread *td)
12261 {
12262 	int rc;
12263 	struct adapter *sc = dev->si_drv1;
12264 
12265 	rc = priv_check(td, PRIV_DRIVER);
12266 	if (rc != 0)
12267 		return (rc);
12268 
12269 	switch (cmd) {
12270 	case CHELSIO_T4_GETREG: {
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 			edata->val = t4_read_reg(sc, edata->addr);
12281 		else if (edata->size == 8)
12282 			edata->val = t4_read_reg64(sc, edata->addr);
12283 		else
12284 			rc = EINVAL;
12285 		mtx_unlock(&sc->reg_lock);
12286 
12287 		break;
12288 	}
12289 	case CHELSIO_T4_SETREG: {
12290 		struct t4_reg *edata = (struct t4_reg *)data;
12291 
12292 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12293 			return (EFAULT);
12294 
12295 		mtx_lock(&sc->reg_lock);
12296 		if (hw_off_limits(sc))
12297 			rc = ENXIO;
12298 		else if (edata->size == 4) {
12299 			if (edata->val & 0xffffffff00000000)
12300 				rc = EINVAL;
12301 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12302 		} else if (edata->size == 8)
12303 			t4_write_reg64(sc, edata->addr, edata->val);
12304 		else
12305 			rc = EINVAL;
12306 		mtx_unlock(&sc->reg_lock);
12307 
12308 		break;
12309 	}
12310 	case CHELSIO_T4_REGDUMP: {
12311 		struct t4_regdump *regs = (struct t4_regdump *)data;
12312 		int reglen = t4_get_regs_len(sc);
12313 		uint8_t *buf;
12314 
12315 		if (regs->len < reglen) {
12316 			regs->len = reglen; /* hint to the caller */
12317 			return (ENOBUFS);
12318 		}
12319 
12320 		regs->len = reglen;
12321 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12322 		mtx_lock(&sc->reg_lock);
12323 		if (hw_off_limits(sc))
12324 			rc = ENXIO;
12325 		else
12326 			get_regs(sc, regs, buf);
12327 		mtx_unlock(&sc->reg_lock);
12328 		if (rc == 0)
12329 			rc = copyout(buf, regs->data, reglen);
12330 		free(buf, M_CXGBE);
12331 		break;
12332 	}
12333 	case CHELSIO_T4_GET_FILTER_MODE:
12334 		rc = get_filter_mode(sc, (uint32_t *)data);
12335 		break;
12336 	case CHELSIO_T4_SET_FILTER_MODE:
12337 		rc = set_filter_mode(sc, *(uint32_t *)data);
12338 		break;
12339 	case CHELSIO_T4_SET_FILTER_MASK:
12340 		rc = set_filter_mask(sc, *(uint32_t *)data);
12341 		break;
12342 	case CHELSIO_T4_GET_FILTER:
12343 		rc = get_filter(sc, (struct t4_filter *)data);
12344 		break;
12345 	case CHELSIO_T4_SET_FILTER:
12346 		rc = set_filter(sc, (struct t4_filter *)data);
12347 		break;
12348 	case CHELSIO_T4_DEL_FILTER:
12349 		rc = del_filter(sc, (struct t4_filter *)data);
12350 		break;
12351 	case CHELSIO_T4_GET_SGE_CONTEXT:
12352 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12353 		break;
12354 	case CHELSIO_T4_LOAD_FW:
12355 		rc = load_fw(sc, (struct t4_data *)data);
12356 		break;
12357 	case CHELSIO_T4_GET_MEM:
12358 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12359 		break;
12360 	case CHELSIO_T4_GET_I2C:
12361 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12362 		break;
12363 	case CHELSIO_T4_CLEAR_STATS:
12364 		rc = clear_stats(sc, *(uint32_t *)data);
12365 		break;
12366 	case CHELSIO_T4_SCHED_CLASS:
12367 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12368 		break;
12369 	case CHELSIO_T4_SCHED_QUEUE:
12370 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12371 		break;
12372 	case CHELSIO_T4_GET_TRACER:
12373 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12374 		break;
12375 	case CHELSIO_T4_SET_TRACER:
12376 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12377 		break;
12378 	case CHELSIO_T4_LOAD_CFG:
12379 		rc = load_cfg(sc, (struct t4_data *)data);
12380 		break;
12381 	case CHELSIO_T4_LOAD_BOOT:
12382 		rc = load_boot(sc, (struct t4_bootrom *)data);
12383 		break;
12384 	case CHELSIO_T4_LOAD_BOOTCFG:
12385 		rc = load_bootcfg(sc, (struct t4_data *)data);
12386 		break;
12387 	case CHELSIO_T4_CUDBG_DUMP:
12388 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12389 		break;
12390 	case CHELSIO_T4_SET_OFLD_POLICY:
12391 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12392 		break;
12393 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12394 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12395 		break;
12396 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12397 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12398 		break;
12399 	default:
12400 		rc = ENOTTY;
12401 	}
12402 
12403 	return (rc);
12404 }
12405 
12406 #ifdef TCP_OFFLOAD
12407 static int
12408 toe_capability(struct vi_info *vi, bool enable)
12409 {
12410 	int rc;
12411 	struct port_info *pi = vi->pi;
12412 	struct adapter *sc = pi->adapter;
12413 
12414 	ASSERT_SYNCHRONIZED_OP(sc);
12415 
12416 	if (!is_offload(sc))
12417 		return (ENODEV);
12418 	if (hw_off_limits(sc))
12419 		return (ENXIO);
12420 
12421 	if (enable) {
12422 #ifdef KERN_TLS
12423 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12424 			int i, j, n;
12425 			struct port_info *p;
12426 			struct vi_info *v;
12427 
12428 			/*
12429 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12430 			 * on any ifnet.
12431 			 */
12432 			n = 0;
12433 			for_each_port(sc, i) {
12434 				p = sc->port[i];
12435 				for_each_vi(p, j, v) {
12436 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12437 						CH_WARN(sc,
12438 						    "%s has NIC TLS enabled.\n",
12439 						    device_get_nameunit(v->dev));
12440 						n++;
12441 					}
12442 				}
12443 			}
12444 			if (n > 0) {
12445 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12446 				    "associated with this adapter before "
12447 				    "trying to enable TOE.\n");
12448 				return (EAGAIN);
12449 			}
12450 			rc = t6_config_kern_tls(sc, false);
12451 			if (rc)
12452 				return (rc);
12453 		}
12454 #endif
12455 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12456 			/* TOE is already enabled. */
12457 			return (0);
12458 		}
12459 
12460 		/*
12461 		 * We need the port's queues around so that we're able to send
12462 		 * and receive CPLs to/from the TOE even if the ifnet for this
12463 		 * port has never been UP'd administratively.
12464 		 */
12465 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12466 			return (rc);
12467 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12468 		    ((rc = vi_init(&pi->vi[0])) != 0))
12469 			return (rc);
12470 
12471 		if (isset(&sc->offload_map, pi->port_id)) {
12472 			/* TOE is enabled on another VI of this port. */
12473 			pi->uld_vis++;
12474 			return (0);
12475 		}
12476 
12477 		if (!uld_active(sc, ULD_TOM)) {
12478 			rc = t4_activate_uld(sc, ULD_TOM);
12479 			if (rc == EAGAIN) {
12480 				log(LOG_WARNING,
12481 				    "You must kldload t4_tom.ko before trying "
12482 				    "to enable TOE on a cxgbe interface.\n");
12483 			}
12484 			if (rc != 0)
12485 				return (rc);
12486 			KASSERT(sc->tom_softc != NULL,
12487 			    ("%s: TOM activated but softc NULL", __func__));
12488 			KASSERT(uld_active(sc, ULD_TOM),
12489 			    ("%s: TOM activated but flag not set", __func__));
12490 		}
12491 
12492 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12493 		if (!uld_active(sc, ULD_IWARP))
12494 			(void) t4_activate_uld(sc, ULD_IWARP);
12495 		if (!uld_active(sc, ULD_ISCSI))
12496 			(void) t4_activate_uld(sc, ULD_ISCSI);
12497 
12498 		pi->uld_vis++;
12499 		setbit(&sc->offload_map, pi->port_id);
12500 	} else {
12501 		pi->uld_vis--;
12502 
12503 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12504 			return (0);
12505 
12506 		KASSERT(uld_active(sc, ULD_TOM),
12507 		    ("%s: TOM never initialized?", __func__));
12508 		clrbit(&sc->offload_map, pi->port_id);
12509 	}
12510 
12511 	return (0);
12512 }
12513 
12514 /*
12515  * Add an upper layer driver to the global list.
12516  */
12517 int
12518 t4_register_uld(struct uld_info *ui)
12519 {
12520 	int rc = 0;
12521 	struct uld_info *u;
12522 
12523 	sx_xlock(&t4_uld_list_lock);
12524 	SLIST_FOREACH(u, &t4_uld_list, link) {
12525 	    if (u->uld_id == ui->uld_id) {
12526 		    rc = EEXIST;
12527 		    goto done;
12528 	    }
12529 	}
12530 
12531 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12532 	ui->refcount = 0;
12533 done:
12534 	sx_xunlock(&t4_uld_list_lock);
12535 	return (rc);
12536 }
12537 
12538 int
12539 t4_unregister_uld(struct uld_info *ui)
12540 {
12541 	int rc = EINVAL;
12542 	struct uld_info *u;
12543 
12544 	sx_xlock(&t4_uld_list_lock);
12545 
12546 	SLIST_FOREACH(u, &t4_uld_list, link) {
12547 	    if (u == ui) {
12548 		    if (ui->refcount > 0) {
12549 			    rc = EBUSY;
12550 			    goto done;
12551 		    }
12552 
12553 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12554 		    rc = 0;
12555 		    goto done;
12556 	    }
12557 	}
12558 done:
12559 	sx_xunlock(&t4_uld_list_lock);
12560 	return (rc);
12561 }
12562 
12563 int
12564 t4_activate_uld(struct adapter *sc, int id)
12565 {
12566 	int rc;
12567 	struct uld_info *ui;
12568 
12569 	ASSERT_SYNCHRONIZED_OP(sc);
12570 
12571 	if (id < 0 || id > ULD_MAX)
12572 		return (EINVAL);
12573 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12574 
12575 	sx_slock(&t4_uld_list_lock);
12576 
12577 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12578 		if (ui->uld_id == id) {
12579 			if (!(sc->flags & FULL_INIT_DONE)) {
12580 				rc = adapter_init(sc);
12581 				if (rc != 0)
12582 					break;
12583 			}
12584 
12585 			rc = ui->activate(sc);
12586 			if (rc == 0) {
12587 				setbit(&sc->active_ulds, id);
12588 				ui->refcount++;
12589 			}
12590 			break;
12591 		}
12592 	}
12593 
12594 	sx_sunlock(&t4_uld_list_lock);
12595 
12596 	return (rc);
12597 }
12598 
12599 int
12600 t4_deactivate_uld(struct adapter *sc, int id)
12601 {
12602 	int rc;
12603 	struct uld_info *ui;
12604 
12605 	ASSERT_SYNCHRONIZED_OP(sc);
12606 
12607 	if (id < 0 || id > ULD_MAX)
12608 		return (EINVAL);
12609 	rc = ENXIO;
12610 
12611 	sx_slock(&t4_uld_list_lock);
12612 
12613 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12614 		if (ui->uld_id == id) {
12615 			rc = ui->deactivate(sc);
12616 			if (rc == 0) {
12617 				clrbit(&sc->active_ulds, id);
12618 				ui->refcount--;
12619 			}
12620 			break;
12621 		}
12622 	}
12623 
12624 	sx_sunlock(&t4_uld_list_lock);
12625 
12626 	return (rc);
12627 }
12628 
12629 static int
12630 t4_deactivate_all_uld(struct adapter *sc)
12631 {
12632 	int rc;
12633 	struct uld_info *ui;
12634 
12635 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12636 	if (rc != 0)
12637 		return (ENXIO);
12638 
12639 	sx_slock(&t4_uld_list_lock);
12640 
12641 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12642 		if (isset(&sc->active_ulds, ui->uld_id)) {
12643 			rc = ui->deactivate(sc);
12644 			if (rc != 0)
12645 				break;
12646 			clrbit(&sc->active_ulds, ui->uld_id);
12647 			ui->refcount--;
12648 		}
12649 	}
12650 
12651 	sx_sunlock(&t4_uld_list_lock);
12652 	end_synchronized_op(sc, 0);
12653 
12654 	return (rc);
12655 }
12656 
12657 static void
12658 t4_async_event(struct adapter *sc)
12659 {
12660 	struct uld_info *ui;
12661 
12662 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12663 		return;
12664 	sx_slock(&t4_uld_list_lock);
12665 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12666 		if (ui->uld_id == ULD_IWARP) {
12667 			ui->async_event(sc);
12668 			break;
12669 		}
12670 	}
12671 	sx_sunlock(&t4_uld_list_lock);
12672 	end_synchronized_op(sc, 0);
12673 }
12674 
12675 int
12676 uld_active(struct adapter *sc, int uld_id)
12677 {
12678 
12679 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12680 
12681 	return (isset(&sc->active_ulds, uld_id));
12682 }
12683 #endif
12684 
12685 #ifdef KERN_TLS
12686 static int
12687 ktls_capability(struct adapter *sc, bool enable)
12688 {
12689 	ASSERT_SYNCHRONIZED_OP(sc);
12690 
12691 	if (!is_ktls(sc))
12692 		return (ENODEV);
12693 	if (!is_t6(sc))
12694 		return (0);
12695 	if (hw_off_limits(sc))
12696 		return (ENXIO);
12697 
12698 	if (enable) {
12699 		if (sc->flags & KERN_TLS_ON)
12700 			return (0);	/* already on */
12701 		if (sc->offload_map != 0) {
12702 			CH_WARN(sc,
12703 			    "Disable TOE on all interfaces associated with "
12704 			    "this adapter before trying to enable NIC TLS.\n");
12705 			return (EAGAIN);
12706 		}
12707 		return (t6_config_kern_tls(sc, true));
12708 	} else {
12709 		/*
12710 		 * Nothing to do for disable.  If TOE is enabled sometime later
12711 		 * then toe_capability will reconfigure the hardware.
12712 		 */
12713 		return (0);
12714 	}
12715 }
12716 #endif
12717 
12718 /*
12719  * t  = ptr to tunable.
12720  * nc = number of CPUs.
12721  * c  = compiled in default for that tunable.
12722  */
12723 static void
12724 calculate_nqueues(int *t, int nc, const int c)
12725 {
12726 	int nq;
12727 
12728 	if (*t > 0)
12729 		return;
12730 	nq = *t < 0 ? -*t : c;
12731 	*t = min(nc, nq);
12732 }
12733 
12734 /*
12735  * Come up with reasonable defaults for some of the tunables, provided they're
12736  * not set by the user (in which case we'll use the values as is).
12737  */
12738 static void
12739 tweak_tunables(void)
12740 {
12741 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12742 
12743 	if (t4_ntxq < 1) {
12744 #ifdef RSS
12745 		t4_ntxq = rss_getnumbuckets();
12746 #else
12747 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12748 #endif
12749 	}
12750 
12751 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12752 
12753 	if (t4_nrxq < 1) {
12754 #ifdef RSS
12755 		t4_nrxq = rss_getnumbuckets();
12756 #else
12757 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12758 #endif
12759 	}
12760 
12761 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12762 
12763 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12764 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12765 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12766 #endif
12767 #ifdef TCP_OFFLOAD
12768 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12769 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12770 #endif
12771 
12772 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12773 	if (t4_toecaps_allowed == -1)
12774 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12775 #else
12776 	if (t4_toecaps_allowed == -1)
12777 		t4_toecaps_allowed = 0;
12778 #endif
12779 
12780 #ifdef TCP_OFFLOAD
12781 	if (t4_rdmacaps_allowed == -1) {
12782 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12783 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12784 	}
12785 
12786 	if (t4_iscsicaps_allowed == -1) {
12787 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12788 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12789 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12790 	}
12791 
12792 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12793 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12794 
12795 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12796 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12797 #else
12798 	if (t4_rdmacaps_allowed == -1)
12799 		t4_rdmacaps_allowed = 0;
12800 
12801 	if (t4_iscsicaps_allowed == -1)
12802 		t4_iscsicaps_allowed = 0;
12803 #endif
12804 
12805 #ifdef DEV_NETMAP
12806 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12807 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12808 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12809 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12810 #endif
12811 
12812 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12813 		t4_tmr_idx = TMR_IDX;
12814 
12815 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12816 		t4_pktc_idx = PKTC_IDX;
12817 
12818 	if (t4_qsize_txq < 128)
12819 		t4_qsize_txq = 128;
12820 
12821 	if (t4_qsize_rxq < 128)
12822 		t4_qsize_rxq = 128;
12823 	while (t4_qsize_rxq & 7)
12824 		t4_qsize_rxq++;
12825 
12826 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12827 
12828 	/*
12829 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12830 	 * VI for the port.  The rest are additional virtual interfaces on the
12831 	 * same physical port.  Note that the main VI does not have native
12832 	 * netmap support but the extra VIs do.
12833 	 *
12834 	 * Limit the number of VIs per port to the number of available
12835 	 * MAC addresses per port.
12836 	 */
12837 	if (t4_num_vis < 1)
12838 		t4_num_vis = 1;
12839 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12840 		t4_num_vis = nitems(vi_mac_funcs);
12841 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12842 	}
12843 
12844 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12845 		pcie_relaxed_ordering = 1;
12846 #if defined(__i386__) || defined(__amd64__)
12847 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12848 			pcie_relaxed_ordering = 0;
12849 #endif
12850 	}
12851 }
12852 
12853 #ifdef DDB
12854 static void
12855 t4_dump_tcb(struct adapter *sc, int tid)
12856 {
12857 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12858 
12859 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12860 	save = t4_read_reg(sc, reg);
12861 	base = sc->memwin[2].mw_base;
12862 
12863 	/* Dump TCB for the tid */
12864 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12865 	tcb_addr += tid * TCB_SIZE;
12866 
12867 	if (is_t4(sc)) {
12868 		pf = 0;
12869 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12870 	} else {
12871 		pf = V_PFNUM(sc->pf);
12872 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12873 	}
12874 	t4_write_reg(sc, reg, win_pos | pf);
12875 	t4_read_reg(sc, reg);
12876 
12877 	off = tcb_addr - win_pos;
12878 	for (i = 0; i < 4; i++) {
12879 		uint32_t buf[8];
12880 		for (j = 0; j < 8; j++, off += 4)
12881 			buf[j] = htonl(t4_read_reg(sc, base + off));
12882 
12883 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12884 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12885 		    buf[7]);
12886 	}
12887 
12888 	t4_write_reg(sc, reg, save);
12889 	t4_read_reg(sc, reg);
12890 }
12891 
12892 static void
12893 t4_dump_devlog(struct adapter *sc)
12894 {
12895 	struct devlog_params *dparams = &sc->params.devlog;
12896 	struct fw_devlog_e e;
12897 	int i, first, j, m, nentries, rc;
12898 	uint64_t ftstamp = UINT64_MAX;
12899 
12900 	if (dparams->start == 0) {
12901 		db_printf("devlog params not valid\n");
12902 		return;
12903 	}
12904 
12905 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12906 	m = fwmtype_to_hwmtype(dparams->memtype);
12907 
12908 	/* Find the first entry. */
12909 	first = -1;
12910 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12911 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12912 		    sizeof(e), (void *)&e);
12913 		if (rc != 0)
12914 			break;
12915 
12916 		if (e.timestamp == 0)
12917 			break;
12918 
12919 		e.timestamp = be64toh(e.timestamp);
12920 		if (e.timestamp < ftstamp) {
12921 			ftstamp = e.timestamp;
12922 			first = i;
12923 		}
12924 	}
12925 
12926 	if (first == -1)
12927 		return;
12928 
12929 	i = first;
12930 	do {
12931 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12932 		    sizeof(e), (void *)&e);
12933 		if (rc != 0)
12934 			return;
12935 
12936 		if (e.timestamp == 0)
12937 			return;
12938 
12939 		e.timestamp = be64toh(e.timestamp);
12940 		e.seqno = be32toh(e.seqno);
12941 		for (j = 0; j < 8; j++)
12942 			e.params[j] = be32toh(e.params[j]);
12943 
12944 		db_printf("%10d  %15ju  %8s  %8s  ",
12945 		    e.seqno, e.timestamp,
12946 		    (e.level < nitems(devlog_level_strings) ?
12947 			devlog_level_strings[e.level] : "UNKNOWN"),
12948 		    (e.facility < nitems(devlog_facility_strings) ?
12949 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12950 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12951 		    e.params[3], e.params[4], e.params[5], e.params[6],
12952 		    e.params[7]);
12953 
12954 		if (++i == nentries)
12955 			i = 0;
12956 	} while (i != first && !db_pager_quit);
12957 }
12958 
12959 static DB_DEFINE_TABLE(show, t4, show_t4);
12960 
12961 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12962 {
12963 	device_t dev;
12964 	int t;
12965 	bool valid;
12966 
12967 	valid = false;
12968 	t = db_read_token();
12969 	if (t == tIDENT) {
12970 		dev = device_lookup_by_name(db_tok_string);
12971 		valid = true;
12972 	}
12973 	db_skip_to_eol();
12974 	if (!valid) {
12975 		db_printf("usage: show t4 devlog <nexus>\n");
12976 		return;
12977 	}
12978 
12979 	if (dev == NULL) {
12980 		db_printf("device not found\n");
12981 		return;
12982 	}
12983 
12984 	t4_dump_devlog(device_get_softc(dev));
12985 }
12986 
12987 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12988 {
12989 	device_t dev;
12990 	int radix, tid, t;
12991 	bool valid;
12992 
12993 	valid = false;
12994 	radix = db_radix;
12995 	db_radix = 10;
12996 	t = db_read_token();
12997 	if (t == tIDENT) {
12998 		dev = device_lookup_by_name(db_tok_string);
12999 		t = db_read_token();
13000 		if (t == tNUMBER) {
13001 			tid = db_tok_number;
13002 			valid = true;
13003 		}
13004 	}
13005 	db_radix = radix;
13006 	db_skip_to_eol();
13007 	if (!valid) {
13008 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
13009 		return;
13010 	}
13011 
13012 	if (dev == NULL) {
13013 		db_printf("device not found\n");
13014 		return;
13015 	}
13016 	if (tid < 0) {
13017 		db_printf("invalid tid\n");
13018 		return;
13019 	}
13020 
13021 	t4_dump_tcb(device_get_softc(dev), tid);
13022 }
13023 #endif
13024 
13025 static eventhandler_tag vxlan_start_evtag;
13026 static eventhandler_tag vxlan_stop_evtag;
13027 
13028 struct vxlan_evargs {
13029 	if_t ifp;
13030 	uint16_t port;
13031 };
13032 
13033 static void
13034 enable_vxlan_rx(struct adapter *sc)
13035 {
13036 	int i, rc;
13037 	struct port_info *pi;
13038 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13039 
13040 	ASSERT_SYNCHRONIZED_OP(sc);
13041 
13042 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13043 	    F_VXLAN_EN);
13044 	for_each_port(sc, i) {
13045 		pi = sc->port[i];
13046 		if (pi->vxlan_tcam_entry == true)
13047 			continue;
13048 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13049 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13050 		    true);
13051 		if (rc < 0) {
13052 			rc = -rc;
13053 			CH_ERR(&pi->vi[0],
13054 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13055 		} else {
13056 			MPASS(rc == sc->rawf_base + pi->port_id);
13057 			pi->vxlan_tcam_entry = true;
13058 		}
13059 	}
13060 }
13061 
13062 static void
13063 t4_vxlan_start(struct adapter *sc, void *arg)
13064 {
13065 	struct vxlan_evargs *v = arg;
13066 
13067 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13068 		return;
13069 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13070 		return;
13071 
13072 	if (sc->vxlan_refcount == 0) {
13073 		sc->vxlan_port = v->port;
13074 		sc->vxlan_refcount = 1;
13075 		if (!hw_off_limits(sc))
13076 			enable_vxlan_rx(sc);
13077 	} else if (sc->vxlan_port == v->port) {
13078 		sc->vxlan_refcount++;
13079 	} else {
13080 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13081 		    "ignoring attempt to configure it on port %d\n",
13082 		    sc->vxlan_port, v->port);
13083 	}
13084 	end_synchronized_op(sc, 0);
13085 }
13086 
13087 static void
13088 t4_vxlan_stop(struct adapter *sc, void *arg)
13089 {
13090 	struct vxlan_evargs *v = arg;
13091 
13092 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13093 		return;
13094 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13095 		return;
13096 
13097 	/*
13098 	 * VXLANs may have been configured before the driver was loaded so we
13099 	 * may see more stops than starts.  This is not handled cleanly but at
13100 	 * least we keep the refcount sane.
13101 	 */
13102 	if (sc->vxlan_port != v->port)
13103 		goto done;
13104 	if (sc->vxlan_refcount == 0) {
13105 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13106 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13107 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13108 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13109 done:
13110 	end_synchronized_op(sc, 0);
13111 }
13112 
13113 static void
13114 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13115     sa_family_t family, u_int port)
13116 {
13117 	struct vxlan_evargs v;
13118 
13119 	MPASS(family == AF_INET || family == AF_INET6);
13120 	v.ifp = ifp;
13121 	v.port = port;
13122 
13123 	t4_iterate(t4_vxlan_start, &v);
13124 }
13125 
13126 static void
13127 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13128     u_int port)
13129 {
13130 	struct vxlan_evargs v;
13131 
13132 	MPASS(family == AF_INET || family == AF_INET6);
13133 	v.ifp = ifp;
13134 	v.port = port;
13135 
13136 	t4_iterate(t4_vxlan_stop, &v);
13137 }
13138 
13139 
13140 static struct sx mlu;	/* mod load unload */
13141 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13142 
13143 static int
13144 mod_event(module_t mod, int cmd, void *arg)
13145 {
13146 	int rc = 0;
13147 	static int loaded = 0;
13148 
13149 	switch (cmd) {
13150 	case MOD_LOAD:
13151 		sx_xlock(&mlu);
13152 		if (loaded++ == 0) {
13153 			t4_sge_modload();
13154 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13155 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13156 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13157 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13158 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13159 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13160 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13161 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13162 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13163 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13164 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13165 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13166 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13167 			    do_smt_write_rpl);
13168 			sx_init(&t4_list_lock, "T4/T5 adapters");
13169 			SLIST_INIT(&t4_list);
13170 			callout_init(&fatal_callout, 1);
13171 #ifdef TCP_OFFLOAD
13172 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13173 			SLIST_INIT(&t4_uld_list);
13174 #endif
13175 #ifdef INET6
13176 			t4_clip_modload();
13177 #endif
13178 #ifdef KERN_TLS
13179 			t6_ktls_modload();
13180 #endif
13181 			t4_tracer_modload();
13182 			tweak_tunables();
13183 			vxlan_start_evtag =
13184 			    EVENTHANDLER_REGISTER(vxlan_start,
13185 				t4_vxlan_start_handler, NULL,
13186 				EVENTHANDLER_PRI_ANY);
13187 			vxlan_stop_evtag =
13188 			    EVENTHANDLER_REGISTER(vxlan_stop,
13189 				t4_vxlan_stop_handler, NULL,
13190 				EVENTHANDLER_PRI_ANY);
13191 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13192 			    taskqueue_thread_enqueue, &reset_tq);
13193 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13194 			    "t4_rst_thr");
13195 		}
13196 		sx_xunlock(&mlu);
13197 		break;
13198 
13199 	case MOD_UNLOAD:
13200 		sx_xlock(&mlu);
13201 		if (--loaded == 0) {
13202 			int tries;
13203 
13204 			taskqueue_free(reset_tq);
13205 			sx_slock(&t4_list_lock);
13206 			if (!SLIST_EMPTY(&t4_list)) {
13207 				rc = EBUSY;
13208 				sx_sunlock(&t4_list_lock);
13209 				goto done_unload;
13210 			}
13211 #ifdef TCP_OFFLOAD
13212 			sx_slock(&t4_uld_list_lock);
13213 			if (!SLIST_EMPTY(&t4_uld_list)) {
13214 				rc = EBUSY;
13215 				sx_sunlock(&t4_uld_list_lock);
13216 				sx_sunlock(&t4_list_lock);
13217 				goto done_unload;
13218 			}
13219 #endif
13220 			tries = 0;
13221 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13222 				uprintf("%ju clusters with custom free routine "
13223 				    "still is use.\n", t4_sge_extfree_refs());
13224 				pause("t4unload", 2 * hz);
13225 			}
13226 #ifdef TCP_OFFLOAD
13227 			sx_sunlock(&t4_uld_list_lock);
13228 #endif
13229 			sx_sunlock(&t4_list_lock);
13230 
13231 			if (t4_sge_extfree_refs() == 0) {
13232 				EVENTHANDLER_DEREGISTER(vxlan_start,
13233 				    vxlan_start_evtag);
13234 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13235 				    vxlan_stop_evtag);
13236 				t4_tracer_modunload();
13237 #ifdef KERN_TLS
13238 				t6_ktls_modunload();
13239 #endif
13240 #ifdef INET6
13241 				t4_clip_modunload();
13242 #endif
13243 #ifdef TCP_OFFLOAD
13244 				sx_destroy(&t4_uld_list_lock);
13245 #endif
13246 				sx_destroy(&t4_list_lock);
13247 				t4_sge_modunload();
13248 				loaded = 0;
13249 			} else {
13250 				rc = EBUSY;
13251 				loaded++;	/* undo earlier decrement */
13252 			}
13253 		}
13254 done_unload:
13255 		sx_xunlock(&mlu);
13256 		break;
13257 	}
13258 
13259 	return (rc);
13260 }
13261 
13262 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13263 MODULE_VERSION(t4nex, 1);
13264 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13265 #ifdef DEV_NETMAP
13266 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13267 #endif /* DEV_NETMAP */
13268 
13269 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13270 MODULE_VERSION(t5nex, 1);
13271 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13272 #ifdef DEV_NETMAP
13273 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13274 #endif /* DEV_NETMAP */
13275 
13276 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13277 MODULE_VERSION(t6nex, 1);
13278 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13279 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13280 #ifdef DEV_NETMAP
13281 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13282 #endif /* DEV_NETMAP */
13283 
13284 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13285 MODULE_VERSION(cxgbe, 1);
13286 
13287 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13288 MODULE_VERSION(cxl, 1);
13289 
13290 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13291 MODULE_VERSION(cc, 1);
13292 
13293 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13294 MODULE_VERSION(vcxgbe, 1);
13295 
13296 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13297 MODULE_VERSION(vcxl, 1);
13298 
13299 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13300 MODULE_VERSION(vcc, 1);
13301