xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 70174ef7d2c80abdfca0e3ad9d0bb1af61318542)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_kern_tls.h"
35 #include "opt_ratelimit.h"
36 #include "opt_rss.h"
37 
38 #include <sys/param.h>
39 #include <sys/conf.h>
40 #include <sys/priv.h>
41 #include <sys/kernel.h>
42 #include <sys/bus.h>
43 #include <sys/eventhandler.h>
44 #include <sys/module.h>
45 #include <sys/malloc.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <sys/pciio.h>
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pci_private.h>
52 #include <sys/firmware.h>
53 #include <sys/sbuf.h>
54 #include <sys/smp.h>
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/sysctl.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_types.h>
61 #include <net/if_dl.h>
62 #include <net/if_vlan_var.h>
63 #ifdef RSS
64 #include <net/rss_config.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #ifdef KERN_TLS
69 #include <netinet/tcp_seq.h>
70 #endif
71 #if defined(__i386__) || defined(__amd64__)
72 #include <machine/md_var.h>
73 #include <machine/cputypes.h>
74 #include <vm/vm.h>
75 #include <vm/pmap.h>
76 #endif
77 #ifdef DDB
78 #include <ddb/ddb.h>
79 #include <ddb/db_lex.h>
80 #endif
81 
82 #include "common/common.h"
83 #include "common/t4_msg.h"
84 #include "common/t4_regs.h"
85 #include "common/t4_regs_values.h"
86 #include "cudbg/cudbg.h"
87 #include "t4_clip.h"
88 #include "t4_ioctl.h"
89 #include "t4_l2t.h"
90 #include "t4_mp_ring.h"
91 #include "t4_if.h"
92 #include "t4_smt.h"
93 
94 /* T4 bus driver interface */
95 static int t4_probe(device_t);
96 static int t4_attach(device_t);
97 static int t4_detach(device_t);
98 static int t4_child_location(device_t, device_t, struct sbuf *);
99 static int t4_ready(device_t);
100 static int t4_read_port_device(device_t, int, device_t *);
101 static int t4_suspend(device_t);
102 static int t4_resume(device_t);
103 static int t4_reset_prepare(device_t, device_t);
104 static int t4_reset_post(device_t, device_t);
105 static device_method_t t4_methods[] = {
106 	DEVMETHOD(device_probe,		t4_probe),
107 	DEVMETHOD(device_attach,	t4_attach),
108 	DEVMETHOD(device_detach,	t4_detach),
109 	DEVMETHOD(device_suspend,	t4_suspend),
110 	DEVMETHOD(device_resume,	t4_resume),
111 
112 	DEVMETHOD(bus_child_location,	t4_child_location),
113 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
114 	DEVMETHOD(bus_reset_post,	t4_reset_post),
115 
116 	DEVMETHOD(t4_is_main_ready,	t4_ready),
117 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
118 
119 	DEVMETHOD_END
120 };
121 static driver_t t4_driver = {
122 	"t4nex",
123 	t4_methods,
124 	sizeof(struct adapter)
125 };
126 
127 
128 /* T4 port (cxgbe) interface */
129 static int cxgbe_probe(device_t);
130 static int cxgbe_attach(device_t);
131 static int cxgbe_detach(device_t);
132 device_method_t cxgbe_methods[] = {
133 	DEVMETHOD(device_probe,		cxgbe_probe),
134 	DEVMETHOD(device_attach,	cxgbe_attach),
135 	DEVMETHOD(device_detach,	cxgbe_detach),
136 	{ 0, 0 }
137 };
138 static driver_t cxgbe_driver = {
139 	"cxgbe",
140 	cxgbe_methods,
141 	sizeof(struct port_info)
142 };
143 
144 /* T4 VI (vcxgbe) interface */
145 static int vcxgbe_probe(device_t);
146 static int vcxgbe_attach(device_t);
147 static int vcxgbe_detach(device_t);
148 static device_method_t vcxgbe_methods[] = {
149 	DEVMETHOD(device_probe,		vcxgbe_probe),
150 	DEVMETHOD(device_attach,	vcxgbe_attach),
151 	DEVMETHOD(device_detach,	vcxgbe_detach),
152 	{ 0, 0 }
153 };
154 static driver_t vcxgbe_driver = {
155 	"vcxgbe",
156 	vcxgbe_methods,
157 	sizeof(struct vi_info)
158 };
159 
160 static d_ioctl_t t4_ioctl;
161 
162 static struct cdevsw t4_cdevsw = {
163        .d_version = D_VERSION,
164        .d_ioctl = t4_ioctl,
165        .d_name = "t4nex",
166 };
167 
168 /* T5 bus driver interface */
169 static int t5_probe(device_t);
170 static device_method_t t5_methods[] = {
171 	DEVMETHOD(device_probe,		t5_probe),
172 	DEVMETHOD(device_attach,	t4_attach),
173 	DEVMETHOD(device_detach,	t4_detach),
174 	DEVMETHOD(device_suspend,	t4_suspend),
175 	DEVMETHOD(device_resume,	t4_resume),
176 
177 	DEVMETHOD(bus_child_location,	t4_child_location),
178 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
179 	DEVMETHOD(bus_reset_post,	t4_reset_post),
180 
181 	DEVMETHOD(t4_is_main_ready,	t4_ready),
182 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
183 
184 	DEVMETHOD_END
185 };
186 static driver_t t5_driver = {
187 	"t5nex",
188 	t5_methods,
189 	sizeof(struct adapter)
190 };
191 
192 
193 /* T5 port (cxl) interface */
194 static driver_t cxl_driver = {
195 	"cxl",
196 	cxgbe_methods,
197 	sizeof(struct port_info)
198 };
199 
200 /* T5 VI (vcxl) interface */
201 static driver_t vcxl_driver = {
202 	"vcxl",
203 	vcxgbe_methods,
204 	sizeof(struct vi_info)
205 };
206 
207 /* T6 bus driver interface */
208 static int t6_probe(device_t);
209 static device_method_t t6_methods[] = {
210 	DEVMETHOD(device_probe,		t6_probe),
211 	DEVMETHOD(device_attach,	t4_attach),
212 	DEVMETHOD(device_detach,	t4_detach),
213 	DEVMETHOD(device_suspend,	t4_suspend),
214 	DEVMETHOD(device_resume,	t4_resume),
215 
216 	DEVMETHOD(bus_child_location,	t4_child_location),
217 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
218 	DEVMETHOD(bus_reset_post,	t4_reset_post),
219 
220 	DEVMETHOD(t4_is_main_ready,	t4_ready),
221 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
222 
223 	DEVMETHOD_END
224 };
225 static driver_t t6_driver = {
226 	"t6nex",
227 	t6_methods,
228 	sizeof(struct adapter)
229 };
230 
231 
232 /* T6 port (cc) interface */
233 static driver_t cc_driver = {
234 	"cc",
235 	cxgbe_methods,
236 	sizeof(struct port_info)
237 };
238 
239 /* T6 VI (vcc) interface */
240 static driver_t vcc_driver = {
241 	"vcc",
242 	vcxgbe_methods,
243 	sizeof(struct vi_info)
244 };
245 
246 /* ifnet interface */
247 static void cxgbe_init(void *);
248 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
249 static int cxgbe_transmit(if_t, struct mbuf *);
250 static void cxgbe_qflush(if_t);
251 #if defined(KERN_TLS) || defined(RATELIMIT)
252 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
253     struct m_snd_tag **);
254 #endif
255 
256 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
257 
258 /*
259  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
260  * then ADAPTER_LOCK, then t4_uld_list_lock.
261  */
262 static struct sx t4_list_lock;
263 SLIST_HEAD(, adapter) t4_list;
264 #ifdef TCP_OFFLOAD
265 static struct sx t4_uld_list_lock;
266 struct uld_info *t4_uld_list[ULD_MAX + 1];
267 #endif
268 
269 /*
270  * Tunables.  See tweak_tunables() too.
271  *
272  * Each tunable is set to a default value here if it's known at compile-time.
273  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274  * provide a reasonable default (upto n) when the driver is loaded.
275  *
276  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277  * T5 are under hw.cxl.
278  */
279 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280     "cxgbe(4) parameters");
281 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) T5+ parameters");
283 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) TOE parameters");
285 
286 /*
287  * Number of queues for tx and rx, NIC and offload.
288  */
289 #define NTXQ 16
290 int t4_ntxq = -NTXQ;
291 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292     "Number of TX queues per port");
293 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294 
295 #define NRXQ 8
296 int t4_nrxq = -NRXQ;
297 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298     "Number of RX queues per port");
299 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300 
301 #define NTXQ_VI 1
302 static int t4_ntxq_vi = -NTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304     "Number of TX queues per VI");
305 
306 #define NRXQ_VI 1
307 static int t4_nrxq_vi = -NRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309     "Number of RX queues per VI");
310 
311 static int t4_rsrv_noflowq = 0;
312 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313     0, "Reserve TX queue 0 of each VI for non-flowid packets");
314 
315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316 #define NOFLDTXQ 8
317 static int t4_nofldtxq = -NOFLDTXQ;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319     "Number of offload TX queues per port");
320 
321 #define NOFLDRXQ 2
322 static int t4_nofldrxq = -NOFLDRXQ;
323 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324     "Number of offload RX queues per port");
325 
326 #define NOFLDTXQ_VI 1
327 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329     "Number of offload TX queues per VI");
330 
331 #define NOFLDRXQ_VI 1
332 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334     "Number of offload RX queues per VI");
335 
336 #define TMR_IDX_OFLD 1
337 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340 
341 #define PKTC_IDX_OFLD (-1)
342 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345 
346 /* 0 means chip/fw default, non-zero number is value in microseconds */
347 static u_long t4_toe_keepalive_idle = 0;
348 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350 
351 /* 0 means chip/fw default, non-zero number is value in microseconds */
352 static u_long t4_toe_keepalive_interval = 0;
353 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355 
356 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357 static int t4_toe_keepalive_count = 0;
358 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360 
361 /* 0 means chip/fw default, non-zero number is value in microseconds */
362 static u_long t4_toe_rexmt_min = 0;
363 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365 
366 /* 0 means chip/fw default, non-zero number is value in microseconds */
367 static u_long t4_toe_rexmt_max = 0;
368 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370 
371 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372 static int t4_toe_rexmt_count = 0;
373 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375 
376 /* -1 means chip/fw default, other values are raw backoff values to use */
377 static int t4_toe_rexmt_backoff[16] = {
378 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379 };
380 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382     "cxgbe(4) TOE retransmit backoff values");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[0], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[1], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[2], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[3], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[4], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[5], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[6], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[7], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[8], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[9], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[10], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[11], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[12], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[13], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[14], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[15], 0, "");
415 
416 int t4_ddp_rcvbuf_len = 256 * 1024;
417 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
418     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
419 
420 unsigned int t4_ddp_rcvbuf_cache = 4;
421 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
422     &t4_ddp_rcvbuf_cache, 0,
423     "maximum number of free DDP RX buffers to cache per connection");
424 #endif
425 
426 #ifdef DEV_NETMAP
427 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
428 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
429 static int t4_native_netmap = NN_EXTRA_VI;
430 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
431     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
432 
433 #define NNMTXQ 8
434 static int t4_nnmtxq = -NNMTXQ;
435 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
436     "Number of netmap TX queues");
437 
438 #define NNMRXQ 8
439 static int t4_nnmrxq = -NNMRXQ;
440 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
441     "Number of netmap RX queues");
442 
443 #define NNMTXQ_VI 2
444 static int t4_nnmtxq_vi = -NNMTXQ_VI;
445 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
446     "Number of netmap TX queues per VI");
447 
448 #define NNMRXQ_VI 2
449 static int t4_nnmrxq_vi = -NNMRXQ_VI;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
451     "Number of netmap RX queues per VI");
452 #endif
453 
454 /*
455  * Holdoff parameters for ports.
456  */
457 #define TMR_IDX 1
458 int t4_tmr_idx = TMR_IDX;
459 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
460     0, "Holdoff timer index");
461 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
462 
463 #define PKTC_IDX (-1)
464 int t4_pktc_idx = PKTC_IDX;
465 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
466     0, "Holdoff packet counter index");
467 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
468 
469 /*
470  * Size (# of entries) of each tx and rx queue.
471  */
472 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
473 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
474     "Number of descriptors in each TX queue");
475 
476 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
477 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
478     "Number of descriptors in each RX queue");
479 
480 /*
481  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
482  */
483 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
485     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
486 
487 /*
488  * Configuration file.  All the _CF names here are special.
489  */
490 #define DEFAULT_CF	"default"
491 #define BUILTIN_CF	"built-in"
492 #define FLASH_CF	"flash"
493 #define UWIRE_CF	"uwire"
494 #define FPGA_CF		"fpga"
495 static char t4_cfg_file[32] = DEFAULT_CF;
496 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
497     sizeof(t4_cfg_file), "Firmware configuration file");
498 
499 /*
500  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
501  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
502  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
503  *            mark or when signalled to do so, 0 to never emit PAUSE.
504  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
505  *                 negotiated settings will override rx_pause/tx_pause.
506  *                 Otherwise rx_pause/tx_pause are applied forcibly.
507  */
508 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
509 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
510     &t4_pause_settings, 0,
511     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
512 
513 /*
514  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
515  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
516  *  0 to disable FEC.
517  */
518 static int t4_fec = -1;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
520     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
521 
522 /*
523  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
524  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
525  * driver runs as if this is set to 0.
526  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
527  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
528  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
529  *    the firmware anyway (may result in l1cfg errors with old firmwares).
530  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
531  *    means set all FEC bits that are valid for the speed.
532  */
533 static int t4_force_fec = -1;
534 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
535     "Controls the use of FORCE_FEC bit in L1 configuration.");
536 
537 /*
538  * Link autonegotiation.
539  * -1 to run with the firmware default.
540  *  0 to disable.
541  *  1 to enable.
542  */
543 static int t4_autoneg = -1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
545     "Link autonegotiation");
546 
547 /*
548  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
549  * encouraged respectively).  '-n' is the same as 'n' except the firmware
550  * version used in the checks is read from the firmware bundled with the driver.
551  */
552 static int t4_fw_install = 1;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
554     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
555 
556 /*
557  * ASIC features that will be used.  Disable the ones you don't want so that the
558  * chip resources aren't wasted on features that will not be used.
559  */
560 static int t4_nbmcaps_allowed = 0;
561 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
562     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
563 
564 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
565 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
566     &t4_linkcaps_allowed, 0, "Default link capabilities");
567 
568 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
569     FW_CAPS_CONFIG_SWITCH_EGRESS;
570 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
571     &t4_switchcaps_allowed, 0, "Default switch capabilities");
572 
573 #ifdef RATELIMIT
574 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
575 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
576 #else
577 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
578 	FW_CAPS_CONFIG_NIC_HASHFILTER;
579 #endif
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
581     &t4_niccaps_allowed, 0, "Default NIC capabilities");
582 
583 static int t4_toecaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
585     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
586 
587 static int t4_rdmacaps_allowed = -1;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
589     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
590 
591 static int t4_cryptocaps_allowed = -1;
592 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
593     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
594 
595 static int t4_iscsicaps_allowed = -1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
597     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
598 
599 static int t4_fcoecaps_allowed = 0;
600 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
601     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
602 
603 static int t5_write_combine = 0;
604 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
605     0, "Use WC instead of UC for BAR2");
606 
607 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
608 static int t4_doorbells_allowed = 0xf;
609 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
610 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
611 
612 static int t4_num_vis = 1;
613 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
614     "Number of VIs per port");
615 
616 /*
617  * PCIe Relaxed Ordering.
618  * -1: driver should figure out a good value.
619  * 0: disable RO.
620  * 1: enable RO.
621  * 2: leave RO alone.
622  */
623 static int pcie_relaxed_ordering = -1;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
625     &pcie_relaxed_ordering, 0,
626     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
627 
628 static int t4_panic_on_fatal_err = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
630     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
631 
632 static int t4_reset_on_fatal_err = 0;
633 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
634     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
635 
636 static int t4_clock_gate_on_suspend = 0;
637 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
638     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
639 
640 static int t4_tx_vm_wr = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
642     "Use VM work requests to transmit packets.");
643 
644 /*
645  * Set to non-zero to enable the attack filter.  A packet that matches any of
646  * these conditions will get dropped on ingress:
647  * 1) IP && source address == destination address.
648  * 2) TCP/IP && source address is not a unicast address.
649  * 3) TCP/IP && destination address is not a unicast address.
650  * 4) IP && source address is loopback (127.x.y.z).
651  * 5) IP && destination address is loopback (127.x.y.z).
652  * 6) IPv6 && source address == destination address.
653  * 7) IPv6 && source address is not a unicast address.
654  * 8) IPv6 && source address is loopback (::1/128).
655  * 9) IPv6 && destination address is loopback (::1/128).
656  * 10) IPv6 && source address is unspecified (::/128).
657  * 11) IPv6 && destination address is unspecified (::/128).
658  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
659  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
660  */
661 static int t4_attack_filter = 0;
662 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
663     &t4_attack_filter, 0, "Drop suspicious traffic");
664 
665 static int t4_drop_ip_fragments = 0;
666 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
667     &t4_drop_ip_fragments, 0, "Drop IP fragments");
668 
669 static int t4_drop_pkts_with_l2_errors = 1;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
671     &t4_drop_pkts_with_l2_errors, 0,
672     "Drop all frames with Layer 2 length or checksum errors");
673 
674 static int t4_drop_pkts_with_l3_errors = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l3_errors, 0,
677     "Drop all frames with IP version, length, or checksum errors");
678 
679 static int t4_drop_pkts_with_l4_errors = 0;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
681     &t4_drop_pkts_with_l4_errors, 0,
682     "Drop all frames with Layer 4 length, checksum, or other errors");
683 
684 #ifdef TCP_OFFLOAD
685 /*
686  * TOE tunables.
687  */
688 static int t4_cop_managed_offloading = 0;
689 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
690     &t4_cop_managed_offloading, 0,
691     "COP (Connection Offload Policy) controls all TOE offload");
692 #endif
693 
694 #ifdef KERN_TLS
695 /*
696  * This enables KERN_TLS for all adapters if set.
697  */
698 static int t4_kern_tls = 0;
699 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
700     "Enable KERN_TLS mode for T6 adapters");
701 
702 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
703     "cxgbe(4) KERN_TLS parameters");
704 
705 static int t4_tls_inline_keys = 0;
706 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
707     &t4_tls_inline_keys, 0,
708     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
709     "in card memory.");
710 
711 static int t4_tls_combo_wrs = 0;
712 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
713     0, "Attempt to combine TCB field updates with TLS record work requests.");
714 #endif
715 
716 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
717 static int vi_mac_funcs[] = {
718 	FW_VI_FUNC_ETH,
719 	FW_VI_FUNC_OFLD,
720 	FW_VI_FUNC_IWARP,
721 	FW_VI_FUNC_OPENISCSI,
722 	FW_VI_FUNC_OPENFCOE,
723 	FW_VI_FUNC_FOISCSI,
724 	FW_VI_FUNC_FOFCOE,
725 };
726 
727 struct intrs_and_queues {
728 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
729 	uint16_t num_vis;	/* number of VIs for each port */
730 	uint16_t nirq;		/* Total # of vectors */
731 	uint16_t ntxq;		/* # of NIC txq's for each port */
732 	uint16_t nrxq;		/* # of NIC rxq's for each port */
733 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
734 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
735 	uint16_t nnmtxq;	/* # of netmap txq's */
736 	uint16_t nnmrxq;	/* # of netmap rxq's */
737 
738 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
739 	uint16_t ntxq_vi;	/* # of NIC txq's */
740 	uint16_t nrxq_vi;	/* # of NIC rxq's */
741 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
742 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
743 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
744 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
745 };
746 
747 static void setup_memwin(struct adapter *);
748 static void position_memwin(struct adapter *, int, uint32_t);
749 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
750 static int fwmtype_to_hwmtype(int);
751 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
752     uint32_t *);
753 static int fixup_devlog_params(struct adapter *);
754 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
755 static int contact_firmware(struct adapter *);
756 static int partition_resources(struct adapter *);
757 static int get_params__pre_init(struct adapter *);
758 static int set_params__pre_init(struct adapter *);
759 static int get_params__post_init(struct adapter *);
760 static int set_params__post_init(struct adapter *);
761 static void t4_set_desc(struct adapter *);
762 static bool fixed_ifmedia(struct port_info *);
763 static void build_medialist(struct port_info *);
764 static void init_link_config(struct port_info *);
765 static int fixup_link_config(struct port_info *);
766 static int apply_link_config(struct port_info *);
767 static int cxgbe_init_synchronized(struct vi_info *);
768 static int cxgbe_uninit_synchronized(struct vi_info *);
769 static int adapter_full_init(struct adapter *);
770 static void adapter_full_uninit(struct adapter *);
771 static int vi_full_init(struct vi_info *);
772 static void vi_full_uninit(struct vi_info *);
773 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
774 static void quiesce_txq(struct sge_txq *);
775 static void quiesce_wrq(struct sge_wrq *);
776 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
777 static void quiesce_vi(struct vi_info *);
778 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
779     driver_intr_t *, void *, char *);
780 static int t4_free_irq(struct adapter *, struct irq *);
781 static void t4_init_atid_table(struct adapter *);
782 static void t4_free_atid_table(struct adapter *);
783 static void stop_atid_allocator(struct adapter *);
784 static void restart_atid_allocator(struct adapter *);
785 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
786 static void vi_refresh_stats(struct vi_info *);
787 static void cxgbe_refresh_stats(struct vi_info *);
788 static void cxgbe_tick(void *);
789 static void vi_tick(void *);
790 static void cxgbe_sysctls(struct port_info *);
791 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
792 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
793 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
794 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
795 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
796 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
797 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
798 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
799 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
800 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
802 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
803 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
804 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
805 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
806 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
807 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
808 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
809 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
810 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
811 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
812 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
813 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
814 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
817 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
818 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
822 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
824 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
825 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
826 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
827 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
828 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
829 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
830 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
831 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
839 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
840 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
841 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
842 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
843 #ifdef TCP_OFFLOAD
844 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
845 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
846 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
847 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
848 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
849 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
850 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
851 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
852 #endif
853 static int get_sge_context(struct adapter *, struct t4_sge_context *);
854 static int load_fw(struct adapter *, struct t4_data *);
855 static int load_cfg(struct adapter *, struct t4_data *);
856 static int load_boot(struct adapter *, struct t4_bootrom *);
857 static int load_bootcfg(struct adapter *, struct t4_data *);
858 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
859 static void free_offload_policy(struct t4_offload_policy *);
860 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
861 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
862 static int read_i2c(struct adapter *, struct t4_i2c_data *);
863 static int clear_stats(struct adapter *, u_int);
864 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
865 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
866 static inline int stop_adapter(struct adapter *);
867 static inline void set_adapter_hwstatus(struct adapter *, const bool);
868 static int stop_lld(struct adapter *);
869 static inline int restart_adapter(struct adapter *);
870 static int restart_lld(struct adapter *);
871 #ifdef TCP_OFFLOAD
872 static int toe_capability(struct vi_info *, bool);
873 static int deactivate_all_uld(struct adapter *);
874 static void stop_all_uld(struct adapter *);
875 static void restart_all_uld(struct adapter *);
876 #endif
877 #ifdef KERN_TLS
878 static int ktls_capability(struct adapter *, bool);
879 #endif
880 static int mod_event(module_t, int, void *);
881 static int notify_siblings(device_t, int);
882 static uint64_t vi_get_counter(if_t, ift_counter);
883 static uint64_t cxgbe_get_counter(if_t, ift_counter);
884 static void enable_vxlan_rx(struct adapter *);
885 static void reset_adapter_task(void *, int);
886 static void fatal_error_task(void *, int);
887 static void dump_devlog(struct adapter *);
888 static void dump_cim_regs(struct adapter *);
889 static void dump_cimla(struct adapter *);
890 
891 struct {
892 	uint16_t device;
893 	char *desc;
894 } t4_pciids[] = {
895 	{0xa000, "Chelsio Terminator 4 FPGA"},
896 	{0x4400, "Chelsio T440-dbg"},
897 	{0x4401, "Chelsio T420-CR"},
898 	{0x4402, "Chelsio T422-CR"},
899 	{0x4403, "Chelsio T440-CR"},
900 	{0x4404, "Chelsio T420-BCH"},
901 	{0x4405, "Chelsio T440-BCH"},
902 	{0x4406, "Chelsio T440-CH"},
903 	{0x4407, "Chelsio T420-SO"},
904 	{0x4408, "Chelsio T420-CX"},
905 	{0x4409, "Chelsio T420-BT"},
906 	{0x440a, "Chelsio T404-BT"},
907 	{0x440e, "Chelsio T440-LP-CR"},
908 }, t5_pciids[] = {
909 	{0xb000, "Chelsio Terminator 5 FPGA"},
910 	{0x5400, "Chelsio T580-dbg"},
911 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
912 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
913 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
914 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
915 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
916 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
917 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
918 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
919 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
920 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
921 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
922 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
923 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
924 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
925 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
926 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
927 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
928 
929 	/* Custom */
930 	{0x5483, "Custom T540-CR"},
931 	{0x5484, "Custom T540-BT"},
932 }, t6_pciids[] = {
933 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
934 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
935 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
936 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
937 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
938 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
939 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
940 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
941 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
942 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
943 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
944 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
945 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
946 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
947 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
948 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
949 
950 	/* Custom */
951 	{0x6480, "Custom T6225-CR"},
952 	{0x6481, "Custom T62100-CR"},
953 	{0x6482, "Custom T6225-CR"},
954 	{0x6483, "Custom T62100-CR"},
955 	{0x6484, "Custom T64100-CR"},
956 	{0x6485, "Custom T6240-SO"},
957 	{0x6486, "Custom T6225-SO-CR"},
958 	{0x6487, "Custom T6225-CR"},
959 };
960 
961 #ifdef TCP_OFFLOAD
962 /*
963  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
964  * be exactly the same for both rxq and ofld_rxq.
965  */
966 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
967 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
968 #endif
969 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
970 
971 static int
972 t4_probe(device_t dev)
973 {
974 	int i;
975 	uint16_t v = pci_get_vendor(dev);
976 	uint16_t d = pci_get_device(dev);
977 	uint8_t f = pci_get_function(dev);
978 
979 	if (v != PCI_VENDOR_ID_CHELSIO)
980 		return (ENXIO);
981 
982 	/* Attach only to PF0 of the FPGA */
983 	if (d == 0xa000 && f != 0)
984 		return (ENXIO);
985 
986 	for (i = 0; i < nitems(t4_pciids); i++) {
987 		if (d == t4_pciids[i].device) {
988 			device_set_desc(dev, t4_pciids[i].desc);
989 			return (BUS_PROBE_DEFAULT);
990 		}
991 	}
992 
993 	return (ENXIO);
994 }
995 
996 static int
997 t5_probe(device_t dev)
998 {
999 	int i;
1000 	uint16_t v = pci_get_vendor(dev);
1001 	uint16_t d = pci_get_device(dev);
1002 	uint8_t f = pci_get_function(dev);
1003 
1004 	if (v != PCI_VENDOR_ID_CHELSIO)
1005 		return (ENXIO);
1006 
1007 	/* Attach only to PF0 of the FPGA */
1008 	if (d == 0xb000 && f != 0)
1009 		return (ENXIO);
1010 
1011 	for (i = 0; i < nitems(t5_pciids); i++) {
1012 		if (d == t5_pciids[i].device) {
1013 			device_set_desc(dev, t5_pciids[i].desc);
1014 			return (BUS_PROBE_DEFAULT);
1015 		}
1016 	}
1017 
1018 	return (ENXIO);
1019 }
1020 
1021 static int
1022 t6_probe(device_t dev)
1023 {
1024 	int i;
1025 	uint16_t v = pci_get_vendor(dev);
1026 	uint16_t d = pci_get_device(dev);
1027 
1028 	if (v != PCI_VENDOR_ID_CHELSIO)
1029 		return (ENXIO);
1030 
1031 	for (i = 0; i < nitems(t6_pciids); i++) {
1032 		if (d == t6_pciids[i].device) {
1033 			device_set_desc(dev, t6_pciids[i].desc);
1034 			return (BUS_PROBE_DEFAULT);
1035 		}
1036 	}
1037 
1038 	return (ENXIO);
1039 }
1040 
1041 static void
1042 t5_attribute_workaround(device_t dev)
1043 {
1044 	device_t root_port;
1045 	uint32_t v;
1046 
1047 	/*
1048 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1049 	 * Ordering attributes when replying to a TLP from a Root
1050 	 * Port.  As a workaround, find the parent Root Port and
1051 	 * disable No Snoop and Relaxed Ordering.  Note that this
1052 	 * affects all devices under this root port.
1053 	 */
1054 	root_port = pci_find_pcie_root_port(dev);
1055 	if (root_port == NULL) {
1056 		device_printf(dev, "Unable to find parent root port\n");
1057 		return;
1058 	}
1059 
1060 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1061 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1062 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1063 	    0)
1064 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1065 		    device_get_nameunit(root_port));
1066 }
1067 
1068 static const struct devnames devnames[] = {
1069 	{
1070 		.nexus_name = "t4nex",
1071 		.ifnet_name = "cxgbe",
1072 		.vi_ifnet_name = "vcxgbe",
1073 		.pf03_drv_name = "t4iov",
1074 		.vf_nexus_name = "t4vf",
1075 		.vf_ifnet_name = "cxgbev"
1076 	}, {
1077 		.nexus_name = "t5nex",
1078 		.ifnet_name = "cxl",
1079 		.vi_ifnet_name = "vcxl",
1080 		.pf03_drv_name = "t5iov",
1081 		.vf_nexus_name = "t5vf",
1082 		.vf_ifnet_name = "cxlv"
1083 	}, {
1084 		.nexus_name = "t6nex",
1085 		.ifnet_name = "cc",
1086 		.vi_ifnet_name = "vcc",
1087 		.pf03_drv_name = "t6iov",
1088 		.vf_nexus_name = "t6vf",
1089 		.vf_ifnet_name = "ccv"
1090 	}
1091 };
1092 
1093 void
1094 t4_init_devnames(struct adapter *sc)
1095 {
1096 	int id;
1097 
1098 	id = chip_id(sc);
1099 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1100 		sc->names = &devnames[id - CHELSIO_T4];
1101 	else {
1102 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1103 		sc->names = NULL;
1104 	}
1105 }
1106 
1107 static int
1108 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1109 {
1110 	const char *parent, *name;
1111 	long value;
1112 	int line, unit;
1113 
1114 	line = 0;
1115 	parent = device_get_nameunit(sc->dev);
1116 	name = sc->names->ifnet_name;
1117 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1118 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1119 		    value == pi->port_id)
1120 			return (unit);
1121 	}
1122 	return (-1);
1123 }
1124 
1125 static void
1126 t4_calibration(void *arg)
1127 {
1128 	struct adapter *sc;
1129 	struct clock_sync *cur, *nex;
1130 	uint64_t hw;
1131 	sbintime_t sbt;
1132 	int next_up;
1133 
1134 	sc = (struct adapter *)arg;
1135 
1136 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1137 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1138 	sbt = sbinuptime();
1139 
1140 	cur = &sc->cal_info[sc->cal_current];
1141 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1142 	nex = &sc->cal_info[next_up];
1143 	if (__predict_false(sc->cal_count == 0)) {
1144 		/* First time in, just get the values in */
1145 		cur->hw_cur = hw;
1146 		cur->sbt_cur = sbt;
1147 		sc->cal_count++;
1148 		goto done;
1149 	}
1150 
1151 	if (cur->hw_cur == hw) {
1152 		/* The clock is not advancing? */
1153 		sc->cal_count = 0;
1154 		atomic_store_rel_int(&cur->gen, 0);
1155 		goto done;
1156 	}
1157 
1158 	seqc_write_begin(&nex->gen);
1159 	nex->hw_prev = cur->hw_cur;
1160 	nex->sbt_prev = cur->sbt_cur;
1161 	nex->hw_cur = hw;
1162 	nex->sbt_cur = sbt;
1163 	seqc_write_end(&nex->gen);
1164 	sc->cal_current = next_up;
1165 done:
1166 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1167 	    sc, C_DIRECT_EXEC);
1168 }
1169 
1170 static void
1171 t4_calibration_start(struct adapter *sc)
1172 {
1173 	/*
1174 	 * Here if we have not done a calibration
1175 	 * then do so otherwise start the appropriate
1176 	 * timer.
1177 	 */
1178 	int i;
1179 
1180 	for (i = 0; i < CNT_CAL_INFO; i++) {
1181 		sc->cal_info[i].gen = 0;
1182 	}
1183 	sc->cal_current = 0;
1184 	sc->cal_count = 0;
1185 	sc->cal_gen = 0;
1186 	t4_calibration(sc);
1187 }
1188 
1189 static int
1190 t4_attach(device_t dev)
1191 {
1192 	struct adapter *sc;
1193 	int rc = 0, i, j, rqidx, tqidx, nports;
1194 	struct make_dev_args mda;
1195 	struct intrs_and_queues iaq;
1196 	struct sge *s;
1197 	uint32_t *buf;
1198 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1199 	int ofld_tqidx;
1200 #endif
1201 #ifdef TCP_OFFLOAD
1202 	int ofld_rqidx;
1203 #endif
1204 #ifdef DEV_NETMAP
1205 	int nm_rqidx, nm_tqidx;
1206 #endif
1207 	int num_vis;
1208 
1209 	sc = device_get_softc(dev);
1210 	sc->dev = dev;
1211 	sysctl_ctx_init(&sc->ctx);
1212 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1213 
1214 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1215 		t5_attribute_workaround(dev);
1216 	pci_enable_busmaster(dev);
1217 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1218 		uint32_t v;
1219 
1220 		pci_set_max_read_req(dev, 4096);
1221 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1222 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1223 		if (pcie_relaxed_ordering == 0 &&
1224 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1225 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1226 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1227 		} else if (pcie_relaxed_ordering == 1 &&
1228 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1229 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1230 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1231 		}
1232 	}
1233 
1234 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1235 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1236 	sc->traceq = -1;
1237 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1238 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1239 	    device_get_nameunit(dev));
1240 
1241 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1242 	    device_get_nameunit(dev));
1243 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1244 	t4_add_adapter(sc);
1245 
1246 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1247 	TAILQ_INIT(&sc->sfl);
1248 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1249 
1250 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1251 
1252 	sc->policy = NULL;
1253 	rw_init(&sc->policy_lock, "connection offload policy");
1254 
1255 	callout_init(&sc->ktls_tick, 1);
1256 
1257 	callout_init(&sc->cal_callout, 1);
1258 
1259 	refcount_init(&sc->vxlan_refcount, 0);
1260 
1261 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1262 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1263 
1264 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1265 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1266 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1267 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1268 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1269 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1270 
1271 	rc = t4_map_bars_0_and_4(sc);
1272 	if (rc != 0)
1273 		goto done; /* error message displayed already */
1274 
1275 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1276 
1277 	/* Prepare the adapter for operation. */
1278 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1279 	rc = -t4_prep_adapter(sc, buf);
1280 	free(buf, M_CXGBE);
1281 	if (rc != 0) {
1282 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1283 		goto done;
1284 	}
1285 
1286 	/*
1287 	 * This is the real PF# to which we're attaching.  Works from within PCI
1288 	 * passthrough environments too, where pci_get_function() could return a
1289 	 * different PF# depending on the passthrough configuration.  We need to
1290 	 * use the real PF# in all our communication with the firmware.
1291 	 */
1292 	j = t4_read_reg(sc, A_PL_WHOAMI);
1293 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1294 	sc->mbox = sc->pf;
1295 
1296 	t4_init_devnames(sc);
1297 	if (sc->names == NULL) {
1298 		rc = ENOTSUP;
1299 		goto done; /* error message displayed already */
1300 	}
1301 
1302 	/*
1303 	 * Do this really early, with the memory windows set up even before the
1304 	 * character device.  The userland tool's register i/o and mem read
1305 	 * will work even in "recovery mode".
1306 	 */
1307 	setup_memwin(sc);
1308 	if (t4_init_devlog_params(sc, 0) == 0)
1309 		fixup_devlog_params(sc);
1310 	make_dev_args_init(&mda);
1311 	mda.mda_devsw = &t4_cdevsw;
1312 	mda.mda_uid = UID_ROOT;
1313 	mda.mda_gid = GID_WHEEL;
1314 	mda.mda_mode = 0600;
1315 	mda.mda_si_drv1 = sc;
1316 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1317 	if (rc != 0)
1318 		device_printf(dev, "failed to create nexus char device: %d.\n",
1319 		    rc);
1320 
1321 	/* Go no further if recovery mode has been requested. */
1322 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1323 		device_printf(dev, "recovery mode.\n");
1324 		goto done;
1325 	}
1326 
1327 #if defined(__i386__)
1328 	if ((cpu_feature & CPUID_CX8) == 0) {
1329 		device_printf(dev, "64 bit atomics not available.\n");
1330 		rc = ENOTSUP;
1331 		goto done;
1332 	}
1333 #endif
1334 
1335 	/* Contact the firmware and try to become the master driver. */
1336 	rc = contact_firmware(sc);
1337 	if (rc != 0)
1338 		goto done; /* error message displayed already */
1339 	MPASS(sc->flags & FW_OK);
1340 
1341 	rc = get_params__pre_init(sc);
1342 	if (rc != 0)
1343 		goto done; /* error message displayed already */
1344 
1345 	if (sc->flags & MASTER_PF) {
1346 		rc = partition_resources(sc);
1347 		if (rc != 0)
1348 			goto done; /* error message displayed already */
1349 	}
1350 
1351 	rc = get_params__post_init(sc);
1352 	if (rc != 0)
1353 		goto done; /* error message displayed already */
1354 
1355 	rc = set_params__post_init(sc);
1356 	if (rc != 0)
1357 		goto done; /* error message displayed already */
1358 
1359 	rc = t4_map_bar_2(sc);
1360 	if (rc != 0)
1361 		goto done; /* error message displayed already */
1362 
1363 	rc = t4_adj_doorbells(sc);
1364 	if (rc != 0)
1365 		goto done; /* error message displayed already */
1366 
1367 	rc = t4_create_dma_tag(sc);
1368 	if (rc != 0)
1369 		goto done; /* error message displayed already */
1370 
1371 	/*
1372 	 * First pass over all the ports - allocate VIs and initialize some
1373 	 * basic parameters like mac address, port type, etc.
1374 	 */
1375 	for_each_port(sc, i) {
1376 		struct port_info *pi;
1377 
1378 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1379 		sc->port[i] = pi;
1380 
1381 		/* These must be set before t4_port_init */
1382 		pi->adapter = sc;
1383 		pi->port_id = i;
1384 		/*
1385 		 * XXX: vi[0] is special so we can't delay this allocation until
1386 		 * pi->nvi's final value is known.
1387 		 */
1388 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1389 		    M_ZERO | M_WAITOK);
1390 
1391 		/*
1392 		 * Allocate the "main" VI and initialize parameters
1393 		 * like mac addr.
1394 		 */
1395 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1396 		if (rc != 0) {
1397 			device_printf(dev, "unable to initialize port %d: %d\n",
1398 			    i, rc);
1399 			free(pi->vi, M_CXGBE);
1400 			free(pi, M_CXGBE);
1401 			sc->port[i] = NULL;
1402 			goto done;
1403 		}
1404 
1405 		if (is_bt(pi->port_type))
1406 			setbit(&sc->bt_map, pi->tx_chan);
1407 		else
1408 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1409 
1410 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1411 		    device_get_nameunit(dev), i);
1412 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1413 		sc->chan_map[pi->tx_chan] = i;
1414 
1415 		/*
1416 		 * The MPS counter for FCS errors doesn't work correctly on the
1417 		 * T6 so we use the MAC counter here.  Which MAC is in use
1418 		 * depends on the link settings which will be known when the
1419 		 * link comes up.
1420 		 */
1421 		if (is_t6(sc))
1422 			pi->fcs_reg = -1;
1423 		else {
1424 			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1425 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1426 		}
1427 		pi->fcs_base = 0;
1428 
1429 		/* All VIs on this port share this media. */
1430 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1431 		    cxgbe_media_status);
1432 
1433 		PORT_LOCK(pi);
1434 		init_link_config(pi);
1435 		fixup_link_config(pi);
1436 		build_medialist(pi);
1437 		if (fixed_ifmedia(pi))
1438 			pi->flags |= FIXED_IFMEDIA;
1439 		PORT_UNLOCK(pi);
1440 
1441 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1442 		    t4_ifnet_unit(sc, pi));
1443 		if (pi->dev == NULL) {
1444 			device_printf(dev,
1445 			    "failed to add device for port %d.\n", i);
1446 			rc = ENXIO;
1447 			goto done;
1448 		}
1449 		pi->vi[0].dev = pi->dev;
1450 		device_set_softc(pi->dev, pi);
1451 	}
1452 
1453 	/*
1454 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1455 	 */
1456 	nports = sc->params.nports;
1457 	rc = cfg_itype_and_nqueues(sc, &iaq);
1458 	if (rc != 0)
1459 		goto done; /* error message displayed already */
1460 
1461 	num_vis = iaq.num_vis;
1462 	sc->intr_type = iaq.intr_type;
1463 	sc->intr_count = iaq.nirq;
1464 
1465 	s = &sc->sge;
1466 	s->nrxq = nports * iaq.nrxq;
1467 	s->ntxq = nports * iaq.ntxq;
1468 	if (num_vis > 1) {
1469 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1470 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1471 	}
1472 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1473 	s->neq += nports;		/* ctrl queues: 1 per port */
1474 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1475 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1476 	if (is_offload(sc) || is_ethoffload(sc)) {
1477 		s->nofldtxq = nports * iaq.nofldtxq;
1478 		if (num_vis > 1)
1479 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1480 		s->neq += s->nofldtxq;
1481 
1482 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1483 		    M_CXGBE, M_ZERO | M_WAITOK);
1484 	}
1485 #endif
1486 #ifdef TCP_OFFLOAD
1487 	if (is_offload(sc)) {
1488 		s->nofldrxq = nports * iaq.nofldrxq;
1489 		if (num_vis > 1)
1490 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1491 		s->neq += s->nofldrxq;	/* free list */
1492 		s->niq += s->nofldrxq;
1493 
1494 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1495 		    M_CXGBE, M_ZERO | M_WAITOK);
1496 	}
1497 #endif
1498 #ifdef DEV_NETMAP
1499 	s->nnmrxq = 0;
1500 	s->nnmtxq = 0;
1501 	if (t4_native_netmap & NN_MAIN_VI) {
1502 		s->nnmrxq += nports * iaq.nnmrxq;
1503 		s->nnmtxq += nports * iaq.nnmtxq;
1504 	}
1505 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1506 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1507 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1508 	}
1509 	s->neq += s->nnmtxq + s->nnmrxq;
1510 	s->niq += s->nnmrxq;
1511 
1512 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1513 	    M_CXGBE, M_ZERO | M_WAITOK);
1514 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1515 	    M_CXGBE, M_ZERO | M_WAITOK);
1516 #endif
1517 	MPASS(s->niq <= s->iqmap_sz);
1518 	MPASS(s->neq <= s->eqmap_sz);
1519 
1520 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1521 	    M_ZERO | M_WAITOK);
1522 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1523 	    M_ZERO | M_WAITOK);
1524 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1525 	    M_ZERO | M_WAITOK);
1526 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1527 	    M_ZERO | M_WAITOK);
1528 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1529 	    M_ZERO | M_WAITOK);
1530 
1531 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1532 	    M_ZERO | M_WAITOK);
1533 
1534 	t4_init_l2t(sc, M_WAITOK);
1535 	t4_init_smt(sc, M_WAITOK);
1536 	t4_init_tx_sched(sc);
1537 	t4_init_atid_table(sc);
1538 #ifdef RATELIMIT
1539 	t4_init_etid_table(sc);
1540 #endif
1541 #ifdef INET6
1542 	t4_init_clip_table(sc);
1543 #endif
1544 	if (sc->vres.key.size != 0)
1545 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1546 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1547 
1548 	/*
1549 	 * Second pass over the ports.  This time we know the number of rx and
1550 	 * tx queues that each port should get.
1551 	 */
1552 	rqidx = tqidx = 0;
1553 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1554 	ofld_tqidx = 0;
1555 #endif
1556 #ifdef TCP_OFFLOAD
1557 	ofld_rqidx = 0;
1558 #endif
1559 #ifdef DEV_NETMAP
1560 	nm_rqidx = nm_tqidx = 0;
1561 #endif
1562 	for_each_port(sc, i) {
1563 		struct port_info *pi = sc->port[i];
1564 		struct vi_info *vi;
1565 
1566 		if (pi == NULL)
1567 			continue;
1568 
1569 		pi->nvi = num_vis;
1570 		for_each_vi(pi, j, vi) {
1571 			vi->pi = pi;
1572 			vi->adapter = sc;
1573 			vi->first_intr = -1;
1574 			vi->qsize_rxq = t4_qsize_rxq;
1575 			vi->qsize_txq = t4_qsize_txq;
1576 
1577 			vi->first_rxq = rqidx;
1578 			vi->first_txq = tqidx;
1579 			vi->tmr_idx = t4_tmr_idx;
1580 			vi->pktc_idx = t4_pktc_idx;
1581 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1582 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1583 
1584 			rqidx += vi->nrxq;
1585 			tqidx += vi->ntxq;
1586 
1587 			if (j == 0 && vi->ntxq > 1)
1588 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1589 			else
1590 				vi->rsrv_noflowq = 0;
1591 
1592 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1593 			vi->first_ofld_txq = ofld_tqidx;
1594 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1595 			ofld_tqidx += vi->nofldtxq;
1596 #endif
1597 #ifdef TCP_OFFLOAD
1598 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1599 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1600 			vi->first_ofld_rxq = ofld_rqidx;
1601 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1602 
1603 			ofld_rqidx += vi->nofldrxq;
1604 #endif
1605 #ifdef DEV_NETMAP
1606 			vi->first_nm_rxq = nm_rqidx;
1607 			vi->first_nm_txq = nm_tqidx;
1608 			if (j == 0) {
1609 				vi->nnmrxq = iaq.nnmrxq;
1610 				vi->nnmtxq = iaq.nnmtxq;
1611 			} else {
1612 				vi->nnmrxq = iaq.nnmrxq_vi;
1613 				vi->nnmtxq = iaq.nnmtxq_vi;
1614 			}
1615 			nm_rqidx += vi->nnmrxq;
1616 			nm_tqidx += vi->nnmtxq;
1617 #endif
1618 		}
1619 	}
1620 
1621 	rc = t4_setup_intr_handlers(sc);
1622 	if (rc != 0) {
1623 		device_printf(dev,
1624 		    "failed to setup interrupt handlers: %d\n", rc);
1625 		goto done;
1626 	}
1627 
1628 	rc = bus_generic_probe(dev);
1629 	if (rc != 0) {
1630 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1631 		goto done;
1632 	}
1633 
1634 	/*
1635 	 * Ensure thread-safe mailbox access (in debug builds).
1636 	 *
1637 	 * So far this was the only thread accessing the mailbox but various
1638 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1639 	 * will access the mailbox from different threads.
1640 	 */
1641 	sc->flags |= CHK_MBOX_ACCESS;
1642 
1643 	rc = bus_generic_attach(dev);
1644 	if (rc != 0) {
1645 		device_printf(dev,
1646 		    "failed to attach all child ports: %d\n", rc);
1647 		goto done;
1648 	}
1649 	t4_calibration_start(sc);
1650 
1651 	device_printf(dev,
1652 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1653 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1654 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1655 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1656 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1657 
1658 	t4_set_desc(sc);
1659 
1660 	notify_siblings(dev, 0);
1661 
1662 done:
1663 	if (rc != 0 && sc->cdev) {
1664 		/* cdev was created and so cxgbetool works; recover that way. */
1665 		device_printf(dev,
1666 		    "error during attach, adapter is now in recovery mode.\n");
1667 		rc = 0;
1668 	}
1669 
1670 	if (rc != 0)
1671 		t4_detach_common(dev);
1672 	else
1673 		t4_sysctls(sc);
1674 
1675 	return (rc);
1676 }
1677 
1678 static int
1679 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1680 {
1681 	struct adapter *sc;
1682 	struct port_info *pi;
1683 	int i;
1684 
1685 	sc = device_get_softc(bus);
1686 	for_each_port(sc, i) {
1687 		pi = sc->port[i];
1688 		if (pi != NULL && pi->dev == dev) {
1689 			sbuf_printf(sb, "port=%d", pi->port_id);
1690 			break;
1691 		}
1692 	}
1693 	return (0);
1694 }
1695 
1696 static int
1697 t4_ready(device_t dev)
1698 {
1699 	struct adapter *sc;
1700 
1701 	sc = device_get_softc(dev);
1702 	if (sc->flags & FW_OK)
1703 		return (0);
1704 	return (ENXIO);
1705 }
1706 
1707 static int
1708 t4_read_port_device(device_t dev, int port, device_t *child)
1709 {
1710 	struct adapter *sc;
1711 	struct port_info *pi;
1712 
1713 	sc = device_get_softc(dev);
1714 	if (port < 0 || port >= MAX_NPORTS)
1715 		return (EINVAL);
1716 	pi = sc->port[port];
1717 	if (pi == NULL || pi->dev == NULL)
1718 		return (ENXIO);
1719 	*child = pi->dev;
1720 	return (0);
1721 }
1722 
1723 static int
1724 notify_siblings(device_t dev, int detaching)
1725 {
1726 	device_t sibling;
1727 	int error, i;
1728 
1729 	error = 0;
1730 	for (i = 0; i < PCI_FUNCMAX; i++) {
1731 		if (i == pci_get_function(dev))
1732 			continue;
1733 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1734 		    pci_get_slot(dev), i);
1735 		if (sibling == NULL || !device_is_attached(sibling))
1736 			continue;
1737 		if (detaching)
1738 			error = T4_DETACH_CHILD(sibling);
1739 		else
1740 			(void)T4_ATTACH_CHILD(sibling);
1741 		if (error)
1742 			break;
1743 	}
1744 	return (error);
1745 }
1746 
1747 /*
1748  * Idempotent
1749  */
1750 static int
1751 t4_detach(device_t dev)
1752 {
1753 	int rc;
1754 
1755 	rc = notify_siblings(dev, 1);
1756 	if (rc) {
1757 		device_printf(dev,
1758 		    "failed to detach sibling devices: %d\n", rc);
1759 		return (rc);
1760 	}
1761 
1762 	return (t4_detach_common(dev));
1763 }
1764 
1765 int
1766 t4_detach_common(device_t dev)
1767 {
1768 	struct adapter *sc;
1769 	struct port_info *pi;
1770 	int i, rc;
1771 
1772 	sc = device_get_softc(dev);
1773 
1774 #ifdef TCP_OFFLOAD
1775 	rc = deactivate_all_uld(sc);
1776 	if (rc) {
1777 		device_printf(dev,
1778 		    "failed to detach upper layer drivers: %d\n", rc);
1779 		return (rc);
1780 	}
1781 #endif
1782 
1783 	if (sc->cdev) {
1784 		destroy_dev(sc->cdev);
1785 		sc->cdev = NULL;
1786 	}
1787 
1788 	sx_xlock(&t4_list_lock);
1789 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1790 	sx_xunlock(&t4_list_lock);
1791 
1792 	sc->flags &= ~CHK_MBOX_ACCESS;
1793 	if (sc->flags & FULL_INIT_DONE) {
1794 		if (!(sc->flags & IS_VF))
1795 			t4_intr_disable(sc);
1796 	}
1797 
1798 	if (device_is_attached(dev)) {
1799 		rc = bus_generic_detach(dev);
1800 		if (rc) {
1801 			device_printf(dev,
1802 			    "failed to detach child devices: %d\n", rc);
1803 			return (rc);
1804 		}
1805 	}
1806 
1807 	for (i = 0; i < sc->intr_count; i++)
1808 		t4_free_irq(sc, &sc->irq[i]);
1809 
1810 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1811 		t4_free_tx_sched(sc);
1812 
1813 	for (i = 0; i < MAX_NPORTS; i++) {
1814 		pi = sc->port[i];
1815 		if (pi) {
1816 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1817 			if (pi->dev)
1818 				device_delete_child(dev, pi->dev);
1819 
1820 			mtx_destroy(&pi->pi_lock);
1821 			free(pi->vi, M_CXGBE);
1822 			free(pi, M_CXGBE);
1823 		}
1824 	}
1825 	callout_stop(&sc->cal_callout);
1826 	callout_drain(&sc->cal_callout);
1827 	device_delete_children(dev);
1828 	sysctl_ctx_free(&sc->ctx);
1829 	adapter_full_uninit(sc);
1830 
1831 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1832 		t4_fw_bye(sc, sc->mbox);
1833 
1834 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1835 		pci_release_msi(dev);
1836 
1837 	if (sc->regs_res)
1838 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1839 		    sc->regs_res);
1840 
1841 	if (sc->udbs_res)
1842 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1843 		    sc->udbs_res);
1844 
1845 	if (sc->msix_res)
1846 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1847 		    sc->msix_res);
1848 
1849 	if (sc->l2t)
1850 		t4_free_l2t(sc);
1851 	if (sc->smt)
1852 		t4_free_smt(sc->smt);
1853 	t4_free_atid_table(sc);
1854 #ifdef RATELIMIT
1855 	t4_free_etid_table(sc);
1856 #endif
1857 	if (sc->key_map)
1858 		vmem_destroy(sc->key_map);
1859 #ifdef INET6
1860 	t4_destroy_clip_table(sc);
1861 #endif
1862 
1863 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1864 	free(sc->sge.ofld_txq, M_CXGBE);
1865 #endif
1866 #ifdef TCP_OFFLOAD
1867 	free(sc->sge.ofld_rxq, M_CXGBE);
1868 #endif
1869 #ifdef DEV_NETMAP
1870 	free(sc->sge.nm_rxq, M_CXGBE);
1871 	free(sc->sge.nm_txq, M_CXGBE);
1872 #endif
1873 	free(sc->irq, M_CXGBE);
1874 	free(sc->sge.rxq, M_CXGBE);
1875 	free(sc->sge.txq, M_CXGBE);
1876 	free(sc->sge.ctrlq, M_CXGBE);
1877 	free(sc->sge.iqmap, M_CXGBE);
1878 	free(sc->sge.eqmap, M_CXGBE);
1879 	free(sc->tids.ftid_tab, M_CXGBE);
1880 	free(sc->tids.hpftid_tab, M_CXGBE);
1881 	free_hftid_hash(&sc->tids);
1882 	free(sc->tids.tid_tab, M_CXGBE);
1883 	t4_destroy_dma_tag(sc);
1884 
1885 	callout_drain(&sc->ktls_tick);
1886 	callout_drain(&sc->sfl_callout);
1887 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1888 		mtx_destroy(&sc->tids.ftid_lock);
1889 		cv_destroy(&sc->tids.ftid_cv);
1890 	}
1891 	if (mtx_initialized(&sc->tids.atid_lock))
1892 		mtx_destroy(&sc->tids.atid_lock);
1893 	if (mtx_initialized(&sc->ifp_lock))
1894 		mtx_destroy(&sc->ifp_lock);
1895 
1896 	if (rw_initialized(&sc->policy_lock)) {
1897 		rw_destroy(&sc->policy_lock);
1898 #ifdef TCP_OFFLOAD
1899 		if (sc->policy != NULL)
1900 			free_offload_policy(sc->policy);
1901 #endif
1902 	}
1903 
1904 	for (i = 0; i < NUM_MEMWIN; i++) {
1905 		struct memwin *mw = &sc->memwin[i];
1906 
1907 		if (rw_initialized(&mw->mw_lock))
1908 			rw_destroy(&mw->mw_lock);
1909 	}
1910 
1911 	mtx_destroy(&sc->sfl_lock);
1912 	mtx_destroy(&sc->reg_lock);
1913 	mtx_destroy(&sc->sc_lock);
1914 
1915 	bzero(sc, sizeof(*sc));
1916 
1917 	return (0);
1918 }
1919 
1920 static inline int
1921 stop_adapter(struct adapter *sc)
1922 {
1923 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1924 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1925 			 __func__, curthread, sc->flags, sc->error_flags);
1926 		return (EALREADY);
1927 	}
1928 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1929 		 sc->flags, sc->error_flags);
1930 	return (t4_shutdown_adapter(sc));
1931 }
1932 
1933 static inline int
1934 restart_adapter(struct adapter *sc)
1935 {
1936 	uint32_t val;
1937 
1938 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1939 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1940 			 __func__, curthread, sc->flags, sc->error_flags);
1941 		return (EALREADY);
1942 	}
1943 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1944 		 sc->flags, sc->error_flags);
1945 
1946 	MPASS(hw_off_limits(sc));
1947 	MPASS((sc->flags & FW_OK) == 0);
1948 	MPASS((sc->flags & MASTER_PF) == 0);
1949 	MPASS(sc->reset_thread == NULL);
1950 
1951 	/*
1952 	 * The adapter is supposed to be back on PCIE with its config space and
1953 	 * BARs restored to their state before reset.  Register access via
1954 	 * t4_read_reg BAR0 should just work.
1955 	 */
1956 	sc->reset_thread = curthread;
1957 	val = t4_read_reg(sc, A_PL_WHOAMI);
1958 	if (val == 0xffffffff || val == 0xeeeeeeee) {
1959 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
1960 		sc->reset_thread = NULL;
1961 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
1962 		return (ENXIO);
1963 	}
1964 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
1965 	atomic_add_int(&sc->incarnation, 1);
1966 	atomic_add_int(&sc->num_resets, 1);
1967 
1968 	return (0);
1969 }
1970 
1971 static inline void
1972 set_adapter_hwstatus(struct adapter *sc, const bool usable)
1973 {
1974 	mtx_lock(&sc->reg_lock);
1975 	if (usable) {
1976 		/* Must be marked reusable by the designated thread. */
1977 		MPASS(sc->reset_thread == curthread);
1978 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
1979 	} else {
1980 		/* Mark the adapter totally off limits. */
1981 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
1982 		sc->flags &= ~(FW_OK | MASTER_PF);
1983 		sc->reset_thread = NULL;
1984 	}
1985 	mtx_unlock(&sc->reg_lock);
1986 }
1987 
1988 static int
1989 stop_lld(struct adapter *sc)
1990 {
1991 	struct port_info *pi;
1992 	struct vi_info *vi;
1993 	if_t ifp;
1994 	struct sge_rxq *rxq;
1995 	struct sge_txq *txq;
1996 	struct sge_wrq *wrq;
1997 #ifdef TCP_OFFLOAD
1998 	struct sge_ofld_rxq *ofld_rxq;
1999 #endif
2000 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2001 	struct sge_ofld_txq *ofld_txq;
2002 #endif
2003 	int rc, i, j, k;
2004 
2005 	/*
2006 	 * XXX: Can there be a synch_op in progress that will hang because
2007 	 * hardware has been stopped?  We'll hang too and the solution will be
2008 	 * to use a version of begin_synch_op that wakes up existing synch_op
2009 	 * with errors.  Maybe stop_adapter should do this wakeup?
2010 	 *
2011 	 * I don't think any synch_op could get stranded waiting for DMA or
2012 	 * interrupt so I think we're okay here.  Remove this comment block
2013 	 * after testing.
2014 	 */
2015 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2016 	if (rc != 0)
2017 		return (ENXIO);
2018 
2019 	/* Quiesce all activity. */
2020 	for_each_port(sc, i) {
2021 		pi = sc->port[i];
2022 		pi->vxlan_tcam_entry = false;
2023 
2024 		PORT_LOCK(pi);
2025 		if (pi->up_vis > 0) {
2026 			/*
2027 			 * t4_shutdown_adapter has already shut down all the
2028 			 * PHYs but it also disables interrupts and DMA so there
2029 			 * won't be a link interrupt.  So we update the state
2030 			 * manually and inform the kernel.
2031 			 */
2032 			pi->link_cfg.link_ok = false;
2033 			t4_os_link_changed(pi);
2034 		}
2035 		PORT_UNLOCK(pi);
2036 
2037 		for_each_vi(pi, j, vi) {
2038 			vi->xact_addr_filt = -1;
2039 			mtx_lock(&vi->tick_mtx);
2040 			vi->flags |= VI_SKIP_STATS;
2041 			mtx_unlock(&vi->tick_mtx);
2042 			if (!(vi->flags & VI_INIT_DONE))
2043 				continue;
2044 
2045 			ifp = vi->ifp;
2046 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2047 				mtx_lock(&vi->tick_mtx);
2048 				callout_stop(&vi->tick);
2049 				mtx_unlock(&vi->tick_mtx);
2050 				callout_drain(&vi->tick);
2051 			}
2052 
2053 			/*
2054 			 * Note that the HW is not available.
2055 			 */
2056 			for_each_txq(vi, k, txq) {
2057 				TXQ_LOCK(txq);
2058 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2059 				TXQ_UNLOCK(txq);
2060 			}
2061 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2062 			for_each_ofld_txq(vi, k, ofld_txq) {
2063 				TXQ_LOCK(&ofld_txq->wrq);
2064 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2065 				TXQ_UNLOCK(&ofld_txq->wrq);
2066 			}
2067 #endif
2068 			for_each_rxq(vi, k, rxq) {
2069 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2070 			}
2071 #if defined(TCP_OFFLOAD)
2072 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2073 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2074 			}
2075 #endif
2076 
2077 			quiesce_vi(vi);
2078 		}
2079 
2080 		if (sc->flags & FULL_INIT_DONE) {
2081 			/* Control queue */
2082 			wrq = &sc->sge.ctrlq[i];
2083 			TXQ_LOCK(wrq);
2084 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2085 			TXQ_UNLOCK(wrq);
2086 			quiesce_wrq(wrq);
2087 		}
2088 	}
2089 	if (sc->flags & FULL_INIT_DONE) {
2090 		/* Firmware event queue */
2091 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2092 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2093 	}
2094 
2095 	/* Stop calibration */
2096 	callout_stop(&sc->cal_callout);
2097 	callout_drain(&sc->cal_callout);
2098 
2099 	if (t4_clock_gate_on_suspend) {
2100 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2101 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2102 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2103 	}
2104 
2105 	end_synchronized_op(sc, 0);
2106 
2107 	stop_atid_allocator(sc);
2108 	t4_stop_l2t(sc);
2109 
2110 	return (rc);
2111 }
2112 
2113 static int
2114 t4_suspend(device_t dev)
2115 {
2116 	struct adapter *sc = device_get_softc(dev);
2117 
2118 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2119 	stop_adapter(sc);
2120 	stop_lld(sc);
2121 #ifdef TCP_OFFLOAD
2122 	stop_all_uld(sc);
2123 #endif
2124 	set_adapter_hwstatus(sc, false);
2125 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2126 
2127 	return (0);
2128 }
2129 
2130 struct adapter_pre_reset_state {
2131 	u_int flags;
2132 	uint16_t nbmcaps;
2133 	uint16_t linkcaps;
2134 	uint16_t switchcaps;
2135 	uint16_t niccaps;
2136 	uint16_t toecaps;
2137 	uint16_t rdmacaps;
2138 	uint16_t cryptocaps;
2139 	uint16_t iscsicaps;
2140 	uint16_t fcoecaps;
2141 
2142 	u_int cfcsum;
2143 	char cfg_file[32];
2144 
2145 	struct adapter_params params;
2146 	struct t4_virt_res vres;
2147 	struct tid_info tids;
2148 	struct sge sge;
2149 
2150 	int rawf_base;
2151 	int nrawf;
2152 
2153 };
2154 
2155 static void
2156 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2157 {
2158 
2159 	ASSERT_SYNCHRONIZED_OP(sc);
2160 
2161 	o->flags = sc->flags;
2162 
2163 	o->nbmcaps =  sc->nbmcaps;
2164 	o->linkcaps = sc->linkcaps;
2165 	o->switchcaps = sc->switchcaps;
2166 	o->niccaps = sc->niccaps;
2167 	o->toecaps = sc->toecaps;
2168 	o->rdmacaps = sc->rdmacaps;
2169 	o->cryptocaps = sc->cryptocaps;
2170 	o->iscsicaps = sc->iscsicaps;
2171 	o->fcoecaps = sc->fcoecaps;
2172 
2173 	o->cfcsum = sc->cfcsum;
2174 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2175 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2176 
2177 	o->params = sc->params;
2178 	o->vres = sc->vres;
2179 	o->tids = sc->tids;
2180 	o->sge = sc->sge;
2181 
2182 	o->rawf_base = sc->rawf_base;
2183 	o->nrawf = sc->nrawf;
2184 }
2185 
2186 static int
2187 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2188 {
2189 	int rc = 0;
2190 
2191 	ASSERT_SYNCHRONIZED_OP(sc);
2192 
2193 	/* Capabilities */
2194 #define COMPARE_CAPS(c) do { \
2195 	if (o->c##caps != sc->c##caps) { \
2196 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2197 		    sc->c##caps); \
2198 		rc = EINVAL; \
2199 	} \
2200 } while (0)
2201 	COMPARE_CAPS(nbm);
2202 	COMPARE_CAPS(link);
2203 	COMPARE_CAPS(switch);
2204 	COMPARE_CAPS(nic);
2205 	COMPARE_CAPS(toe);
2206 	COMPARE_CAPS(rdma);
2207 	COMPARE_CAPS(crypto);
2208 	COMPARE_CAPS(iscsi);
2209 	COMPARE_CAPS(fcoe);
2210 #undef COMPARE_CAPS
2211 
2212 	/* Firmware config file */
2213 	if (o->cfcsum != sc->cfcsum) {
2214 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2215 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2216 		rc = EINVAL;
2217 	}
2218 
2219 #define COMPARE_PARAM(p, name) do { \
2220 	if (o->p != sc->p) { \
2221 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2222 		rc = EINVAL; \
2223 	} \
2224 } while (0)
2225 	COMPARE_PARAM(sge.iq_start, iq_start);
2226 	COMPARE_PARAM(sge.eq_start, eq_start);
2227 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2228 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2229 	COMPARE_PARAM(tids.nftids, nftids);
2230 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2231 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2232 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2233 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2234 	COMPARE_PARAM(tids.tid_base, tid_base);
2235 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2236 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2237 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2238 	COMPARE_PARAM(rawf_base, rawf_base);
2239 	COMPARE_PARAM(nrawf, nrawf);
2240 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2241 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2242 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2243 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2244 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2245 	COMPARE_PARAM(tids.ntids, ntids);
2246 	COMPARE_PARAM(tids.etid_base, etid_base);
2247 	COMPARE_PARAM(tids.etid_end, etid_end);
2248 	COMPARE_PARAM(tids.netids, netids);
2249 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2250 	COMPARE_PARAM(params.ethoffload, ethoffload);
2251 	COMPARE_PARAM(tids.natids, natids);
2252 	COMPARE_PARAM(tids.stid_base, stid_base);
2253 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2254 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2255 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2256 	COMPARE_PARAM(vres.stag.start, stag_start);
2257 	COMPARE_PARAM(vres.stag.size, stag_size);
2258 	COMPARE_PARAM(vres.rq.start, rq_start);
2259 	COMPARE_PARAM(vres.rq.size, rq_size);
2260 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2261 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2262 	COMPARE_PARAM(vres.qp.start, qp_start);
2263 	COMPARE_PARAM(vres.qp.size, qp_size);
2264 	COMPARE_PARAM(vres.cq.start, cq_start);
2265 	COMPARE_PARAM(vres.cq.size, cq_size);
2266 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2267 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2268 	COMPARE_PARAM(vres.srq.start, srq_start);
2269 	COMPARE_PARAM(vres.srq.size, srq_size);
2270 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2271 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2272 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2273 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2274 	COMPARE_PARAM(vres.key.start, key_start);
2275 	COMPARE_PARAM(vres.key.size, key_size);
2276 #undef COMPARE_PARAM
2277 
2278 	return (rc);
2279 }
2280 
2281 static int
2282 restart_lld(struct adapter *sc)
2283 {
2284 	struct adapter_pre_reset_state *old_state = NULL;
2285 	struct port_info *pi;
2286 	struct vi_info *vi;
2287 	if_t ifp;
2288 	struct sge_txq *txq;
2289 	int rc, i, j, k;
2290 
2291 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2292 	if (rc != 0)
2293 		return (ENXIO);
2294 
2295 	/* Restore memory window. */
2296 	setup_memwin(sc);
2297 
2298 	/* Go no further if recovery mode has been requested. */
2299 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2300 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2301 		rc = 0;
2302 		set_adapter_hwstatus(sc, true);
2303 		goto done;
2304 	}
2305 
2306 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2307 	save_caps_and_params(sc, old_state);
2308 
2309 	/* Reestablish contact with firmware and become the primary PF. */
2310 	rc = contact_firmware(sc);
2311 	if (rc != 0)
2312 		goto done; /* error message displayed already */
2313 	MPASS(sc->flags & FW_OK);
2314 
2315 	if (sc->flags & MASTER_PF) {
2316 		rc = partition_resources(sc);
2317 		if (rc != 0)
2318 			goto done; /* error message displayed already */
2319 	}
2320 
2321 	rc = get_params__post_init(sc);
2322 	if (rc != 0)
2323 		goto done; /* error message displayed already */
2324 
2325 	rc = set_params__post_init(sc);
2326 	if (rc != 0)
2327 		goto done; /* error message displayed already */
2328 
2329 	rc = compare_caps_and_params(sc, old_state);
2330 	if (rc != 0)
2331 		goto done; /* error message displayed already */
2332 
2333 	for_each_port(sc, i) {
2334 		pi = sc->port[i];
2335 		MPASS(pi != NULL);
2336 		MPASS(pi->vi != NULL);
2337 		MPASS(pi->vi[0].dev == pi->dev);
2338 
2339 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2340 		if (rc != 0) {
2341 			CH_ERR(sc,
2342 			    "failed to re-initialize port %d: %d\n", i, rc);
2343 			goto done;
2344 		}
2345 		MPASS(sc->chan_map[pi->tx_chan] == i);
2346 
2347 		PORT_LOCK(pi);
2348 		fixup_link_config(pi);
2349 		build_medialist(pi);
2350 		PORT_UNLOCK(pi);
2351 		for_each_vi(pi, j, vi) {
2352 			if (IS_MAIN_VI(vi))
2353 				continue;
2354 			rc = alloc_extra_vi(sc, pi, vi);
2355 			if (rc != 0) {
2356 				CH_ERR(vi,
2357 				    "failed to re-allocate extra VI: %d\n", rc);
2358 				goto done;
2359 			}
2360 		}
2361 	}
2362 
2363 	/*
2364 	 * Interrupts and queues are about to be enabled and other threads will
2365 	 * want to access the hardware too.  It is safe to do so.  Note that
2366 	 * this thread is still in the middle of a synchronized_op.
2367 	 */
2368 	set_adapter_hwstatus(sc, true);
2369 
2370 	if (sc->flags & FULL_INIT_DONE) {
2371 		rc = adapter_full_init(sc);
2372 		if (rc != 0) {
2373 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2374 			goto done;
2375 		}
2376 
2377 		if (sc->vxlan_refcount > 0)
2378 			enable_vxlan_rx(sc);
2379 
2380 		for_each_port(sc, i) {
2381 			pi = sc->port[i];
2382 			for_each_vi(pi, j, vi) {
2383 				mtx_lock(&vi->tick_mtx);
2384 				vi->flags &= ~VI_SKIP_STATS;
2385 				mtx_unlock(&vi->tick_mtx);
2386 				if (!(vi->flags & VI_INIT_DONE))
2387 					continue;
2388 				rc = vi_full_init(vi);
2389 				if (rc != 0) {
2390 					CH_ERR(vi, "failed to re-initialize "
2391 					    "interface: %d\n", rc);
2392 					goto done;
2393 				}
2394 
2395 				ifp = vi->ifp;
2396 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2397 					continue;
2398 				/*
2399 				 * Note that we do not setup multicast addresses
2400 				 * in the first pass.  This ensures that the
2401 				 * unicast DMACs for all VIs on all ports get an
2402 				 * MPS TCAM entry.
2403 				 */
2404 				rc = update_mac_settings(ifp, XGMAC_ALL &
2405 				    ~XGMAC_MCADDRS);
2406 				if (rc != 0) {
2407 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2408 					goto done;
2409 				}
2410 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2411 				    true);
2412 				if (rc != 0) {
2413 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2414 					goto done;
2415 				}
2416 				for_each_txq(vi, k, txq) {
2417 					TXQ_LOCK(txq);
2418 					txq->eq.flags |= EQ_ENABLED;
2419 					TXQ_UNLOCK(txq);
2420 				}
2421 				mtx_lock(&vi->tick_mtx);
2422 				callout_schedule(&vi->tick, hz);
2423 				mtx_unlock(&vi->tick_mtx);
2424 			}
2425 			PORT_LOCK(pi);
2426 			if (pi->up_vis > 0) {
2427 				t4_update_port_info(pi);
2428 				fixup_link_config(pi);
2429 				build_medialist(pi);
2430 				apply_link_config(pi);
2431 				if (pi->link_cfg.link_ok)
2432 					t4_os_link_changed(pi);
2433 			}
2434 			PORT_UNLOCK(pi);
2435 		}
2436 
2437 		/* Now reprogram the L2 multicast addresses. */
2438 		for_each_port(sc, i) {
2439 			pi = sc->port[i];
2440 			for_each_vi(pi, j, vi) {
2441 				if (!(vi->flags & VI_INIT_DONE))
2442 					continue;
2443 				ifp = vi->ifp;
2444 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2445 					continue;
2446 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2447 				if (rc != 0) {
2448 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2449 					rc = 0;	/* carry on */
2450 				}
2451 			}
2452 		}
2453 	}
2454 
2455 	/* Reset all calibration */
2456 	t4_calibration_start(sc);
2457 done:
2458 	end_synchronized_op(sc, 0);
2459 	free(old_state, M_CXGBE);
2460 
2461 	restart_atid_allocator(sc);
2462 	t4_restart_l2t(sc);
2463 
2464 	return (rc);
2465 }
2466 
2467 static int
2468 t4_resume(device_t dev)
2469 {
2470 	struct adapter *sc = device_get_softc(dev);
2471 
2472 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2473 	restart_adapter(sc);
2474 	restart_lld(sc);
2475 #ifdef TCP_OFFLOAD
2476 	restart_all_uld(sc);
2477 #endif
2478 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2479 
2480 	return (0);
2481 }
2482 
2483 static int
2484 t4_reset_prepare(device_t dev, device_t child)
2485 {
2486 	struct adapter *sc = device_get_softc(dev);
2487 
2488 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2489 	return (0);
2490 }
2491 
2492 static int
2493 t4_reset_post(device_t dev, device_t child)
2494 {
2495 	struct adapter *sc = device_get_softc(dev);
2496 
2497 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2498 	return (0);
2499 }
2500 
2501 static int
2502 reset_adapter_with_pci_bus_reset(struct adapter *sc)
2503 {
2504 	int rc;
2505 
2506 	mtx_lock(&Giant);
2507 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2508 	mtx_unlock(&Giant);
2509 	return (rc);
2510 }
2511 
2512 static int
2513 reset_adapter_with_pl_rst(struct adapter *sc)
2514 {
2515 	stop_adapter(sc);
2516 	stop_lld(sc);
2517 #ifdef TCP_OFFLOAD
2518 	stop_all_uld(sc);
2519 #endif
2520 	set_adapter_hwstatus(sc, false);
2521 
2522 	/* This is a t4_write_reg without the hw_off_limits check. */
2523 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2524 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2525 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2526 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2527 
2528 	restart_adapter(sc);
2529 	restart_lld(sc);
2530 #ifdef TCP_OFFLOAD
2531 	restart_all_uld(sc);
2532 #endif
2533 
2534 	return (0);
2535 }
2536 
2537 static inline int
2538 reset_adapter(struct adapter *sc)
2539 {
2540 	if (vm_guest == 0)
2541 		return (reset_adapter_with_pci_bus_reset(sc));
2542 	else
2543 		return (reset_adapter_with_pl_rst(sc));
2544 }
2545 
2546 static void
2547 reset_adapter_task(void *arg, int pending)
2548 {
2549 	struct adapter *sc = arg;
2550 	const int flags = sc->flags;
2551 	const int eflags = sc->error_flags;
2552 	int rc;
2553 
2554 	if (pending > 1)
2555 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2556 	rc = reset_adapter(sc);
2557 	if (rc != 0) {
2558 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2559 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2560 		       rc, flags, sc->flags, eflags, sc->error_flags);
2561 	}
2562 }
2563 
2564 static int
2565 cxgbe_probe(device_t dev)
2566 {
2567 	struct port_info *pi = device_get_softc(dev);
2568 
2569 	device_set_descf(dev, "port %d", pi->port_id);
2570 
2571 	return (BUS_PROBE_DEFAULT);
2572 }
2573 
2574 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2575     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2576     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2577     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2578 #define T4_CAP_ENABLE (T4_CAP)
2579 
2580 static void
2581 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2582 {
2583 	if_t ifp;
2584 	struct sbuf *sb;
2585 	struct sysctl_ctx_list *ctx = &vi->ctx;
2586 	struct sysctl_oid_list *children;
2587 	struct pfil_head_args pa;
2588 	struct adapter *sc = vi->adapter;
2589 
2590 	sysctl_ctx_init(ctx);
2591 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2592 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2593 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2594 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2595 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2596 #ifdef DEV_NETMAP
2597 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2598 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2599 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2600 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2601 #endif
2602 #ifdef TCP_OFFLOAD
2603 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2604 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2605 #endif
2606 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2607 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2608 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2609 #endif
2610 
2611 	vi->xact_addr_filt = -1;
2612 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2613 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2614 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2615 		vi->flags |= TX_USES_VM_WR;
2616 
2617 	/* Allocate an ifnet and set it up */
2618 	ifp = if_alloc_dev(IFT_ETHER, dev);
2619 	vi->ifp = ifp;
2620 	if_setsoftc(ifp, vi);
2621 
2622 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2623 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2624 
2625 	if_setinitfn(ifp, cxgbe_init);
2626 	if_setioctlfn(ifp, cxgbe_ioctl);
2627 	if_settransmitfn(ifp, cxgbe_transmit);
2628 	if_setqflushfn(ifp, cxgbe_qflush);
2629 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2630 		if_setgetcounterfn(ifp, vi_get_counter);
2631 	else
2632 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2633 #if defined(KERN_TLS) || defined(RATELIMIT)
2634 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2635 #endif
2636 #ifdef RATELIMIT
2637 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2638 #endif
2639 
2640 	if_setcapabilities(ifp, T4_CAP);
2641 	if_setcapenable(ifp, T4_CAP_ENABLE);
2642 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2643 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2644 	if (chip_id(sc) >= CHELSIO_T6) {
2645 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2646 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2647 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2648 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2649 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2650 	}
2651 
2652 #ifdef TCP_OFFLOAD
2653 	if (vi->nofldrxq != 0)
2654 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2655 #endif
2656 #ifdef RATELIMIT
2657 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2658 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2659 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2660 	}
2661 #endif
2662 
2663 	if_sethwtsomax(ifp, IP_MAXPACKET);
2664 	if (vi->flags & TX_USES_VM_WR)
2665 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2666 	else
2667 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2668 #ifdef RATELIMIT
2669 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2670 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2671 #endif
2672 	if_sethwtsomaxsegsize(ifp, 65536);
2673 #ifdef KERN_TLS
2674 	if (is_ktls(sc)) {
2675 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2676 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2677 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2678 	}
2679 #endif
2680 
2681 	ether_ifattach(ifp, vi->hw_addr);
2682 #ifdef DEV_NETMAP
2683 	if (vi->nnmrxq != 0)
2684 		cxgbe_nm_attach(vi);
2685 #endif
2686 	sb = sbuf_new_auto();
2687 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2688 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2689 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2690 	case IFCAP_TOE:
2691 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2692 		break;
2693 	case IFCAP_TOE | IFCAP_TXRTLMT:
2694 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2695 		break;
2696 	case IFCAP_TXRTLMT:
2697 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2698 		break;
2699 	}
2700 #endif
2701 #ifdef TCP_OFFLOAD
2702 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2703 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2704 #endif
2705 #ifdef DEV_NETMAP
2706 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2707 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2708 		    vi->nnmtxq, vi->nnmrxq);
2709 #endif
2710 	sbuf_finish(sb);
2711 	device_printf(dev, "%s\n", sbuf_data(sb));
2712 	sbuf_delete(sb);
2713 
2714 	vi_sysctls(vi);
2715 
2716 	pa.pa_version = PFIL_VERSION;
2717 	pa.pa_flags = PFIL_IN;
2718 	pa.pa_type = PFIL_TYPE_ETHERNET;
2719 	pa.pa_headname = if_name(ifp);
2720 	vi->pfil = pfil_head_register(&pa);
2721 }
2722 
2723 static int
2724 cxgbe_attach(device_t dev)
2725 {
2726 	struct port_info *pi = device_get_softc(dev);
2727 	struct adapter *sc = pi->adapter;
2728 	struct vi_info *vi;
2729 	int i;
2730 
2731 	sysctl_ctx_init(&pi->ctx);
2732 
2733 	cxgbe_vi_attach(dev, &pi->vi[0]);
2734 
2735 	for_each_vi(pi, i, vi) {
2736 		if (i == 0)
2737 			continue;
2738 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2739 		if (vi->dev == NULL) {
2740 			device_printf(dev, "failed to add VI %d\n", i);
2741 			continue;
2742 		}
2743 		device_set_softc(vi->dev, vi);
2744 	}
2745 
2746 	cxgbe_sysctls(pi);
2747 
2748 	bus_generic_attach(dev);
2749 
2750 	return (0);
2751 }
2752 
2753 static void
2754 cxgbe_vi_detach(struct vi_info *vi)
2755 {
2756 	if_t ifp = vi->ifp;
2757 
2758 	if (vi->pfil != NULL) {
2759 		pfil_head_unregister(vi->pfil);
2760 		vi->pfil = NULL;
2761 	}
2762 
2763 	ether_ifdetach(ifp);
2764 
2765 	/* Let detach proceed even if these fail. */
2766 #ifdef DEV_NETMAP
2767 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2768 		cxgbe_nm_detach(vi);
2769 #endif
2770 	cxgbe_uninit_synchronized(vi);
2771 	callout_drain(&vi->tick);
2772 	mtx_destroy(&vi->tick_mtx);
2773 	sysctl_ctx_free(&vi->ctx);
2774 	vi_full_uninit(vi);
2775 
2776 	if_free(vi->ifp);
2777 	vi->ifp = NULL;
2778 }
2779 
2780 static int
2781 cxgbe_detach(device_t dev)
2782 {
2783 	struct port_info *pi = device_get_softc(dev);
2784 	struct adapter *sc = pi->adapter;
2785 	int rc;
2786 
2787 	/* Detach the extra VIs first. */
2788 	rc = bus_generic_detach(dev);
2789 	if (rc)
2790 		return (rc);
2791 	device_delete_children(dev);
2792 
2793 	sysctl_ctx_free(&pi->ctx);
2794 	begin_vi_detach(sc, &pi->vi[0]);
2795 	if (pi->flags & HAS_TRACEQ) {
2796 		sc->traceq = -1;	/* cloner should not create ifnet */
2797 		t4_tracer_port_detach(sc);
2798 	}
2799 	cxgbe_vi_detach(&pi->vi[0]);
2800 	ifmedia_removeall(&pi->media);
2801 	end_vi_detach(sc, &pi->vi[0]);
2802 
2803 	return (0);
2804 }
2805 
2806 static void
2807 cxgbe_init(void *arg)
2808 {
2809 	struct vi_info *vi = arg;
2810 	struct adapter *sc = vi->adapter;
2811 
2812 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2813 		return;
2814 	cxgbe_init_synchronized(vi);
2815 	end_synchronized_op(sc, 0);
2816 }
2817 
2818 static int
2819 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2820 {
2821 	int rc = 0, mtu, flags;
2822 	struct vi_info *vi = if_getsoftc(ifp);
2823 	struct port_info *pi = vi->pi;
2824 	struct adapter *sc = pi->adapter;
2825 	struct ifreq *ifr = (struct ifreq *)data;
2826 	uint32_t mask;
2827 
2828 	switch (cmd) {
2829 	case SIOCSIFMTU:
2830 		mtu = ifr->ifr_mtu;
2831 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2832 			return (EINVAL);
2833 
2834 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2835 		if (rc)
2836 			return (rc);
2837 		if_setmtu(ifp, mtu);
2838 		if (vi->flags & VI_INIT_DONE) {
2839 			t4_update_fl_bufsize(ifp);
2840 			if (!hw_off_limits(sc) &&
2841 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2842 				rc = update_mac_settings(ifp, XGMAC_MTU);
2843 		}
2844 		end_synchronized_op(sc, 0);
2845 		break;
2846 
2847 	case SIOCSIFFLAGS:
2848 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2849 		if (rc)
2850 			return (rc);
2851 
2852 		if (hw_off_limits(sc)) {
2853 			rc = ENXIO;
2854 			goto fail;
2855 		}
2856 
2857 		if (if_getflags(ifp) & IFF_UP) {
2858 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2859 				flags = vi->if_flags;
2860 				if ((if_getflags(ifp) ^ flags) &
2861 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2862 					rc = update_mac_settings(ifp,
2863 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2864 				}
2865 			} else {
2866 				rc = cxgbe_init_synchronized(vi);
2867 			}
2868 			vi->if_flags = if_getflags(ifp);
2869 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2870 			rc = cxgbe_uninit_synchronized(vi);
2871 		}
2872 		end_synchronized_op(sc, 0);
2873 		break;
2874 
2875 	case SIOCADDMULTI:
2876 	case SIOCDELMULTI:
2877 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2878 		if (rc)
2879 			return (rc);
2880 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2881 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2882 		end_synchronized_op(sc, 0);
2883 		break;
2884 
2885 	case SIOCSIFCAP:
2886 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2887 		if (rc)
2888 			return (rc);
2889 
2890 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2891 		if (mask & IFCAP_TXCSUM) {
2892 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2893 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2894 
2895 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2896 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2897 				mask &= ~IFCAP_TSO4;
2898 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2899 				if_printf(ifp,
2900 				    "tso4 disabled due to -txcsum.\n");
2901 			}
2902 		}
2903 		if (mask & IFCAP_TXCSUM_IPV6) {
2904 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2905 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2906 
2907 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2908 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2909 				mask &= ~IFCAP_TSO6;
2910 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2911 				if_printf(ifp,
2912 				    "tso6 disabled due to -txcsum6.\n");
2913 			}
2914 		}
2915 		if (mask & IFCAP_RXCSUM)
2916 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2917 		if (mask & IFCAP_RXCSUM_IPV6)
2918 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2919 
2920 		/*
2921 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2922 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2923 		 * sending a TSO request our way, so it's sufficient to toggle
2924 		 * IFCAP_TSOx only.
2925 		 */
2926 		if (mask & IFCAP_TSO4) {
2927 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2928 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2929 				if_printf(ifp, "enable txcsum first.\n");
2930 				rc = EAGAIN;
2931 				goto fail;
2932 			}
2933 			if_togglecapenable(ifp, IFCAP_TSO4);
2934 		}
2935 		if (mask & IFCAP_TSO6) {
2936 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2937 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2938 				if_printf(ifp, "enable txcsum6 first.\n");
2939 				rc = EAGAIN;
2940 				goto fail;
2941 			}
2942 			if_togglecapenable(ifp, IFCAP_TSO6);
2943 		}
2944 		if (mask & IFCAP_LRO) {
2945 #if defined(INET) || defined(INET6)
2946 			int i;
2947 			struct sge_rxq *rxq;
2948 
2949 			if_togglecapenable(ifp, IFCAP_LRO);
2950 			for_each_rxq(vi, i, rxq) {
2951 				if (if_getcapenable(ifp) & IFCAP_LRO)
2952 					rxq->iq.flags |= IQ_LRO_ENABLED;
2953 				else
2954 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2955 			}
2956 #endif
2957 		}
2958 #ifdef TCP_OFFLOAD
2959 		if (mask & IFCAP_TOE) {
2960 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2961 
2962 			rc = toe_capability(vi, enable);
2963 			if (rc != 0)
2964 				goto fail;
2965 
2966 			if_togglecapenable(ifp, mask);
2967 		}
2968 #endif
2969 		if (mask & IFCAP_VLAN_HWTAGGING) {
2970 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2971 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2972 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2973 		}
2974 		if (mask & IFCAP_VLAN_MTU) {
2975 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2976 
2977 			/* Need to find out how to disable auto-mtu-inflation */
2978 		}
2979 		if (mask & IFCAP_VLAN_HWTSO)
2980 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2981 		if (mask & IFCAP_VLAN_HWCSUM)
2982 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2983 #ifdef RATELIMIT
2984 		if (mask & IFCAP_TXRTLMT)
2985 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2986 #endif
2987 		if (mask & IFCAP_HWRXTSTMP) {
2988 			int i;
2989 			struct sge_rxq *rxq;
2990 
2991 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2992 			for_each_rxq(vi, i, rxq) {
2993 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2994 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2995 				else
2996 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2997 			}
2998 		}
2999 		if (mask & IFCAP_MEXTPG)
3000 			if_togglecapenable(ifp, IFCAP_MEXTPG);
3001 
3002 #ifdef KERN_TLS
3003 		if (mask & IFCAP_TXTLS) {
3004 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
3005 
3006 			rc = ktls_capability(sc, enable);
3007 			if (rc != 0)
3008 				goto fail;
3009 
3010 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3011 		}
3012 #endif
3013 		if (mask & IFCAP_VXLAN_HWCSUM) {
3014 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3015 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3016 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3017 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3018 		}
3019 		if (mask & IFCAP_VXLAN_HWTSO) {
3020 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3021 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3022 			    CSUM_INNER_IP_TSO);
3023 		}
3024 
3025 #ifdef VLAN_CAPABILITIES
3026 		VLAN_CAPABILITIES(ifp);
3027 #endif
3028 fail:
3029 		end_synchronized_op(sc, 0);
3030 		break;
3031 
3032 	case SIOCSIFMEDIA:
3033 	case SIOCGIFMEDIA:
3034 	case SIOCGIFXMEDIA:
3035 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3036 		break;
3037 
3038 	case SIOCGI2C: {
3039 		struct ifi2creq i2c;
3040 
3041 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3042 		if (rc != 0)
3043 			break;
3044 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3045 			rc = EPERM;
3046 			break;
3047 		}
3048 		if (i2c.len > sizeof(i2c.data)) {
3049 			rc = EINVAL;
3050 			break;
3051 		}
3052 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3053 		if (rc)
3054 			return (rc);
3055 		if (hw_off_limits(sc))
3056 			rc = ENXIO;
3057 		else
3058 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3059 			    i2c.offset, i2c.len, &i2c.data[0]);
3060 		end_synchronized_op(sc, 0);
3061 		if (rc == 0)
3062 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3063 		break;
3064 	}
3065 
3066 	default:
3067 		rc = ether_ioctl(ifp, cmd, data);
3068 	}
3069 
3070 	return (rc);
3071 }
3072 
3073 static int
3074 cxgbe_transmit(if_t ifp, struct mbuf *m)
3075 {
3076 	struct vi_info *vi = if_getsoftc(ifp);
3077 	struct port_info *pi = vi->pi;
3078 	struct adapter *sc;
3079 	struct sge_txq *txq;
3080 	void *items[1];
3081 	int rc;
3082 
3083 	M_ASSERTPKTHDR(m);
3084 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3085 #if defined(KERN_TLS) || defined(RATELIMIT)
3086 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3087 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3088 #endif
3089 
3090 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3091 		m_freem(m);
3092 		return (ENETDOWN);
3093 	}
3094 
3095 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3096 	if (__predict_false(rc != 0)) {
3097 		if (__predict_true(rc == EINPROGRESS)) {
3098 			/* queued by parse_pkt */
3099 			MPASS(m != NULL);
3100 			return (0);
3101 		}
3102 
3103 		MPASS(m == NULL);			/* was freed already */
3104 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3105 		return (rc);
3106 	}
3107 
3108 	/* Select a txq. */
3109 	sc = vi->adapter;
3110 	txq = &sc->sge.txq[vi->first_txq];
3111 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3112 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3113 		    vi->rsrv_noflowq);
3114 
3115 	items[0] = m;
3116 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3117 	if (__predict_false(rc != 0))
3118 		m_freem(m);
3119 
3120 	return (rc);
3121 }
3122 
3123 static void
3124 cxgbe_qflush(if_t ifp)
3125 {
3126 	struct vi_info *vi = if_getsoftc(ifp);
3127 	struct sge_txq *txq;
3128 	int i;
3129 
3130 	/* queues do not exist if !VI_INIT_DONE. */
3131 	if (vi->flags & VI_INIT_DONE) {
3132 		for_each_txq(vi, i, txq) {
3133 			TXQ_LOCK(txq);
3134 			txq->eq.flags |= EQ_QFLUSH;
3135 			TXQ_UNLOCK(txq);
3136 			while (!mp_ring_is_idle(txq->r)) {
3137 				mp_ring_check_drainage(txq->r, 4096);
3138 				pause("qflush", 1);
3139 			}
3140 			TXQ_LOCK(txq);
3141 			txq->eq.flags &= ~EQ_QFLUSH;
3142 			TXQ_UNLOCK(txq);
3143 		}
3144 	}
3145 	if_qflush(ifp);
3146 }
3147 
3148 static uint64_t
3149 vi_get_counter(if_t ifp, ift_counter c)
3150 {
3151 	struct vi_info *vi = if_getsoftc(ifp);
3152 	struct fw_vi_stats_vf *s = &vi->stats;
3153 
3154 	mtx_lock(&vi->tick_mtx);
3155 	vi_refresh_stats(vi);
3156 	mtx_unlock(&vi->tick_mtx);
3157 
3158 	switch (c) {
3159 	case IFCOUNTER_IPACKETS:
3160 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3161 		    s->rx_ucast_frames);
3162 	case IFCOUNTER_IERRORS:
3163 		return (s->rx_err_frames);
3164 	case IFCOUNTER_OPACKETS:
3165 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3166 		    s->tx_ucast_frames + s->tx_offload_frames);
3167 	case IFCOUNTER_OERRORS:
3168 		return (s->tx_drop_frames);
3169 	case IFCOUNTER_IBYTES:
3170 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3171 		    s->rx_ucast_bytes);
3172 	case IFCOUNTER_OBYTES:
3173 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3174 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3175 	case IFCOUNTER_IMCASTS:
3176 		return (s->rx_mcast_frames);
3177 	case IFCOUNTER_OMCASTS:
3178 		return (s->tx_mcast_frames);
3179 	case IFCOUNTER_OQDROPS: {
3180 		uint64_t drops;
3181 
3182 		drops = 0;
3183 		if (vi->flags & VI_INIT_DONE) {
3184 			int i;
3185 			struct sge_txq *txq;
3186 
3187 			for_each_txq(vi, i, txq)
3188 				drops += counter_u64_fetch(txq->r->dropped);
3189 		}
3190 
3191 		return (drops);
3192 
3193 	}
3194 
3195 	default:
3196 		return (if_get_counter_default(ifp, c));
3197 	}
3198 }
3199 
3200 static uint64_t
3201 cxgbe_get_counter(if_t ifp, ift_counter c)
3202 {
3203 	struct vi_info *vi = if_getsoftc(ifp);
3204 	struct port_info *pi = vi->pi;
3205 	struct port_stats *s = &pi->stats;
3206 
3207 	mtx_lock(&vi->tick_mtx);
3208 	cxgbe_refresh_stats(vi);
3209 	mtx_unlock(&vi->tick_mtx);
3210 
3211 	switch (c) {
3212 	case IFCOUNTER_IPACKETS:
3213 		return (s->rx_frames);
3214 
3215 	case IFCOUNTER_IERRORS:
3216 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3217 		    s->rx_fcs_err + s->rx_len_err);
3218 
3219 	case IFCOUNTER_OPACKETS:
3220 		return (s->tx_frames);
3221 
3222 	case IFCOUNTER_OERRORS:
3223 		return (s->tx_error_frames);
3224 
3225 	case IFCOUNTER_IBYTES:
3226 		return (s->rx_octets);
3227 
3228 	case IFCOUNTER_OBYTES:
3229 		return (s->tx_octets);
3230 
3231 	case IFCOUNTER_IMCASTS:
3232 		return (s->rx_mcast_frames);
3233 
3234 	case IFCOUNTER_OMCASTS:
3235 		return (s->tx_mcast_frames);
3236 
3237 	case IFCOUNTER_IQDROPS:
3238 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3239 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3240 		    s->rx_trunc3 + pi->tnl_cong_drops);
3241 
3242 	case IFCOUNTER_OQDROPS: {
3243 		uint64_t drops;
3244 
3245 		drops = s->tx_drop;
3246 		if (vi->flags & VI_INIT_DONE) {
3247 			int i;
3248 			struct sge_txq *txq;
3249 
3250 			for_each_txq(vi, i, txq)
3251 				drops += counter_u64_fetch(txq->r->dropped);
3252 		}
3253 
3254 		return (drops);
3255 
3256 	}
3257 
3258 	default:
3259 		return (if_get_counter_default(ifp, c));
3260 	}
3261 }
3262 
3263 #if defined(KERN_TLS) || defined(RATELIMIT)
3264 static int
3265 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3266     struct m_snd_tag **pt)
3267 {
3268 	int error;
3269 
3270 	switch (params->hdr.type) {
3271 #ifdef RATELIMIT
3272 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3273 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3274 		break;
3275 #endif
3276 #ifdef KERN_TLS
3277 	case IF_SND_TAG_TYPE_TLS:
3278 	{
3279 		struct vi_info *vi = if_getsoftc(ifp);
3280 
3281 		if (is_t6(vi->pi->adapter))
3282 			error = t6_tls_tag_alloc(ifp, params, pt);
3283 		else
3284 			error = EOPNOTSUPP;
3285 		break;
3286 	}
3287 #endif
3288 	default:
3289 		error = EOPNOTSUPP;
3290 	}
3291 	return (error);
3292 }
3293 #endif
3294 
3295 /*
3296  * The kernel picks a media from the list we had provided but we still validate
3297  * the requeste.
3298  */
3299 int
3300 cxgbe_media_change(if_t ifp)
3301 {
3302 	struct vi_info *vi = if_getsoftc(ifp);
3303 	struct port_info *pi = vi->pi;
3304 	struct ifmedia *ifm = &pi->media;
3305 	struct link_config *lc = &pi->link_cfg;
3306 	struct adapter *sc = pi->adapter;
3307 	int rc;
3308 
3309 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3310 	if (rc != 0)
3311 		return (rc);
3312 	PORT_LOCK(pi);
3313 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3314 		/* ifconfig .. media autoselect */
3315 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3316 			rc = ENOTSUP; /* AN not supported by transceiver */
3317 			goto done;
3318 		}
3319 		lc->requested_aneg = AUTONEG_ENABLE;
3320 		lc->requested_speed = 0;
3321 		lc->requested_fc |= PAUSE_AUTONEG;
3322 	} else {
3323 		lc->requested_aneg = AUTONEG_DISABLE;
3324 		lc->requested_speed =
3325 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3326 		lc->requested_fc = 0;
3327 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3328 			lc->requested_fc |= PAUSE_RX;
3329 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3330 			lc->requested_fc |= PAUSE_TX;
3331 	}
3332 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3333 		fixup_link_config(pi);
3334 		rc = apply_link_config(pi);
3335 	}
3336 done:
3337 	PORT_UNLOCK(pi);
3338 	end_synchronized_op(sc, 0);
3339 	return (rc);
3340 }
3341 
3342 /*
3343  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3344  * given speed.
3345  */
3346 static int
3347 port_mword(struct port_info *pi, uint32_t speed)
3348 {
3349 
3350 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3351 	MPASS(powerof2(speed));
3352 
3353 	switch(pi->port_type) {
3354 	case FW_PORT_TYPE_BT_SGMII:
3355 	case FW_PORT_TYPE_BT_XFI:
3356 	case FW_PORT_TYPE_BT_XAUI:
3357 		/* BaseT */
3358 		switch (speed) {
3359 		case FW_PORT_CAP32_SPEED_100M:
3360 			return (IFM_100_T);
3361 		case FW_PORT_CAP32_SPEED_1G:
3362 			return (IFM_1000_T);
3363 		case FW_PORT_CAP32_SPEED_10G:
3364 			return (IFM_10G_T);
3365 		}
3366 		break;
3367 	case FW_PORT_TYPE_KX4:
3368 		if (speed == FW_PORT_CAP32_SPEED_10G)
3369 			return (IFM_10G_KX4);
3370 		break;
3371 	case FW_PORT_TYPE_CX4:
3372 		if (speed == FW_PORT_CAP32_SPEED_10G)
3373 			return (IFM_10G_CX4);
3374 		break;
3375 	case FW_PORT_TYPE_KX:
3376 		if (speed == FW_PORT_CAP32_SPEED_1G)
3377 			return (IFM_1000_KX);
3378 		break;
3379 	case FW_PORT_TYPE_KR:
3380 	case FW_PORT_TYPE_BP_AP:
3381 	case FW_PORT_TYPE_BP4_AP:
3382 	case FW_PORT_TYPE_BP40_BA:
3383 	case FW_PORT_TYPE_KR4_100G:
3384 	case FW_PORT_TYPE_KR_SFP28:
3385 	case FW_PORT_TYPE_KR_XLAUI:
3386 		switch (speed) {
3387 		case FW_PORT_CAP32_SPEED_1G:
3388 			return (IFM_1000_KX);
3389 		case FW_PORT_CAP32_SPEED_10G:
3390 			return (IFM_10G_KR);
3391 		case FW_PORT_CAP32_SPEED_25G:
3392 			return (IFM_25G_KR);
3393 		case FW_PORT_CAP32_SPEED_40G:
3394 			return (IFM_40G_KR4);
3395 		case FW_PORT_CAP32_SPEED_50G:
3396 			return (IFM_50G_KR2);
3397 		case FW_PORT_CAP32_SPEED_100G:
3398 			return (IFM_100G_KR4);
3399 		}
3400 		break;
3401 	case FW_PORT_TYPE_FIBER_XFI:
3402 	case FW_PORT_TYPE_FIBER_XAUI:
3403 	case FW_PORT_TYPE_SFP:
3404 	case FW_PORT_TYPE_QSFP_10G:
3405 	case FW_PORT_TYPE_QSA:
3406 	case FW_PORT_TYPE_QSFP:
3407 	case FW_PORT_TYPE_CR4_QSFP:
3408 	case FW_PORT_TYPE_CR_QSFP:
3409 	case FW_PORT_TYPE_CR2_QSFP:
3410 	case FW_PORT_TYPE_SFP28:
3411 		/* Pluggable transceiver */
3412 		switch (pi->mod_type) {
3413 		case FW_PORT_MOD_TYPE_LR:
3414 			switch (speed) {
3415 			case FW_PORT_CAP32_SPEED_1G:
3416 				return (IFM_1000_LX);
3417 			case FW_PORT_CAP32_SPEED_10G:
3418 				return (IFM_10G_LR);
3419 			case FW_PORT_CAP32_SPEED_25G:
3420 				return (IFM_25G_LR);
3421 			case FW_PORT_CAP32_SPEED_40G:
3422 				return (IFM_40G_LR4);
3423 			case FW_PORT_CAP32_SPEED_50G:
3424 				return (IFM_50G_LR2);
3425 			case FW_PORT_CAP32_SPEED_100G:
3426 				return (IFM_100G_LR4);
3427 			}
3428 			break;
3429 		case FW_PORT_MOD_TYPE_SR:
3430 			switch (speed) {
3431 			case FW_PORT_CAP32_SPEED_1G:
3432 				return (IFM_1000_SX);
3433 			case FW_PORT_CAP32_SPEED_10G:
3434 				return (IFM_10G_SR);
3435 			case FW_PORT_CAP32_SPEED_25G:
3436 				return (IFM_25G_SR);
3437 			case FW_PORT_CAP32_SPEED_40G:
3438 				return (IFM_40G_SR4);
3439 			case FW_PORT_CAP32_SPEED_50G:
3440 				return (IFM_50G_SR2);
3441 			case FW_PORT_CAP32_SPEED_100G:
3442 				return (IFM_100G_SR4);
3443 			}
3444 			break;
3445 		case FW_PORT_MOD_TYPE_ER:
3446 			if (speed == FW_PORT_CAP32_SPEED_10G)
3447 				return (IFM_10G_ER);
3448 			break;
3449 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3450 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3451 			switch (speed) {
3452 			case FW_PORT_CAP32_SPEED_1G:
3453 				return (IFM_1000_CX);
3454 			case FW_PORT_CAP32_SPEED_10G:
3455 				return (IFM_10G_TWINAX);
3456 			case FW_PORT_CAP32_SPEED_25G:
3457 				return (IFM_25G_CR);
3458 			case FW_PORT_CAP32_SPEED_40G:
3459 				return (IFM_40G_CR4);
3460 			case FW_PORT_CAP32_SPEED_50G:
3461 				return (IFM_50G_CR2);
3462 			case FW_PORT_CAP32_SPEED_100G:
3463 				return (IFM_100G_CR4);
3464 			}
3465 			break;
3466 		case FW_PORT_MOD_TYPE_LRM:
3467 			if (speed == FW_PORT_CAP32_SPEED_10G)
3468 				return (IFM_10G_LRM);
3469 			break;
3470 		case FW_PORT_MOD_TYPE_NA:
3471 			MPASS(0);	/* Not pluggable? */
3472 			/* fall throough */
3473 		case FW_PORT_MOD_TYPE_ERROR:
3474 		case FW_PORT_MOD_TYPE_UNKNOWN:
3475 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3476 			break;
3477 		case FW_PORT_MOD_TYPE_NONE:
3478 			return (IFM_NONE);
3479 		}
3480 		break;
3481 	case FW_PORT_TYPE_NONE:
3482 		return (IFM_NONE);
3483 	}
3484 
3485 	return (IFM_UNKNOWN);
3486 }
3487 
3488 void
3489 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3490 {
3491 	struct vi_info *vi = if_getsoftc(ifp);
3492 	struct port_info *pi = vi->pi;
3493 	struct adapter *sc = pi->adapter;
3494 	struct link_config *lc = &pi->link_cfg;
3495 
3496 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3497 		return;
3498 	PORT_LOCK(pi);
3499 
3500 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3501 		/*
3502 		 * If all the interfaces are administratively down the firmware
3503 		 * does not report transceiver changes.  Refresh port info here
3504 		 * so that ifconfig displays accurate ifmedia at all times.
3505 		 * This is the only reason we have a synchronized op in this
3506 		 * function.  Just PORT_LOCK would have been enough otherwise.
3507 		 */
3508 		t4_update_port_info(pi);
3509 		build_medialist(pi);
3510 	}
3511 
3512 	/* ifm_status */
3513 	ifmr->ifm_status = IFM_AVALID;
3514 	if (lc->link_ok == false)
3515 		goto done;
3516 	ifmr->ifm_status |= IFM_ACTIVE;
3517 
3518 	/* ifm_active */
3519 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3520 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3521 	if (lc->fc & PAUSE_RX)
3522 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3523 	if (lc->fc & PAUSE_TX)
3524 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3525 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3526 done:
3527 	PORT_UNLOCK(pi);
3528 	end_synchronized_op(sc, 0);
3529 }
3530 
3531 static int
3532 vcxgbe_probe(device_t dev)
3533 {
3534 	struct vi_info *vi = device_get_softc(dev);
3535 
3536 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3537 	    vi - vi->pi->vi);
3538 
3539 	return (BUS_PROBE_DEFAULT);
3540 }
3541 
3542 static int
3543 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3544 {
3545 	int func, index, rc;
3546 	uint32_t param, val;
3547 
3548 	ASSERT_SYNCHRONIZED_OP(sc);
3549 
3550 	index = vi - pi->vi;
3551 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3552 	KASSERT(index < nitems(vi_mac_funcs),
3553 	    ("%s: VI %s doesn't have a MAC func", __func__,
3554 	    device_get_nameunit(vi->dev)));
3555 	func = vi_mac_funcs[index];
3556 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3557 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3558 	if (rc < 0) {
3559 		CH_ERR(vi, "failed to allocate virtual interface %d"
3560 		    "for port %d: %d\n", index, pi->port_id, -rc);
3561 		return (-rc);
3562 	}
3563 	vi->viid = rc;
3564 
3565 	if (vi->rss_size == 1) {
3566 		/*
3567 		 * This VI didn't get a slice of the RSS table.  Reduce the
3568 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3569 		 * configuration file (nvi, rssnvi for this PF) if this is a
3570 		 * problem.
3571 		 */
3572 		device_printf(vi->dev, "RSS table not available.\n");
3573 		vi->rss_base = 0xffff;
3574 
3575 		return (0);
3576 	}
3577 
3578 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3579 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3580 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3581 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3582 	if (rc)
3583 		vi->rss_base = 0xffff;
3584 	else {
3585 		MPASS((val >> 16) == vi->rss_size);
3586 		vi->rss_base = val & 0xffff;
3587 	}
3588 
3589 	return (0);
3590 }
3591 
3592 static int
3593 vcxgbe_attach(device_t dev)
3594 {
3595 	struct vi_info *vi;
3596 	struct port_info *pi;
3597 	struct adapter *sc;
3598 	int rc;
3599 
3600 	vi = device_get_softc(dev);
3601 	pi = vi->pi;
3602 	sc = pi->adapter;
3603 
3604 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3605 	if (rc)
3606 		return (rc);
3607 	rc = alloc_extra_vi(sc, pi, vi);
3608 	end_synchronized_op(sc, 0);
3609 	if (rc)
3610 		return (rc);
3611 
3612 	cxgbe_vi_attach(dev, vi);
3613 
3614 	return (0);
3615 }
3616 
3617 static int
3618 vcxgbe_detach(device_t dev)
3619 {
3620 	struct vi_info *vi;
3621 	struct adapter *sc;
3622 
3623 	vi = device_get_softc(dev);
3624 	sc = vi->adapter;
3625 
3626 	begin_vi_detach(sc, vi);
3627 	cxgbe_vi_detach(vi);
3628 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3629 	end_vi_detach(sc, vi);
3630 
3631 	return (0);
3632 }
3633 
3634 static struct callout fatal_callout;
3635 static struct taskqueue *reset_tq;
3636 
3637 static void
3638 delayed_panic(void *arg)
3639 {
3640 	struct adapter *sc = arg;
3641 
3642 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3643 }
3644 
3645 static void
3646 fatal_error_task(void *arg, int pending)
3647 {
3648 	struct adapter *sc = arg;
3649 	int rc;
3650 
3651 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3652 		dump_cim_regs(sc);
3653 		dump_cimla(sc);
3654 		dump_devlog(sc);
3655 	}
3656 
3657 	if (t4_reset_on_fatal_err) {
3658 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3659 		rc = reset_adapter(sc);
3660 		if (rc == 0 && t4_panic_on_fatal_err) {
3661 			CH_ALERT(sc, "reset was successful, "
3662 			    "system will NOT panic.\n");
3663 			return;
3664 		}
3665 	}
3666 
3667 	if (t4_panic_on_fatal_err) {
3668 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3669 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3670 	}
3671 }
3672 
3673 void
3674 t4_fatal_err(struct adapter *sc, bool fw_error)
3675 {
3676 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3677 
3678 	stop_adapter(sc);
3679 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3680 		return;
3681 	if (fw_error) {
3682 		/*
3683 		 * We are here because of a firmware error/timeout and not
3684 		 * because of a hardware interrupt.  It is possible (although
3685 		 * not very likely) that an error interrupt was also raised but
3686 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3687 		 * main INT_CAUSE registers here to make sure we haven't missed
3688 		 * anything interesting.
3689 		 */
3690 		t4_slow_intr_handler(sc, verbose);
3691 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3692 	}
3693 	t4_report_fw_error(sc);
3694 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3695 	    device_get_nameunit(sc->dev), fw_error);
3696 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3697 }
3698 
3699 void
3700 t4_add_adapter(struct adapter *sc)
3701 {
3702 	sx_xlock(&t4_list_lock);
3703 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3704 	sx_xunlock(&t4_list_lock);
3705 }
3706 
3707 int
3708 t4_map_bars_0_and_4(struct adapter *sc)
3709 {
3710 	sc->regs_rid = PCIR_BAR(0);
3711 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3712 	    &sc->regs_rid, RF_ACTIVE);
3713 	if (sc->regs_res == NULL) {
3714 		device_printf(sc->dev, "cannot map registers.\n");
3715 		return (ENXIO);
3716 	}
3717 	sc->bt = rman_get_bustag(sc->regs_res);
3718 	sc->bh = rman_get_bushandle(sc->regs_res);
3719 	sc->mmio_len = rman_get_size(sc->regs_res);
3720 	setbit(&sc->doorbells, DOORBELL_KDB);
3721 
3722 	sc->msix_rid = PCIR_BAR(4);
3723 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3724 	    &sc->msix_rid, RF_ACTIVE);
3725 	if (sc->msix_res == NULL) {
3726 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3727 		return (ENXIO);
3728 	}
3729 
3730 	return (0);
3731 }
3732 
3733 int
3734 t4_map_bar_2(struct adapter *sc)
3735 {
3736 
3737 	/*
3738 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3739 	 * to map it if RDMA is disabled.
3740 	 */
3741 	if (is_t4(sc) && sc->rdmacaps == 0)
3742 		return (0);
3743 
3744 	sc->udbs_rid = PCIR_BAR(2);
3745 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3746 	    &sc->udbs_rid, RF_ACTIVE);
3747 	if (sc->udbs_res == NULL) {
3748 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3749 		return (ENXIO);
3750 	}
3751 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3752 
3753 	if (chip_id(sc) >= CHELSIO_T5) {
3754 		setbit(&sc->doorbells, DOORBELL_UDB);
3755 #if defined(__i386__) || defined(__amd64__)
3756 		if (t5_write_combine) {
3757 			int rc, mode;
3758 
3759 			/*
3760 			 * Enable write combining on BAR2.  This is the
3761 			 * userspace doorbell BAR and is split into 128B
3762 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3763 			 * with an egress queue.  The first 64B has the doorbell
3764 			 * and the second 64B can be used to submit a tx work
3765 			 * request with an implicit doorbell.
3766 			 */
3767 
3768 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3769 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3770 			if (rc == 0) {
3771 				clrbit(&sc->doorbells, DOORBELL_UDB);
3772 				setbit(&sc->doorbells, DOORBELL_WCWR);
3773 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3774 			} else {
3775 				device_printf(sc->dev,
3776 				    "couldn't enable write combining: %d\n",
3777 				    rc);
3778 			}
3779 
3780 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3781 			t4_write_reg(sc, A_SGE_STAT_CFG,
3782 			    V_STATSOURCE_T5(7) | mode);
3783 		}
3784 #endif
3785 	}
3786 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3787 
3788 	return (0);
3789 }
3790 
3791 int
3792 t4_adj_doorbells(struct adapter *sc)
3793 {
3794 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3795 		sc->doorbells &= t4_doorbells_allowed;
3796 		return (0);
3797 	}
3798 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3799 	       sc->doorbells, t4_doorbells_allowed);
3800 	return (EINVAL);
3801 }
3802 
3803 struct memwin_init {
3804 	uint32_t base;
3805 	uint32_t aperture;
3806 };
3807 
3808 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3809 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3810 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3811 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3812 };
3813 
3814 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3815 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3816 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3817 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3818 };
3819 
3820 static void
3821 setup_memwin(struct adapter *sc)
3822 {
3823 	const struct memwin_init *mw_init;
3824 	struct memwin *mw;
3825 	int i;
3826 	uint32_t bar0;
3827 
3828 	if (is_t4(sc)) {
3829 		/*
3830 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3831 		 * mechanism.  Works from within PCI passthrough environments
3832 		 * too, where rman_get_start() can return a different value.  We
3833 		 * need to program the T4 memory window decoders with the actual
3834 		 * addresses that will be coming across the PCIe link.
3835 		 */
3836 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3837 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3838 
3839 		mw_init = &t4_memwin[0];
3840 	} else {
3841 		/* T5+ use the relative offset inside the PCIe BAR */
3842 		bar0 = 0;
3843 
3844 		mw_init = &t5_memwin[0];
3845 	}
3846 
3847 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3848 		if (!rw_initialized(&mw->mw_lock)) {
3849 			rw_init(&mw->mw_lock, "memory window access");
3850 			mw->mw_base = mw_init->base;
3851 			mw->mw_aperture = mw_init->aperture;
3852 			mw->mw_curpos = 0;
3853 		}
3854 		t4_write_reg(sc,
3855 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3856 		    (mw->mw_base + bar0) | V_BIR(0) |
3857 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3858 		rw_wlock(&mw->mw_lock);
3859 		position_memwin(sc, i, mw->mw_curpos);
3860 		rw_wunlock(&mw->mw_lock);
3861 	}
3862 
3863 	/* flush */
3864 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3865 }
3866 
3867 /*
3868  * Positions the memory window at the given address in the card's address space.
3869  * There are some alignment requirements and the actual position may be at an
3870  * address prior to the requested address.  mw->mw_curpos always has the actual
3871  * position of the window.
3872  */
3873 static void
3874 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3875 {
3876 	struct memwin *mw;
3877 	uint32_t pf;
3878 	uint32_t reg;
3879 
3880 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3881 	mw = &sc->memwin[idx];
3882 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3883 
3884 	if (is_t4(sc)) {
3885 		pf = 0;
3886 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3887 	} else {
3888 		pf = V_PFNUM(sc->pf);
3889 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3890 	}
3891 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3892 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3893 	t4_read_reg(sc, reg);	/* flush */
3894 }
3895 
3896 int
3897 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3898     int len, int rw)
3899 {
3900 	struct memwin *mw;
3901 	uint32_t mw_end, v;
3902 
3903 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3904 
3905 	/* Memory can only be accessed in naturally aligned 4 byte units */
3906 	if (addr & 3 || len & 3 || len <= 0)
3907 		return (EINVAL);
3908 
3909 	mw = &sc->memwin[idx];
3910 	while (len > 0) {
3911 		rw_rlock(&mw->mw_lock);
3912 		mw_end = mw->mw_curpos + mw->mw_aperture;
3913 		if (addr >= mw_end || addr < mw->mw_curpos) {
3914 			/* Will need to reposition the window */
3915 			if (!rw_try_upgrade(&mw->mw_lock)) {
3916 				rw_runlock(&mw->mw_lock);
3917 				rw_wlock(&mw->mw_lock);
3918 			}
3919 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3920 			position_memwin(sc, idx, addr);
3921 			rw_downgrade(&mw->mw_lock);
3922 			mw_end = mw->mw_curpos + mw->mw_aperture;
3923 		}
3924 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3925 		while (addr < mw_end && len > 0) {
3926 			if (rw == 0) {
3927 				v = t4_read_reg(sc, mw->mw_base + addr -
3928 				    mw->mw_curpos);
3929 				*val++ = le32toh(v);
3930 			} else {
3931 				v = *val++;
3932 				t4_write_reg(sc, mw->mw_base + addr -
3933 				    mw->mw_curpos, htole32(v));
3934 			}
3935 			addr += 4;
3936 			len -= 4;
3937 		}
3938 		rw_runlock(&mw->mw_lock);
3939 	}
3940 
3941 	return (0);
3942 }
3943 
3944 CTASSERT(M_TID_COOKIE == M_COOKIE);
3945 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3946 
3947 static void
3948 t4_init_atid_table(struct adapter *sc)
3949 {
3950 	struct tid_info *t;
3951 	int i;
3952 
3953 	t = &sc->tids;
3954 	if (t->natids == 0)
3955 		return;
3956 
3957 	MPASS(t->atid_tab == NULL);
3958 
3959 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3960 	    M_ZERO | M_WAITOK);
3961 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3962 	t->afree = t->atid_tab;
3963 	t->atids_in_use = 0;
3964 	t->atid_alloc_stopped = false;
3965 	for (i = 1; i < t->natids; i++)
3966 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3967 	t->atid_tab[t->natids - 1].next = NULL;
3968 }
3969 
3970 static void
3971 t4_free_atid_table(struct adapter *sc)
3972 {
3973 	struct tid_info *t;
3974 
3975 	t = &sc->tids;
3976 
3977 	KASSERT(t->atids_in_use == 0,
3978 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3979 
3980 	if (mtx_initialized(&t->atid_lock))
3981 		mtx_destroy(&t->atid_lock);
3982 	free(t->atid_tab, M_CXGBE);
3983 	t->atid_tab = NULL;
3984 }
3985 
3986 static void
3987 stop_atid_allocator(struct adapter *sc)
3988 {
3989 	struct tid_info *t = &sc->tids;
3990 
3991 	mtx_lock(&t->atid_lock);
3992 	t->atid_alloc_stopped = true;
3993 	mtx_unlock(&t->atid_lock);
3994 }
3995 
3996 static void
3997 restart_atid_allocator(struct adapter *sc)
3998 {
3999 	struct tid_info *t = &sc->tids;
4000 
4001 	mtx_lock(&t->atid_lock);
4002 	KASSERT(t->atids_in_use == 0,
4003 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
4004 	t->atid_alloc_stopped = false;
4005 	mtx_unlock(&t->atid_lock);
4006 }
4007 
4008 int
4009 alloc_atid(struct adapter *sc, void *ctx)
4010 {
4011 	struct tid_info *t = &sc->tids;
4012 	int atid = -1;
4013 
4014 	mtx_lock(&t->atid_lock);
4015 	if (t->afree && !t->atid_alloc_stopped) {
4016 		union aopen_entry *p = t->afree;
4017 
4018 		atid = p - t->atid_tab;
4019 		MPASS(atid <= M_TID_TID);
4020 		t->afree = p->next;
4021 		p->data = ctx;
4022 		t->atids_in_use++;
4023 	}
4024 	mtx_unlock(&t->atid_lock);
4025 	return (atid);
4026 }
4027 
4028 void *
4029 lookup_atid(struct adapter *sc, int atid)
4030 {
4031 	struct tid_info *t = &sc->tids;
4032 
4033 	return (t->atid_tab[atid].data);
4034 }
4035 
4036 void
4037 free_atid(struct adapter *sc, int atid)
4038 {
4039 	struct tid_info *t = &sc->tids;
4040 	union aopen_entry *p = &t->atid_tab[atid];
4041 
4042 	mtx_lock(&t->atid_lock);
4043 	p->next = t->afree;
4044 	t->afree = p;
4045 	t->atids_in_use--;
4046 	mtx_unlock(&t->atid_lock);
4047 }
4048 
4049 static void
4050 queue_tid_release(struct adapter *sc, int tid)
4051 {
4052 
4053 	CXGBE_UNIMPLEMENTED("deferred tid release");
4054 }
4055 
4056 void
4057 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4058 {
4059 	struct wrqe *wr;
4060 	struct cpl_tid_release *req;
4061 
4062 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4063 	if (wr == NULL) {
4064 		queue_tid_release(sc, tid);	/* defer */
4065 		return;
4066 	}
4067 	req = wrtod(wr);
4068 
4069 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4070 
4071 	t4_wrq_tx(sc, wr);
4072 }
4073 
4074 static int
4075 t4_range_cmp(const void *a, const void *b)
4076 {
4077 	return ((const struct t4_range *)a)->start -
4078 	       ((const struct t4_range *)b)->start;
4079 }
4080 
4081 /*
4082  * Verify that the memory range specified by the addr/len pair is valid within
4083  * the card's address space.
4084  */
4085 static int
4086 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4087 {
4088 	struct t4_range mem_ranges[4], *r, *next;
4089 	uint32_t em, addr_len;
4090 	int i, n, remaining;
4091 
4092 	/* Memory can only be accessed in naturally aligned 4 byte units */
4093 	if (addr & 3 || len & 3 || len == 0)
4094 		return (EINVAL);
4095 
4096 	/* Enabled memories */
4097 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4098 
4099 	r = &mem_ranges[0];
4100 	n = 0;
4101 	bzero(r, sizeof(mem_ranges));
4102 	if (em & F_EDRAM0_ENABLE) {
4103 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4104 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4105 		if (r->size > 0) {
4106 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4107 			if (addr >= r->start &&
4108 			    addr + len <= r->start + r->size)
4109 				return (0);
4110 			r++;
4111 			n++;
4112 		}
4113 	}
4114 	if (em & F_EDRAM1_ENABLE) {
4115 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4116 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4117 		if (r->size > 0) {
4118 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4119 			if (addr >= r->start &&
4120 			    addr + len <= r->start + r->size)
4121 				return (0);
4122 			r++;
4123 			n++;
4124 		}
4125 	}
4126 	if (em & F_EXT_MEM_ENABLE) {
4127 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4128 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4129 		if (r->size > 0) {
4130 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4131 			if (addr >= r->start &&
4132 			    addr + len <= r->start + r->size)
4133 				return (0);
4134 			r++;
4135 			n++;
4136 		}
4137 	}
4138 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4139 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4140 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4141 		if (r->size > 0) {
4142 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4143 			if (addr >= r->start &&
4144 			    addr + len <= r->start + r->size)
4145 				return (0);
4146 			r++;
4147 			n++;
4148 		}
4149 	}
4150 	MPASS(n <= nitems(mem_ranges));
4151 
4152 	if (n > 1) {
4153 		/* Sort and merge the ranges. */
4154 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4155 
4156 		/* Start from index 0 and examine the next n - 1 entries. */
4157 		r = &mem_ranges[0];
4158 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4159 
4160 			MPASS(r->size > 0);	/* r is a valid entry. */
4161 			next = r + 1;
4162 			MPASS(next->size > 0);	/* and so is the next one. */
4163 
4164 			while (r->start + r->size >= next->start) {
4165 				/* Merge the next one into the current entry. */
4166 				r->size = max(r->start + r->size,
4167 				    next->start + next->size) - r->start;
4168 				n--;	/* One fewer entry in total. */
4169 				if (--remaining == 0)
4170 					goto done;	/* short circuit */
4171 				next++;
4172 			}
4173 			if (next != r + 1) {
4174 				/*
4175 				 * Some entries were merged into r and next
4176 				 * points to the first valid entry that couldn't
4177 				 * be merged.
4178 				 */
4179 				MPASS(next->size > 0);	/* must be valid */
4180 				memcpy(r + 1, next, remaining * sizeof(*r));
4181 #ifdef INVARIANTS
4182 				/*
4183 				 * This so that the foo->size assertion in the
4184 				 * next iteration of the loop do the right
4185 				 * thing for entries that were pulled up and are
4186 				 * no longer valid.
4187 				 */
4188 				MPASS(n < nitems(mem_ranges));
4189 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4190 				    sizeof(struct t4_range));
4191 #endif
4192 			}
4193 		}
4194 done:
4195 		/* Done merging the ranges. */
4196 		MPASS(n > 0);
4197 		r = &mem_ranges[0];
4198 		for (i = 0; i < n; i++, r++) {
4199 			if (addr >= r->start &&
4200 			    addr + len <= r->start + r->size)
4201 				return (0);
4202 		}
4203 	}
4204 
4205 	return (EFAULT);
4206 }
4207 
4208 static int
4209 fwmtype_to_hwmtype(int mtype)
4210 {
4211 
4212 	switch (mtype) {
4213 	case FW_MEMTYPE_EDC0:
4214 		return (MEM_EDC0);
4215 	case FW_MEMTYPE_EDC1:
4216 		return (MEM_EDC1);
4217 	case FW_MEMTYPE_EXTMEM:
4218 		return (MEM_MC0);
4219 	case FW_MEMTYPE_EXTMEM1:
4220 		return (MEM_MC1);
4221 	default:
4222 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4223 	}
4224 }
4225 
4226 /*
4227  * Verify that the memory range specified by the memtype/offset/len pair is
4228  * valid and lies entirely within the memtype specified.  The global address of
4229  * the start of the range is returned in addr.
4230  */
4231 static int
4232 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4233     uint32_t *addr)
4234 {
4235 	uint32_t em, addr_len, maddr;
4236 
4237 	/* Memory can only be accessed in naturally aligned 4 byte units */
4238 	if (off & 3 || len & 3 || len == 0)
4239 		return (EINVAL);
4240 
4241 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4242 	switch (fwmtype_to_hwmtype(mtype)) {
4243 	case MEM_EDC0:
4244 		if (!(em & F_EDRAM0_ENABLE))
4245 			return (EINVAL);
4246 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4247 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4248 		break;
4249 	case MEM_EDC1:
4250 		if (!(em & F_EDRAM1_ENABLE))
4251 			return (EINVAL);
4252 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4253 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4254 		break;
4255 	case MEM_MC:
4256 		if (!(em & F_EXT_MEM_ENABLE))
4257 			return (EINVAL);
4258 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4259 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4260 		break;
4261 	case MEM_MC1:
4262 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4263 			return (EINVAL);
4264 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4265 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4266 		break;
4267 	default:
4268 		return (EINVAL);
4269 	}
4270 
4271 	*addr = maddr + off;	/* global address */
4272 	return (validate_mem_range(sc, *addr, len));
4273 }
4274 
4275 static int
4276 fixup_devlog_params(struct adapter *sc)
4277 {
4278 	struct devlog_params *dparams = &sc->params.devlog;
4279 	int rc;
4280 
4281 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4282 	    dparams->size, &dparams->addr);
4283 
4284 	return (rc);
4285 }
4286 
4287 static void
4288 update_nirq(struct intrs_and_queues *iaq, int nports)
4289 {
4290 
4291 	iaq->nirq = T4_EXTRA_INTR;
4292 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4293 	iaq->nirq += nports * iaq->nofldrxq;
4294 	iaq->nirq += nports * (iaq->num_vis - 1) *
4295 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4296 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4297 }
4298 
4299 /*
4300  * Adjust requirements to fit the number of interrupts available.
4301  */
4302 static void
4303 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4304     int navail)
4305 {
4306 	int old_nirq;
4307 	const int nports = sc->params.nports;
4308 
4309 	MPASS(nports > 0);
4310 	MPASS(navail > 0);
4311 
4312 	bzero(iaq, sizeof(*iaq));
4313 	iaq->intr_type = itype;
4314 	iaq->num_vis = t4_num_vis;
4315 	iaq->ntxq = t4_ntxq;
4316 	iaq->ntxq_vi = t4_ntxq_vi;
4317 	iaq->nrxq = t4_nrxq;
4318 	iaq->nrxq_vi = t4_nrxq_vi;
4319 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4320 	if (is_offload(sc) || is_ethoffload(sc)) {
4321 		iaq->nofldtxq = t4_nofldtxq;
4322 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4323 	}
4324 #endif
4325 #ifdef TCP_OFFLOAD
4326 	if (is_offload(sc)) {
4327 		iaq->nofldrxq = t4_nofldrxq;
4328 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4329 	}
4330 #endif
4331 #ifdef DEV_NETMAP
4332 	if (t4_native_netmap & NN_MAIN_VI) {
4333 		iaq->nnmtxq = t4_nnmtxq;
4334 		iaq->nnmrxq = t4_nnmrxq;
4335 	}
4336 	if (t4_native_netmap & NN_EXTRA_VI) {
4337 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4338 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4339 	}
4340 #endif
4341 
4342 	update_nirq(iaq, nports);
4343 	if (iaq->nirq <= navail &&
4344 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4345 		/*
4346 		 * This is the normal case -- there are enough interrupts for
4347 		 * everything.
4348 		 */
4349 		goto done;
4350 	}
4351 
4352 	/*
4353 	 * If extra VIs have been configured try reducing their count and see if
4354 	 * that works.
4355 	 */
4356 	while (iaq->num_vis > 1) {
4357 		iaq->num_vis--;
4358 		update_nirq(iaq, nports);
4359 		if (iaq->nirq <= navail &&
4360 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4361 			device_printf(sc->dev, "virtual interfaces per port "
4362 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4363 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4364 			    "itype %d, navail %u, nirq %d.\n",
4365 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4366 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4367 			    itype, navail, iaq->nirq);
4368 			goto done;
4369 		}
4370 	}
4371 
4372 	/*
4373 	 * Extra VIs will not be created.  Log a message if they were requested.
4374 	 */
4375 	MPASS(iaq->num_vis == 1);
4376 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4377 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4378 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4379 	if (iaq->num_vis != t4_num_vis) {
4380 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4381 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4382 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4383 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4384 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4385 	}
4386 
4387 	/*
4388 	 * Keep reducing the number of NIC rx queues to the next lower power of
4389 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4390 	 * if that works.
4391 	 */
4392 	do {
4393 		if (iaq->nrxq > 1) {
4394 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4395 			if (iaq->nnmrxq > iaq->nrxq)
4396 				iaq->nnmrxq = iaq->nrxq;
4397 		}
4398 		if (iaq->nofldrxq > 1)
4399 			iaq->nofldrxq >>= 1;
4400 
4401 		old_nirq = iaq->nirq;
4402 		update_nirq(iaq, nports);
4403 		if (iaq->nirq <= navail &&
4404 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4405 			device_printf(sc->dev, "running with reduced number of "
4406 			    "rx queues because of shortage of interrupts.  "
4407 			    "nrxq=%u, nofldrxq=%u.  "
4408 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4409 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4410 			goto done;
4411 		}
4412 	} while (old_nirq != iaq->nirq);
4413 
4414 	/* One interrupt for everything.  Ugh. */
4415 	device_printf(sc->dev, "running with minimal number of queues.  "
4416 	    "itype %d, navail %u.\n", itype, navail);
4417 	iaq->nirq = 1;
4418 	iaq->nrxq = 1;
4419 	iaq->ntxq = 1;
4420 	if (iaq->nofldrxq > 0) {
4421 		iaq->nofldrxq = 1;
4422 		iaq->nofldtxq = 1;
4423 	}
4424 	iaq->nnmtxq = 0;
4425 	iaq->nnmrxq = 0;
4426 done:
4427 	MPASS(iaq->num_vis > 0);
4428 	if (iaq->num_vis > 1) {
4429 		MPASS(iaq->nrxq_vi > 0);
4430 		MPASS(iaq->ntxq_vi > 0);
4431 	}
4432 	MPASS(iaq->nirq > 0);
4433 	MPASS(iaq->nrxq > 0);
4434 	MPASS(iaq->ntxq > 0);
4435 	if (itype == INTR_MSI) {
4436 		MPASS(powerof2(iaq->nirq));
4437 	}
4438 }
4439 
4440 static int
4441 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4442 {
4443 	int rc, itype, navail, nalloc;
4444 
4445 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4446 
4447 		if ((itype & t4_intr_types) == 0)
4448 			continue;	/* not allowed */
4449 
4450 		if (itype == INTR_MSIX)
4451 			navail = pci_msix_count(sc->dev);
4452 		else if (itype == INTR_MSI)
4453 			navail = pci_msi_count(sc->dev);
4454 		else
4455 			navail = 1;
4456 restart:
4457 		if (navail == 0)
4458 			continue;
4459 
4460 		calculate_iaq(sc, iaq, itype, navail);
4461 		nalloc = iaq->nirq;
4462 		rc = 0;
4463 		if (itype == INTR_MSIX)
4464 			rc = pci_alloc_msix(sc->dev, &nalloc);
4465 		else if (itype == INTR_MSI)
4466 			rc = pci_alloc_msi(sc->dev, &nalloc);
4467 
4468 		if (rc == 0 && nalloc > 0) {
4469 			if (nalloc == iaq->nirq)
4470 				return (0);
4471 
4472 			/*
4473 			 * Didn't get the number requested.  Use whatever number
4474 			 * the kernel is willing to allocate.
4475 			 */
4476 			device_printf(sc->dev, "fewer vectors than requested, "
4477 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4478 			    itype, iaq->nirq, nalloc);
4479 			pci_release_msi(sc->dev);
4480 			navail = nalloc;
4481 			goto restart;
4482 		}
4483 
4484 		device_printf(sc->dev,
4485 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4486 		    itype, rc, iaq->nirq, nalloc);
4487 	}
4488 
4489 	device_printf(sc->dev,
4490 	    "failed to find a usable interrupt type.  "
4491 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4492 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4493 
4494 	return (ENXIO);
4495 }
4496 
4497 #define FW_VERSION(chip) ( \
4498     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4499     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4500     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4501     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4502 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4503 
4504 /* Just enough of fw_hdr to cover all version info. */
4505 struct fw_h {
4506 	__u8	ver;
4507 	__u8	chip;
4508 	__be16	len512;
4509 	__be32	fw_ver;
4510 	__be32	tp_microcode_ver;
4511 	__u8	intfver_nic;
4512 	__u8	intfver_vnic;
4513 	__u8	intfver_ofld;
4514 	__u8	intfver_ri;
4515 	__u8	intfver_iscsipdu;
4516 	__u8	intfver_iscsi;
4517 	__u8	intfver_fcoepdu;
4518 	__u8	intfver_fcoe;
4519 };
4520 /* Spot check a couple of fields. */
4521 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4522 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4523 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4524 
4525 struct fw_info {
4526 	uint8_t chip;
4527 	char *kld_name;
4528 	char *fw_mod_name;
4529 	struct fw_h fw_h;
4530 } fw_info[] = {
4531 	{
4532 		.chip = CHELSIO_T4,
4533 		.kld_name = "t4fw_cfg",
4534 		.fw_mod_name = "t4fw",
4535 		.fw_h = {
4536 			.chip = FW_HDR_CHIP_T4,
4537 			.fw_ver = htobe32(FW_VERSION(T4)),
4538 			.intfver_nic = FW_INTFVER(T4, NIC),
4539 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4540 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4541 			.intfver_ri = FW_INTFVER(T4, RI),
4542 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4543 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4544 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4545 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4546 		},
4547 	}, {
4548 		.chip = CHELSIO_T5,
4549 		.kld_name = "t5fw_cfg",
4550 		.fw_mod_name = "t5fw",
4551 		.fw_h = {
4552 			.chip = FW_HDR_CHIP_T5,
4553 			.fw_ver = htobe32(FW_VERSION(T5)),
4554 			.intfver_nic = FW_INTFVER(T5, NIC),
4555 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4556 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4557 			.intfver_ri = FW_INTFVER(T5, RI),
4558 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4559 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4560 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4561 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4562 		},
4563 	}, {
4564 		.chip = CHELSIO_T6,
4565 		.kld_name = "t6fw_cfg",
4566 		.fw_mod_name = "t6fw",
4567 		.fw_h = {
4568 			.chip = FW_HDR_CHIP_T6,
4569 			.fw_ver = htobe32(FW_VERSION(T6)),
4570 			.intfver_nic = FW_INTFVER(T6, NIC),
4571 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4572 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4573 			.intfver_ri = FW_INTFVER(T6, RI),
4574 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4575 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4576 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4577 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4578 		},
4579 	}
4580 };
4581 
4582 static struct fw_info *
4583 find_fw_info(int chip)
4584 {
4585 	int i;
4586 
4587 	for (i = 0; i < nitems(fw_info); i++) {
4588 		if (fw_info[i].chip == chip)
4589 			return (&fw_info[i]);
4590 	}
4591 	return (NULL);
4592 }
4593 
4594 /*
4595  * Is the given firmware API compatible with the one the driver was compiled
4596  * with?
4597  */
4598 static int
4599 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4600 {
4601 
4602 	/* short circuit if it's the exact same firmware version */
4603 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4604 		return (1);
4605 
4606 	/*
4607 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4608 	 * features that are supported in the driver.
4609 	 */
4610 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4611 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4612 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4613 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4614 		return (1);
4615 #undef SAME_INTF
4616 
4617 	return (0);
4618 }
4619 
4620 static int
4621 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4622     const struct firmware **fw)
4623 {
4624 	struct fw_info *fw_info;
4625 
4626 	*dcfg = NULL;
4627 	if (fw != NULL)
4628 		*fw = NULL;
4629 
4630 	fw_info = find_fw_info(chip_id(sc));
4631 	if (fw_info == NULL) {
4632 		device_printf(sc->dev,
4633 		    "unable to look up firmware information for chip %d.\n",
4634 		    chip_id(sc));
4635 		return (EINVAL);
4636 	}
4637 
4638 	*dcfg = firmware_get(fw_info->kld_name);
4639 	if (*dcfg != NULL) {
4640 		if (fw != NULL)
4641 			*fw = firmware_get(fw_info->fw_mod_name);
4642 		return (0);
4643 	}
4644 
4645 	return (ENOENT);
4646 }
4647 
4648 static void
4649 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4650     const struct firmware *fw)
4651 {
4652 
4653 	if (fw != NULL)
4654 		firmware_put(fw, FIRMWARE_UNLOAD);
4655 	if (dcfg != NULL)
4656 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4657 }
4658 
4659 /*
4660  * Return values:
4661  * 0 means no firmware install attempted.
4662  * ERESTART means a firmware install was attempted and was successful.
4663  * +ve errno means a firmware install was attempted but failed.
4664  */
4665 static int
4666 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4667     const struct fw_h *drv_fw, const char *reason, int *already)
4668 {
4669 	const struct firmware *cfg, *fw;
4670 	const uint32_t c = be32toh(card_fw->fw_ver);
4671 	uint32_t d, k;
4672 	int rc, fw_install;
4673 	struct fw_h bundled_fw;
4674 	bool load_attempted;
4675 
4676 	cfg = fw = NULL;
4677 	load_attempted = false;
4678 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4679 
4680 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4681 	if (t4_fw_install < 0) {
4682 		rc = load_fw_module(sc, &cfg, &fw);
4683 		if (rc != 0 || fw == NULL) {
4684 			device_printf(sc->dev,
4685 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4686 			    " will use compiled-in firmware version for"
4687 			    "hw.cxgbe.fw_install checks.\n",
4688 			    rc, cfg, fw);
4689 		} else {
4690 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4691 		}
4692 		load_attempted = true;
4693 	}
4694 	d = be32toh(bundled_fw.fw_ver);
4695 
4696 	if (reason != NULL)
4697 		goto install;
4698 
4699 	if ((sc->flags & FW_OK) == 0) {
4700 
4701 		if (c == 0xffffffff) {
4702 			reason = "missing";
4703 			goto install;
4704 		}
4705 
4706 		rc = 0;
4707 		goto done;
4708 	}
4709 
4710 	if (!fw_compatible(card_fw, &bundled_fw)) {
4711 		reason = "incompatible or unusable";
4712 		goto install;
4713 	}
4714 
4715 	if (d > c) {
4716 		reason = "older than the version bundled with this driver";
4717 		goto install;
4718 	}
4719 
4720 	if (fw_install == 2 && d != c) {
4721 		reason = "different than the version bundled with this driver";
4722 		goto install;
4723 	}
4724 
4725 	/* No reason to do anything to the firmware already on the card. */
4726 	rc = 0;
4727 	goto done;
4728 
4729 install:
4730 	rc = 0;
4731 	if ((*already)++)
4732 		goto done;
4733 
4734 	if (fw_install == 0) {
4735 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4736 		    "but the driver is prohibited from installing a firmware "
4737 		    "on the card.\n",
4738 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4739 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4740 
4741 		goto done;
4742 	}
4743 
4744 	/*
4745 	 * We'll attempt to install a firmware.  Load the module first (if it
4746 	 * hasn't been loaded already).
4747 	 */
4748 	if (!load_attempted) {
4749 		rc = load_fw_module(sc, &cfg, &fw);
4750 		if (rc != 0 || fw == NULL) {
4751 			device_printf(sc->dev,
4752 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4753 			    rc, cfg, fw);
4754 			/* carry on */
4755 		}
4756 	}
4757 	if (fw == NULL) {
4758 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4759 		    "but the driver cannot take corrective action because it "
4760 		    "is unable to load the firmware module.\n",
4761 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4762 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4763 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4764 		goto done;
4765 	}
4766 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4767 	if (k != d) {
4768 		MPASS(t4_fw_install > 0);
4769 		device_printf(sc->dev,
4770 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4771 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4772 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4773 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4774 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4775 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4776 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4777 		goto done;
4778 	}
4779 
4780 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4781 	    "installing firmware %u.%u.%u.%u on card.\n",
4782 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4783 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4784 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4785 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4786 
4787 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4788 	if (rc != 0) {
4789 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4790 	} else {
4791 		/* Installed successfully, update the cached header too. */
4792 		rc = ERESTART;
4793 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4794 	}
4795 done:
4796 	unload_fw_module(sc, cfg, fw);
4797 
4798 	return (rc);
4799 }
4800 
4801 /*
4802  * Establish contact with the firmware and attempt to become the master driver.
4803  *
4804  * A firmware will be installed to the card if needed (if the driver is allowed
4805  * to do so).
4806  */
4807 static int
4808 contact_firmware(struct adapter *sc)
4809 {
4810 	int rc, already = 0;
4811 	enum dev_state state;
4812 	struct fw_info *fw_info;
4813 	struct fw_hdr *card_fw;		/* fw on the card */
4814 	const struct fw_h *drv_fw;
4815 
4816 	fw_info = find_fw_info(chip_id(sc));
4817 	if (fw_info == NULL) {
4818 		device_printf(sc->dev,
4819 		    "unable to look up firmware information for chip %d.\n",
4820 		    chip_id(sc));
4821 		return (EINVAL);
4822 	}
4823 	drv_fw = &fw_info->fw_h;
4824 
4825 	/* Read the header of the firmware on the card */
4826 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4827 restart:
4828 	rc = -t4_get_fw_hdr(sc, card_fw);
4829 	if (rc != 0) {
4830 		device_printf(sc->dev,
4831 		    "unable to read firmware header from card's flash: %d\n",
4832 		    rc);
4833 		goto done;
4834 	}
4835 
4836 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4837 	    &already);
4838 	if (rc == ERESTART)
4839 		goto restart;
4840 	if (rc != 0)
4841 		goto done;
4842 
4843 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4844 	if (rc < 0 || state == DEV_STATE_ERR) {
4845 		rc = -rc;
4846 		device_printf(sc->dev,
4847 		    "failed to connect to the firmware: %d, %d.  "
4848 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4849 #if 0
4850 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4851 		    "not responding properly to HELLO", &already) == ERESTART)
4852 			goto restart;
4853 #endif
4854 		goto done;
4855 	}
4856 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4857 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4858 
4859 	if (rc == sc->pf) {
4860 		sc->flags |= MASTER_PF;
4861 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4862 		    NULL, &already);
4863 		if (rc == ERESTART)
4864 			rc = 0;
4865 		else if (rc != 0)
4866 			goto done;
4867 	} else if (state == DEV_STATE_UNINIT) {
4868 		/*
4869 		 * We didn't get to be the master so we definitely won't be
4870 		 * configuring the chip.  It's a bug if someone else hasn't
4871 		 * configured it already.
4872 		 */
4873 		device_printf(sc->dev, "couldn't be master(%d), "
4874 		    "device not already initialized either(%d).  "
4875 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4876 		rc = EPROTO;
4877 		goto done;
4878 	} else {
4879 		/*
4880 		 * Some other PF is the master and has configured the chip.
4881 		 * This is allowed but untested.
4882 		 */
4883 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4884 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4885 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4886 		sc->cfcsum = 0;
4887 		rc = 0;
4888 	}
4889 done:
4890 	if (rc != 0 && sc->flags & FW_OK) {
4891 		t4_fw_bye(sc, sc->mbox);
4892 		sc->flags &= ~FW_OK;
4893 	}
4894 	free(card_fw, M_CXGBE);
4895 	return (rc);
4896 }
4897 
4898 static int
4899 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4900     uint32_t mtype, uint32_t moff)
4901 {
4902 	struct fw_info *fw_info;
4903 	const struct firmware *dcfg, *rcfg = NULL;
4904 	const uint32_t *cfdata;
4905 	uint32_t cflen, addr;
4906 	int rc;
4907 
4908 	load_fw_module(sc, &dcfg, NULL);
4909 
4910 	/* Card specific interpretation of "default". */
4911 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4912 		if (pci_get_device(sc->dev) == 0x440a)
4913 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4914 		if (is_fpga(sc))
4915 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4916 	}
4917 
4918 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4919 		if (dcfg == NULL) {
4920 			device_printf(sc->dev,
4921 			    "KLD with default config is not available.\n");
4922 			rc = ENOENT;
4923 			goto done;
4924 		}
4925 		cfdata = dcfg->data;
4926 		cflen = dcfg->datasize & ~3;
4927 	} else {
4928 		char s[32];
4929 
4930 		fw_info = find_fw_info(chip_id(sc));
4931 		if (fw_info == NULL) {
4932 			device_printf(sc->dev,
4933 			    "unable to look up firmware information for chip %d.\n",
4934 			    chip_id(sc));
4935 			rc = EINVAL;
4936 			goto done;
4937 		}
4938 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4939 
4940 		rcfg = firmware_get(s);
4941 		if (rcfg == NULL) {
4942 			device_printf(sc->dev,
4943 			    "unable to load module \"%s\" for configuration "
4944 			    "profile \"%s\".\n", s, cfg_file);
4945 			rc = ENOENT;
4946 			goto done;
4947 		}
4948 		cfdata = rcfg->data;
4949 		cflen = rcfg->datasize & ~3;
4950 	}
4951 
4952 	if (cflen > FLASH_CFG_MAX_SIZE) {
4953 		device_printf(sc->dev,
4954 		    "config file too long (%d, max allowed is %d).\n",
4955 		    cflen, FLASH_CFG_MAX_SIZE);
4956 		rc = EINVAL;
4957 		goto done;
4958 	}
4959 
4960 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4961 	if (rc != 0) {
4962 		device_printf(sc->dev,
4963 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4964 		    __func__, mtype, moff, cflen, rc);
4965 		rc = EINVAL;
4966 		goto done;
4967 	}
4968 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4969 done:
4970 	if (rcfg != NULL)
4971 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4972 	unload_fw_module(sc, dcfg, NULL);
4973 	return (rc);
4974 }
4975 
4976 struct caps_allowed {
4977 	uint16_t nbmcaps;
4978 	uint16_t linkcaps;
4979 	uint16_t switchcaps;
4980 	uint16_t niccaps;
4981 	uint16_t toecaps;
4982 	uint16_t rdmacaps;
4983 	uint16_t cryptocaps;
4984 	uint16_t iscsicaps;
4985 	uint16_t fcoecaps;
4986 };
4987 
4988 #define FW_PARAM_DEV(param) \
4989 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4990 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4991 #define FW_PARAM_PFVF(param) \
4992 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4993 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4994 
4995 /*
4996  * Provide a configuration profile to the firmware and have it initialize the
4997  * chip accordingly.  This may involve uploading a configuration file to the
4998  * card.
4999  */
5000 static int
5001 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
5002     const struct caps_allowed *caps_allowed)
5003 {
5004 	int rc;
5005 	struct fw_caps_config_cmd caps;
5006 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5007 
5008 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5009 	if (rc != 0) {
5010 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5011 		return (rc);
5012 	}
5013 
5014 	bzero(&caps, sizeof(caps));
5015 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5016 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5017 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5018 		mtype = 0;
5019 		moff = 0;
5020 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5021 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5022 		mtype = FW_MEMTYPE_FLASH;
5023 		moff = t4_flash_cfg_addr(sc);
5024 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5025 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5026 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5027 		    FW_LEN16(caps));
5028 	} else {
5029 		/*
5030 		 * Ask the firmware where it wants us to upload the config file.
5031 		 */
5032 		param = FW_PARAM_DEV(CF);
5033 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5034 		if (rc != 0) {
5035 			/* No support for config file?  Shouldn't happen. */
5036 			device_printf(sc->dev,
5037 			    "failed to query config file location: %d.\n", rc);
5038 			goto done;
5039 		}
5040 		mtype = G_FW_PARAMS_PARAM_Y(val);
5041 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5042 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5043 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5044 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5045 		    FW_LEN16(caps));
5046 
5047 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
5048 		if (rc != 0) {
5049 			device_printf(sc->dev,
5050 			    "failed to upload config file to card: %d.\n", rc);
5051 			goto done;
5052 		}
5053 	}
5054 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5055 	if (rc != 0) {
5056 		device_printf(sc->dev, "failed to pre-process config file: %d "
5057 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5058 		goto done;
5059 	}
5060 
5061 	finicsum = be32toh(caps.finicsum);
5062 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5063 	if (finicsum != cfcsum) {
5064 		device_printf(sc->dev,
5065 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5066 		    finicsum, cfcsum);
5067 	}
5068 	sc->cfcsum = cfcsum;
5069 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5070 
5071 	/*
5072 	 * Let the firmware know what features will (not) be used so it can tune
5073 	 * things accordingly.
5074 	 */
5075 #define LIMIT_CAPS(x) do { \
5076 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5077 } while (0)
5078 	LIMIT_CAPS(nbm);
5079 	LIMIT_CAPS(link);
5080 	LIMIT_CAPS(switch);
5081 	LIMIT_CAPS(nic);
5082 	LIMIT_CAPS(toe);
5083 	LIMIT_CAPS(rdma);
5084 	LIMIT_CAPS(crypto);
5085 	LIMIT_CAPS(iscsi);
5086 	LIMIT_CAPS(fcoe);
5087 #undef LIMIT_CAPS
5088 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5089 		/*
5090 		 * TOE and hashfilters are mutually exclusive.  It is a config
5091 		 * file or firmware bug if both are reported as available.  Try
5092 		 * to cope with the situation in non-debug builds by disabling
5093 		 * TOE.
5094 		 */
5095 		MPASS(caps.toecaps == 0);
5096 
5097 		caps.toecaps = 0;
5098 		caps.rdmacaps = 0;
5099 		caps.iscsicaps = 0;
5100 	}
5101 
5102 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5103 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5104 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5105 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5106 	if (rc != 0) {
5107 		device_printf(sc->dev,
5108 		    "failed to process config file: %d.\n", rc);
5109 		goto done;
5110 	}
5111 
5112 	t4_tweak_chip_settings(sc);
5113 	set_params__pre_init(sc);
5114 
5115 	/* get basic stuff going */
5116 	rc = -t4_fw_initialize(sc, sc->mbox);
5117 	if (rc != 0) {
5118 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5119 		goto done;
5120 	}
5121 done:
5122 	return (rc);
5123 }
5124 
5125 /*
5126  * Partition chip resources for use between various PFs, VFs, etc.
5127  */
5128 static int
5129 partition_resources(struct adapter *sc)
5130 {
5131 	char cfg_file[sizeof(t4_cfg_file)];
5132 	struct caps_allowed caps_allowed;
5133 	int rc;
5134 	bool fallback;
5135 
5136 	/* Only the master driver gets to configure the chip resources. */
5137 	MPASS(sc->flags & MASTER_PF);
5138 
5139 #define COPY_CAPS(x) do { \
5140 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5141 } while (0)
5142 	bzero(&caps_allowed, sizeof(caps_allowed));
5143 	COPY_CAPS(nbm);
5144 	COPY_CAPS(link);
5145 	COPY_CAPS(switch);
5146 	COPY_CAPS(nic);
5147 	COPY_CAPS(toe);
5148 	COPY_CAPS(rdma);
5149 	COPY_CAPS(crypto);
5150 	COPY_CAPS(iscsi);
5151 	COPY_CAPS(fcoe);
5152 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5153 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5154 retry:
5155 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5156 	if (rc != 0 && fallback) {
5157 		dump_devlog(sc);
5158 		device_printf(sc->dev,
5159 		    "failed (%d) to configure card with \"%s\" profile, "
5160 		    "will fall back to a basic configuration and retry.\n",
5161 		    rc, cfg_file);
5162 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5163 		bzero(&caps_allowed, sizeof(caps_allowed));
5164 		COPY_CAPS(switch);
5165 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5166 		fallback = false;
5167 		goto retry;
5168 	}
5169 #undef COPY_CAPS
5170 	return (rc);
5171 }
5172 
5173 /*
5174  * Retrieve parameters that are needed (or nice to have) very early.
5175  */
5176 static int
5177 get_params__pre_init(struct adapter *sc)
5178 {
5179 	int rc;
5180 	uint32_t param[2], val[2];
5181 
5182 	t4_get_version_info(sc);
5183 
5184 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5185 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5186 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5187 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5188 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5189 
5190 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5191 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5192 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5193 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5194 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5195 
5196 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5197 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5198 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5199 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5200 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5201 
5202 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5203 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5204 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5205 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5206 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5207 
5208 	param[0] = FW_PARAM_DEV(PORTVEC);
5209 	param[1] = FW_PARAM_DEV(CCLK);
5210 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5211 	if (rc != 0) {
5212 		device_printf(sc->dev,
5213 		    "failed to query parameters (pre_init): %d.\n", rc);
5214 		return (rc);
5215 	}
5216 
5217 	sc->params.portvec = val[0];
5218 	sc->params.nports = bitcount32(val[0]);
5219 	sc->params.vpd.cclk = val[1];
5220 
5221 	/* Read device log parameters. */
5222 	rc = -t4_init_devlog_params(sc, 1);
5223 	if (rc == 0)
5224 		fixup_devlog_params(sc);
5225 	else {
5226 		device_printf(sc->dev,
5227 		    "failed to get devlog parameters: %d.\n", rc);
5228 		rc = 0;	/* devlog isn't critical for device operation */
5229 	}
5230 
5231 	return (rc);
5232 }
5233 
5234 /*
5235  * Any params that need to be set before FW_INITIALIZE.
5236  */
5237 static int
5238 set_params__pre_init(struct adapter *sc)
5239 {
5240 	int rc = 0;
5241 	uint32_t param, val;
5242 
5243 	if (chip_id(sc) >= CHELSIO_T6) {
5244 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5245 		val = 1;
5246 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5247 		/* firmwares < 1.20.1.0 do not have this param. */
5248 		if (rc == FW_EINVAL &&
5249 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5250 			rc = 0;
5251 		}
5252 		if (rc != 0) {
5253 			device_printf(sc->dev,
5254 			    "failed to enable high priority filters :%d.\n",
5255 			    rc);
5256 		}
5257 
5258 		param = FW_PARAM_DEV(PPOD_EDRAM);
5259 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5260 		if (rc == 0 && val == 1) {
5261 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5262 			    &val);
5263 			if (rc != 0) {
5264 				device_printf(sc->dev,
5265 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5266 			}
5267 		}
5268 	}
5269 
5270 	/* Enable opaque VIIDs with firmwares that support it. */
5271 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5272 	val = 1;
5273 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5274 	if (rc == 0 && val == 1)
5275 		sc->params.viid_smt_extn_support = true;
5276 	else
5277 		sc->params.viid_smt_extn_support = false;
5278 
5279 	return (rc);
5280 }
5281 
5282 /*
5283  * Retrieve various parameters that are of interest to the driver.  The device
5284  * has been initialized by the firmware at this point.
5285  */
5286 static int
5287 get_params__post_init(struct adapter *sc)
5288 {
5289 	int rc;
5290 	uint32_t param[7], val[7];
5291 	struct fw_caps_config_cmd caps;
5292 
5293 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5294 	param[1] = FW_PARAM_PFVF(EQ_START);
5295 	param[2] = FW_PARAM_PFVF(FILTER_START);
5296 	param[3] = FW_PARAM_PFVF(FILTER_END);
5297 	param[4] = FW_PARAM_PFVF(L2T_START);
5298 	param[5] = FW_PARAM_PFVF(L2T_END);
5299 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5300 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5301 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5302 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5303 	if (rc != 0) {
5304 		device_printf(sc->dev,
5305 		    "failed to query parameters (post_init): %d.\n", rc);
5306 		return (rc);
5307 	}
5308 
5309 	sc->sge.iq_start = val[0];
5310 	sc->sge.eq_start = val[1];
5311 	if ((int)val[3] > (int)val[2]) {
5312 		sc->tids.ftid_base = val[2];
5313 		sc->tids.ftid_end = val[3];
5314 		sc->tids.nftids = val[3] - val[2] + 1;
5315 	}
5316 	sc->vres.l2t.start = val[4];
5317 	sc->vres.l2t.size = val[5] - val[4] + 1;
5318 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5319 	if (sc->vres.l2t.size > 0)
5320 		MPASS(fls(val[5]) <= S_SYNC_WR);
5321 	sc->params.core_vdd = val[6];
5322 
5323 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5324 	param[1] = FW_PARAM_PFVF(EQ_END);
5325 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5326 	if (rc != 0) {
5327 		device_printf(sc->dev,
5328 		    "failed to query parameters (post_init2): %d.\n", rc);
5329 		return (rc);
5330 	}
5331 	MPASS((int)val[0] >= sc->sge.iq_start);
5332 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5333 	MPASS((int)val[1] >= sc->sge.eq_start);
5334 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5335 
5336 	if (chip_id(sc) >= CHELSIO_T6) {
5337 
5338 		sc->tids.tid_base = t4_read_reg(sc,
5339 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5340 
5341 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5342 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5343 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5344 		if (rc != 0) {
5345 			device_printf(sc->dev,
5346 			   "failed to query hpfilter parameters: %d.\n", rc);
5347 			return (rc);
5348 		}
5349 		if ((int)val[1] > (int)val[0]) {
5350 			sc->tids.hpftid_base = val[0];
5351 			sc->tids.hpftid_end = val[1];
5352 			sc->tids.nhpftids = val[1] - val[0] + 1;
5353 
5354 			/*
5355 			 * These should go off if the layout changes and the
5356 			 * driver needs to catch up.
5357 			 */
5358 			MPASS(sc->tids.hpftid_base == 0);
5359 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5360 		}
5361 
5362 		param[0] = FW_PARAM_PFVF(RAWF_START);
5363 		param[1] = FW_PARAM_PFVF(RAWF_END);
5364 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5365 		if (rc != 0) {
5366 			device_printf(sc->dev,
5367 			   "failed to query rawf parameters: %d.\n", rc);
5368 			return (rc);
5369 		}
5370 		if ((int)val[1] > (int)val[0]) {
5371 			sc->rawf_base = val[0];
5372 			sc->nrawf = val[1] - val[0] + 1;
5373 		}
5374 	}
5375 
5376 	/*
5377 	 * The parameters that follow may not be available on all firmwares.  We
5378 	 * query them individually rather than in a compound query because old
5379 	 * firmwares fail the entire query if an unknown parameter is queried.
5380 	 */
5381 
5382 	/*
5383 	 * MPS buffer group configuration.
5384 	 */
5385 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5386 	val[0] = 0;
5387 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5388 	if (rc == 0)
5389 		sc->params.mps_bg_map = val[0];
5390 	else
5391 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5392 
5393 	param[0] = FW_PARAM_DEV(TPCHMAP);
5394 	val[0] = 0;
5395 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5396 	if (rc == 0)
5397 		sc->params.tp_ch_map = val[0];
5398 	else
5399 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5400 
5401 	/*
5402 	 * Determine whether the firmware supports the filter2 work request.
5403 	 */
5404 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5405 	val[0] = 0;
5406 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5407 	if (rc == 0)
5408 		sc->params.filter2_wr_support = val[0] != 0;
5409 	else
5410 		sc->params.filter2_wr_support = 0;
5411 
5412 	/*
5413 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5414 	 */
5415 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5416 	val[0] = 0;
5417 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5418 	if (rc == 0)
5419 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5420 	else
5421 		sc->params.ulptx_memwrite_dsgl = false;
5422 
5423 	/* FW_RI_FR_NSMR_TPTE_WR support */
5424 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5425 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5426 	if (rc == 0)
5427 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5428 	else
5429 		sc->params.fr_nsmr_tpte_wr_support = false;
5430 
5431 	/* Support for 512 SGL entries per FR MR. */
5432 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5433 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5434 	if (rc == 0)
5435 		sc->params.dev_512sgl_mr = val[0] != 0;
5436 	else
5437 		sc->params.dev_512sgl_mr = false;
5438 
5439 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5440 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5441 	if (rc == 0)
5442 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5443 	else
5444 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5445 
5446 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5447 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5448 	if (rc == 0) {
5449 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5450 		sc->params.nsched_cls = val[0];
5451 	} else
5452 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5453 
5454 	/* get capabilites */
5455 	bzero(&caps, sizeof(caps));
5456 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5457 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5458 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5459 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5460 	if (rc != 0) {
5461 		device_printf(sc->dev,
5462 		    "failed to get card capabilities: %d.\n", rc);
5463 		return (rc);
5464 	}
5465 
5466 #define READ_CAPS(x) do { \
5467 	sc->x = htobe16(caps.x); \
5468 } while (0)
5469 	READ_CAPS(nbmcaps);
5470 	READ_CAPS(linkcaps);
5471 	READ_CAPS(switchcaps);
5472 	READ_CAPS(niccaps);
5473 	READ_CAPS(toecaps);
5474 	READ_CAPS(rdmacaps);
5475 	READ_CAPS(cryptocaps);
5476 	READ_CAPS(iscsicaps);
5477 	READ_CAPS(fcoecaps);
5478 
5479 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5480 		MPASS(chip_id(sc) > CHELSIO_T4);
5481 		MPASS(sc->toecaps == 0);
5482 		sc->toecaps = 0;
5483 
5484 		param[0] = FW_PARAM_DEV(NTID);
5485 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5486 		if (rc != 0) {
5487 			device_printf(sc->dev,
5488 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5489 			return (rc);
5490 		}
5491 		sc->tids.ntids = val[0];
5492 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5493 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5494 			sc->tids.ntids -= sc->tids.nhpftids;
5495 		}
5496 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5497 		sc->params.hash_filter = 1;
5498 	}
5499 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5500 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5501 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5502 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5503 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5504 		if (rc != 0) {
5505 			device_printf(sc->dev,
5506 			    "failed to query NIC parameters: %d.\n", rc);
5507 			return (rc);
5508 		}
5509 		if ((int)val[1] > (int)val[0]) {
5510 			sc->tids.etid_base = val[0];
5511 			sc->tids.etid_end = val[1];
5512 			sc->tids.netids = val[1] - val[0] + 1;
5513 			sc->params.eo_wr_cred = val[2];
5514 			sc->params.ethoffload = 1;
5515 		}
5516 	}
5517 	if (sc->toecaps) {
5518 		/* query offload-related parameters */
5519 		param[0] = FW_PARAM_DEV(NTID);
5520 		param[1] = FW_PARAM_PFVF(SERVER_START);
5521 		param[2] = FW_PARAM_PFVF(SERVER_END);
5522 		param[3] = FW_PARAM_PFVF(TDDP_START);
5523 		param[4] = FW_PARAM_PFVF(TDDP_END);
5524 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5525 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5526 		if (rc != 0) {
5527 			device_printf(sc->dev,
5528 			    "failed to query TOE parameters: %d.\n", rc);
5529 			return (rc);
5530 		}
5531 		sc->tids.ntids = val[0];
5532 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5533 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5534 			sc->tids.ntids -= sc->tids.nhpftids;
5535 		}
5536 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5537 		if ((int)val[2] > (int)val[1]) {
5538 			sc->tids.stid_base = val[1];
5539 			sc->tids.nstids = val[2] - val[1] + 1;
5540 		}
5541 		sc->vres.ddp.start = val[3];
5542 		sc->vres.ddp.size = val[4] - val[3] + 1;
5543 		sc->params.ofldq_wr_cred = val[5];
5544 		sc->params.offload = 1;
5545 	} else {
5546 		/*
5547 		 * The firmware attempts memfree TOE configuration for -SO cards
5548 		 * and will report toecaps=0 if it runs out of resources (this
5549 		 * depends on the config file).  It may not report 0 for other
5550 		 * capabilities dependent on the TOE in this case.  Set them to
5551 		 * 0 here so that the driver doesn't bother tracking resources
5552 		 * that will never be used.
5553 		 */
5554 		sc->iscsicaps = 0;
5555 		sc->rdmacaps = 0;
5556 	}
5557 	if (sc->rdmacaps) {
5558 		param[0] = FW_PARAM_PFVF(STAG_START);
5559 		param[1] = FW_PARAM_PFVF(STAG_END);
5560 		param[2] = FW_PARAM_PFVF(RQ_START);
5561 		param[3] = FW_PARAM_PFVF(RQ_END);
5562 		param[4] = FW_PARAM_PFVF(PBL_START);
5563 		param[5] = FW_PARAM_PFVF(PBL_END);
5564 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5565 		if (rc != 0) {
5566 			device_printf(sc->dev,
5567 			    "failed to query RDMA parameters(1): %d.\n", rc);
5568 			return (rc);
5569 		}
5570 		sc->vres.stag.start = val[0];
5571 		sc->vres.stag.size = val[1] - val[0] + 1;
5572 		sc->vres.rq.start = val[2];
5573 		sc->vres.rq.size = val[3] - val[2] + 1;
5574 		sc->vres.pbl.start = val[4];
5575 		sc->vres.pbl.size = val[5] - val[4] + 1;
5576 
5577 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5578 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5579 		param[2] = FW_PARAM_PFVF(CQ_START);
5580 		param[3] = FW_PARAM_PFVF(CQ_END);
5581 		param[4] = FW_PARAM_PFVF(OCQ_START);
5582 		param[5] = FW_PARAM_PFVF(OCQ_END);
5583 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5584 		if (rc != 0) {
5585 			device_printf(sc->dev,
5586 			    "failed to query RDMA parameters(2): %d.\n", rc);
5587 			return (rc);
5588 		}
5589 		sc->vres.qp.start = val[0];
5590 		sc->vres.qp.size = val[1] - val[0] + 1;
5591 		sc->vres.cq.start = val[2];
5592 		sc->vres.cq.size = val[3] - val[2] + 1;
5593 		sc->vres.ocq.start = val[4];
5594 		sc->vres.ocq.size = val[5] - val[4] + 1;
5595 
5596 		param[0] = FW_PARAM_PFVF(SRQ_START);
5597 		param[1] = FW_PARAM_PFVF(SRQ_END);
5598 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5599 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5600 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5601 		if (rc != 0) {
5602 			device_printf(sc->dev,
5603 			    "failed to query RDMA parameters(3): %d.\n", rc);
5604 			return (rc);
5605 		}
5606 		sc->vres.srq.start = val[0];
5607 		sc->vres.srq.size = val[1] - val[0] + 1;
5608 		sc->params.max_ordird_qp = val[2];
5609 		sc->params.max_ird_adapter = val[3];
5610 	}
5611 	if (sc->iscsicaps) {
5612 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5613 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5614 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5615 		if (rc != 0) {
5616 			device_printf(sc->dev,
5617 			    "failed to query iSCSI parameters: %d.\n", rc);
5618 			return (rc);
5619 		}
5620 		sc->vres.iscsi.start = val[0];
5621 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5622 	}
5623 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5624 		param[0] = FW_PARAM_PFVF(TLS_START);
5625 		param[1] = FW_PARAM_PFVF(TLS_END);
5626 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5627 		if (rc != 0) {
5628 			device_printf(sc->dev,
5629 			    "failed to query TLS parameters: %d.\n", rc);
5630 			return (rc);
5631 		}
5632 		sc->vres.key.start = val[0];
5633 		sc->vres.key.size = val[1] - val[0] + 1;
5634 	}
5635 
5636 	/*
5637 	 * We've got the params we wanted to query directly from the firmware.
5638 	 * Grab some others via other means.
5639 	 */
5640 	t4_init_sge_params(sc);
5641 	t4_init_tp_params(sc);
5642 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5643 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5644 
5645 	rc = t4_verify_chip_settings(sc);
5646 	if (rc != 0)
5647 		return (rc);
5648 	t4_init_rx_buf_info(sc);
5649 
5650 	return (rc);
5651 }
5652 
5653 #ifdef KERN_TLS
5654 static void
5655 ktls_tick(void *arg)
5656 {
5657 	struct adapter *sc;
5658 	uint32_t tstamp;
5659 
5660 	sc = arg;
5661 	tstamp = tcp_ts_getticks();
5662 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5663 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5664 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5665 }
5666 
5667 static int
5668 t6_config_kern_tls(struct adapter *sc, bool enable)
5669 {
5670 	int rc;
5671 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5672 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5673 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5674 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5675 
5676 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5677 	if (rc != 0) {
5678 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5679 		    enable ?  "enable" : "disable", rc);
5680 		return (rc);
5681 	}
5682 
5683 	if (enable) {
5684 		sc->flags |= KERN_TLS_ON;
5685 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5686 		    C_HARDCLOCK);
5687 	} else {
5688 		sc->flags &= ~KERN_TLS_ON;
5689 		callout_stop(&sc->ktls_tick);
5690 	}
5691 
5692 	return (rc);
5693 }
5694 #endif
5695 
5696 static int
5697 set_params__post_init(struct adapter *sc)
5698 {
5699 	uint32_t mask, param, val;
5700 #ifdef TCP_OFFLOAD
5701 	int i, v, shift;
5702 #endif
5703 
5704 	/* ask for encapsulated CPLs */
5705 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5706 	val = 1;
5707 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5708 
5709 	/* Enable 32b port caps if the firmware supports it. */
5710 	param = FW_PARAM_PFVF(PORT_CAPS32);
5711 	val = 1;
5712 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5713 		sc->params.port_caps32 = 1;
5714 
5715 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5716 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5717 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5718 	    V_MASKFILTER(val - 1));
5719 
5720 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5721 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5722 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5723 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5724 	val = 0;
5725 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5726 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5727 		    F_ATTACKFILTERENABLE);
5728 		val |= F_DROPERRORATTACK;
5729 	}
5730 	if (t4_drop_ip_fragments != 0) {
5731 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5732 		    F_FRAGMENTDROP);
5733 		val |= F_DROPERRORFRAG;
5734 	}
5735 	if (t4_drop_pkts_with_l2_errors != 0)
5736 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5737 	if (t4_drop_pkts_with_l3_errors != 0) {
5738 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5739 		    F_DROPERRORCSUMIP;
5740 	}
5741 	if (t4_drop_pkts_with_l4_errors != 0) {
5742 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5743 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5744 	}
5745 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5746 
5747 #ifdef TCP_OFFLOAD
5748 	/*
5749 	 * Override the TOE timers with user provided tunables.  This is not the
5750 	 * recommended way to change the timers (the firmware config file is) so
5751 	 * these tunables are not documented.
5752 	 *
5753 	 * All the timer tunables are in microseconds.
5754 	 */
5755 	if (t4_toe_keepalive_idle != 0) {
5756 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5757 		v &= M_KEEPALIVEIDLE;
5758 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5759 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5760 	}
5761 	if (t4_toe_keepalive_interval != 0) {
5762 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5763 		v &= M_KEEPALIVEINTVL;
5764 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5765 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5766 	}
5767 	if (t4_toe_keepalive_count != 0) {
5768 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5769 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5770 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5771 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5772 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5773 	}
5774 	if (t4_toe_rexmt_min != 0) {
5775 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5776 		v &= M_RXTMIN;
5777 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5778 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5779 	}
5780 	if (t4_toe_rexmt_max != 0) {
5781 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5782 		v &= M_RXTMAX;
5783 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5784 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5785 	}
5786 	if (t4_toe_rexmt_count != 0) {
5787 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5788 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5789 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5790 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5791 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5792 	}
5793 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5794 		if (t4_toe_rexmt_backoff[i] != -1) {
5795 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5796 			shift = (i & 3) << 3;
5797 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5798 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5799 		}
5800 	}
5801 #endif
5802 
5803 	/*
5804 	 * Limit TOE connections to 2 reassembly "islands".  This is
5805 	 * required to permit migrating TOE connections to either
5806 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5807 	 */
5808 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5809 	    V_PASSMODE(2));
5810 
5811 #ifdef KERN_TLS
5812 	if (is_ktls(sc)) {
5813 		sc->tlst.inline_keys = t4_tls_inline_keys;
5814 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5815 		if (t4_kern_tls != 0 && is_t6(sc))
5816 			t6_config_kern_tls(sc, true);
5817 	}
5818 #endif
5819 	return (0);
5820 }
5821 
5822 #undef FW_PARAM_PFVF
5823 #undef FW_PARAM_DEV
5824 
5825 static void
5826 t4_set_desc(struct adapter *sc)
5827 {
5828 	struct adapter_params *p = &sc->params;
5829 
5830 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5831 }
5832 
5833 static inline void
5834 ifmedia_add4(struct ifmedia *ifm, int m)
5835 {
5836 
5837 	ifmedia_add(ifm, m, 0, NULL);
5838 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5839 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5840 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5841 }
5842 
5843 /*
5844  * This is the selected media, which is not quite the same as the active media.
5845  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5846  * and active are not the same, and "media: Ethernet selected" otherwise.
5847  */
5848 static void
5849 set_current_media(struct port_info *pi)
5850 {
5851 	struct link_config *lc;
5852 	struct ifmedia *ifm;
5853 	int mword;
5854 	u_int speed;
5855 
5856 	PORT_LOCK_ASSERT_OWNED(pi);
5857 
5858 	/* Leave current media alone if it's already set to IFM_NONE. */
5859 	ifm = &pi->media;
5860 	if (ifm->ifm_cur != NULL &&
5861 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5862 		return;
5863 
5864 	lc = &pi->link_cfg;
5865 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5866 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5867 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5868 		return;
5869 	}
5870 	mword = IFM_ETHER | IFM_FDX;
5871 	if (lc->requested_fc & PAUSE_TX)
5872 		mword |= IFM_ETH_TXPAUSE;
5873 	if (lc->requested_fc & PAUSE_RX)
5874 		mword |= IFM_ETH_RXPAUSE;
5875 	if (lc->requested_speed == 0)
5876 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5877 	else
5878 		speed = lc->requested_speed;
5879 	mword |= port_mword(pi, speed_to_fwcap(speed));
5880 	ifmedia_set(ifm, mword);
5881 }
5882 
5883 /*
5884  * Returns true if the ifmedia list for the port cannot change.
5885  */
5886 static bool
5887 fixed_ifmedia(struct port_info *pi)
5888 {
5889 
5890 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5891 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5892 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5893 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5894 	    pi->port_type == FW_PORT_TYPE_KX ||
5895 	    pi->port_type == FW_PORT_TYPE_KR ||
5896 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5897 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5898 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5899 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5900 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5901 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5902 }
5903 
5904 static void
5905 build_medialist(struct port_info *pi)
5906 {
5907 	uint32_t ss, speed;
5908 	int unknown, mword, bit;
5909 	struct link_config *lc;
5910 	struct ifmedia *ifm;
5911 
5912 	PORT_LOCK_ASSERT_OWNED(pi);
5913 
5914 	if (pi->flags & FIXED_IFMEDIA)
5915 		return;
5916 
5917 	/*
5918 	 * Rebuild the ifmedia list.
5919 	 */
5920 	ifm = &pi->media;
5921 	ifmedia_removeall(ifm);
5922 	lc = &pi->link_cfg;
5923 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5924 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5925 		MPASS(ss != 0);
5926 no_media:
5927 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5928 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5929 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5930 		return;
5931 	}
5932 
5933 	unknown = 0;
5934 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5935 		speed = 1 << bit;
5936 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5937 		if (ss & speed) {
5938 			mword = port_mword(pi, speed);
5939 			if (mword == IFM_NONE) {
5940 				goto no_media;
5941 			} else if (mword == IFM_UNKNOWN)
5942 				unknown++;
5943 			else
5944 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5945 		}
5946 	}
5947 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5948 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5949 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5950 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5951 
5952 	set_current_media(pi);
5953 }
5954 
5955 /*
5956  * Initialize the requested fields in the link config based on driver tunables.
5957  */
5958 static void
5959 init_link_config(struct port_info *pi)
5960 {
5961 	struct link_config *lc = &pi->link_cfg;
5962 
5963 	PORT_LOCK_ASSERT_OWNED(pi);
5964 
5965 	lc->requested_caps = 0;
5966 	lc->requested_speed = 0;
5967 
5968 	if (t4_autoneg == 0)
5969 		lc->requested_aneg = AUTONEG_DISABLE;
5970 	else if (t4_autoneg == 1)
5971 		lc->requested_aneg = AUTONEG_ENABLE;
5972 	else
5973 		lc->requested_aneg = AUTONEG_AUTO;
5974 
5975 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5976 	    PAUSE_AUTONEG);
5977 
5978 	if (t4_fec & FEC_AUTO)
5979 		lc->requested_fec = FEC_AUTO;
5980 	else if (t4_fec == 0)
5981 		lc->requested_fec = FEC_NONE;
5982 	else {
5983 		/* -1 is handled by the FEC_AUTO block above and not here. */
5984 		lc->requested_fec = t4_fec &
5985 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5986 		if (lc->requested_fec == 0)
5987 			lc->requested_fec = FEC_AUTO;
5988 	}
5989 	if (t4_force_fec < 0)
5990 		lc->force_fec = -1;
5991 	else if (t4_force_fec > 0)
5992 		lc->force_fec = 1;
5993 	else
5994 		lc->force_fec = 0;
5995 }
5996 
5997 /*
5998  * Makes sure that all requested settings comply with what's supported by the
5999  * port.  Returns the number of settings that were invalid and had to be fixed.
6000  */
6001 static int
6002 fixup_link_config(struct port_info *pi)
6003 {
6004 	int n = 0;
6005 	struct link_config *lc = &pi->link_cfg;
6006 	uint32_t fwspeed;
6007 
6008 	PORT_LOCK_ASSERT_OWNED(pi);
6009 
6010 	/* Speed (when not autonegotiating) */
6011 	if (lc->requested_speed != 0) {
6012 		fwspeed = speed_to_fwcap(lc->requested_speed);
6013 		if ((fwspeed & lc->pcaps) == 0) {
6014 			n++;
6015 			lc->requested_speed = 0;
6016 		}
6017 	}
6018 
6019 	/* Link autonegotiation */
6020 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6021 	    lc->requested_aneg == AUTONEG_DISABLE ||
6022 	    lc->requested_aneg == AUTONEG_AUTO);
6023 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6024 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6025 		n++;
6026 		lc->requested_aneg = AUTONEG_AUTO;
6027 	}
6028 
6029 	/* Flow control */
6030 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6031 	if (lc->requested_fc & PAUSE_TX &&
6032 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6033 		n++;
6034 		lc->requested_fc &= ~PAUSE_TX;
6035 	}
6036 	if (lc->requested_fc & PAUSE_RX &&
6037 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6038 		n++;
6039 		lc->requested_fc &= ~PAUSE_RX;
6040 	}
6041 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6042 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6043 		n++;
6044 		lc->requested_fc |= PAUSE_AUTONEG;
6045 	}
6046 
6047 	/* FEC */
6048 	if ((lc->requested_fec & FEC_RS &&
6049 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6050 	    (lc->requested_fec & FEC_BASER_RS &&
6051 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6052 		n++;
6053 		lc->requested_fec = FEC_AUTO;
6054 	}
6055 
6056 	return (n);
6057 }
6058 
6059 /*
6060  * Apply the requested L1 settings, which are expected to be valid, to the
6061  * hardware.
6062  */
6063 static int
6064 apply_link_config(struct port_info *pi)
6065 {
6066 	struct adapter *sc = pi->adapter;
6067 	struct link_config *lc = &pi->link_cfg;
6068 	int rc;
6069 
6070 #ifdef INVARIANTS
6071 	ASSERT_SYNCHRONIZED_OP(sc);
6072 	PORT_LOCK_ASSERT_OWNED(pi);
6073 
6074 	if (lc->requested_aneg == AUTONEG_ENABLE)
6075 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6076 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6077 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6078 	if (lc->requested_fc & PAUSE_TX)
6079 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6080 	if (lc->requested_fc & PAUSE_RX)
6081 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6082 	if (lc->requested_fec & FEC_RS)
6083 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6084 	if (lc->requested_fec & FEC_BASER_RS)
6085 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6086 #endif
6087 	if (!(sc->flags & IS_VF)) {
6088 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6089 		if (rc != 0) {
6090 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6091 			return (rc);
6092 		}
6093 	}
6094 
6095 	/*
6096 	 * An L1_CFG will almost always result in a link-change event if the
6097 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6098 	 * the notification is processed.  If the link is down then the actual
6099 	 * settings are meaningless.
6100 	 *
6101 	 * This takes care of the case where a change in the L1 settings may not
6102 	 * result in a notification.
6103 	 */
6104 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6105 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6106 
6107 	return (0);
6108 }
6109 
6110 #define FW_MAC_EXACT_CHUNK	7
6111 struct mcaddr_ctx {
6112 	if_t ifp;
6113 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6114 	uint64_t hash;
6115 	int i;
6116 	int del;
6117 	int rc;
6118 };
6119 
6120 static u_int
6121 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6122 {
6123 	struct mcaddr_ctx *ctx = arg;
6124 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6125 	struct port_info *pi = vi->pi;
6126 	struct adapter *sc = pi->adapter;
6127 
6128 	if (ctx->rc < 0)
6129 		return (0);
6130 
6131 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6132 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6133 	ctx->i++;
6134 
6135 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6136 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6137 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6138 		if (ctx->rc < 0) {
6139 			int j;
6140 
6141 			for (j = 0; j < ctx->i; j++) {
6142 				if_printf(ctx->ifp,
6143 				    "failed to add mc address"
6144 				    " %02x:%02x:%02x:"
6145 				    "%02x:%02x:%02x rc=%d\n",
6146 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6147 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6148 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6149 				    -ctx->rc);
6150 			}
6151 			return (0);
6152 		}
6153 		ctx->del = 0;
6154 		ctx->i = 0;
6155 	}
6156 
6157 	return (1);
6158 }
6159 
6160 /*
6161  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6162  * indicates which parameters should be programmed (the rest are left alone).
6163  */
6164 int
6165 update_mac_settings(if_t ifp, int flags)
6166 {
6167 	int rc = 0;
6168 	struct vi_info *vi = if_getsoftc(ifp);
6169 	struct port_info *pi = vi->pi;
6170 	struct adapter *sc = pi->adapter;
6171 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6172 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6173 
6174 	ASSERT_SYNCHRONIZED_OP(sc);
6175 	KASSERT(flags, ("%s: not told what to update.", __func__));
6176 
6177 	if (flags & XGMAC_MTU)
6178 		mtu = if_getmtu(ifp);
6179 
6180 	if (flags & XGMAC_PROMISC)
6181 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6182 
6183 	if (flags & XGMAC_ALLMULTI)
6184 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6185 
6186 	if (flags & XGMAC_VLANEX)
6187 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6188 
6189 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6190 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6191 		    allmulti, 1, vlanex, false);
6192 		if (rc) {
6193 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6194 			    rc);
6195 			return (rc);
6196 		}
6197 	}
6198 
6199 	if (flags & XGMAC_UCADDR) {
6200 		uint8_t ucaddr[ETHER_ADDR_LEN];
6201 
6202 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6203 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6204 		    ucaddr, true, &vi->smt_idx);
6205 		if (rc < 0) {
6206 			rc = -rc;
6207 			if_printf(ifp, "change_mac failed: %d\n", rc);
6208 			return (rc);
6209 		} else {
6210 			vi->xact_addr_filt = rc;
6211 			rc = 0;
6212 		}
6213 	}
6214 
6215 	if (flags & XGMAC_MCADDRS) {
6216 		struct epoch_tracker et;
6217 		struct mcaddr_ctx ctx;
6218 		int j;
6219 
6220 		ctx.ifp = ifp;
6221 		ctx.hash = 0;
6222 		ctx.i = 0;
6223 		ctx.del = 1;
6224 		ctx.rc = 0;
6225 		/*
6226 		 * Unlike other drivers, we accumulate list of pointers into
6227 		 * interface address lists and we need to keep it safe even
6228 		 * after if_foreach_llmaddr() returns, thus we must enter the
6229 		 * network epoch.
6230 		 */
6231 		NET_EPOCH_ENTER(et);
6232 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6233 		if (ctx.rc < 0) {
6234 			NET_EPOCH_EXIT(et);
6235 			rc = -ctx.rc;
6236 			return (rc);
6237 		}
6238 		if (ctx.i > 0) {
6239 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6240 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6241 			NET_EPOCH_EXIT(et);
6242 			if (rc < 0) {
6243 				rc = -rc;
6244 				for (j = 0; j < ctx.i; j++) {
6245 					if_printf(ifp,
6246 					    "failed to add mcast address"
6247 					    " %02x:%02x:%02x:"
6248 					    "%02x:%02x:%02x rc=%d\n",
6249 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6250 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6251 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6252 					    rc);
6253 				}
6254 				return (rc);
6255 			}
6256 			ctx.del = 0;
6257 		} else
6258 			NET_EPOCH_EXIT(et);
6259 
6260 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6261 		if (rc != 0)
6262 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6263 			    rc);
6264 		if (ctx.del == 0) {
6265 			/* We clobbered the VXLAN entry if there was one. */
6266 			pi->vxlan_tcam_entry = false;
6267 		}
6268 	}
6269 
6270 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6271 	    pi->vxlan_tcam_entry == false) {
6272 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6273 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6274 		    true);
6275 		if (rc < 0) {
6276 			rc = -rc;
6277 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6278 			    rc);
6279 		} else {
6280 			MPASS(rc == sc->rawf_base + pi->port_id);
6281 			rc = 0;
6282 			pi->vxlan_tcam_entry = true;
6283 		}
6284 	}
6285 
6286 	return (rc);
6287 }
6288 
6289 /*
6290  * {begin|end}_synchronized_op must be called from the same thread.
6291  */
6292 int
6293 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6294     char *wmesg)
6295 {
6296 	int rc, pri;
6297 
6298 #ifdef WITNESS
6299 	/* the caller thinks it's ok to sleep, but is it really? */
6300 	if (flags & SLEEP_OK)
6301 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6302 		    "begin_synchronized_op");
6303 #endif
6304 
6305 	if (INTR_OK)
6306 		pri = PCATCH;
6307 	else
6308 		pri = 0;
6309 
6310 	ADAPTER_LOCK(sc);
6311 	for (;;) {
6312 
6313 		if (vi && IS_DETACHING(vi)) {
6314 			rc = ENXIO;
6315 			goto done;
6316 		}
6317 
6318 		if (!IS_BUSY(sc)) {
6319 			rc = 0;
6320 			break;
6321 		}
6322 
6323 		if (!(flags & SLEEP_OK)) {
6324 			rc = EBUSY;
6325 			goto done;
6326 		}
6327 
6328 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6329 			rc = EINTR;
6330 			goto done;
6331 		}
6332 	}
6333 
6334 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6335 	SET_BUSY(sc);
6336 #ifdef INVARIANTS
6337 	sc->last_op = wmesg;
6338 	sc->last_op_thr = curthread;
6339 	sc->last_op_flags = flags;
6340 #endif
6341 
6342 done:
6343 	if (!(flags & HOLD_LOCK) || rc)
6344 		ADAPTER_UNLOCK(sc);
6345 
6346 	return (rc);
6347 }
6348 
6349 /*
6350  * Tell if_ioctl and if_init that the VI is going away.  This is
6351  * special variant of begin_synchronized_op and must be paired with a
6352  * call to end_vi_detach.
6353  */
6354 void
6355 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6356 {
6357 	ADAPTER_LOCK(sc);
6358 	SET_DETACHING(vi);
6359 	wakeup(&sc->flags);
6360 	while (IS_BUSY(sc))
6361 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6362 	SET_BUSY(sc);
6363 #ifdef INVARIANTS
6364 	sc->last_op = "t4detach";
6365 	sc->last_op_thr = curthread;
6366 	sc->last_op_flags = 0;
6367 #endif
6368 	ADAPTER_UNLOCK(sc);
6369 }
6370 
6371 void
6372 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6373 {
6374 	ADAPTER_LOCK(sc);
6375 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6376 	CLR_BUSY(sc);
6377 	CLR_DETACHING(vi);
6378 	wakeup(&sc->flags);
6379 	ADAPTER_UNLOCK(sc);
6380 }
6381 
6382 /*
6383  * {begin|end}_synchronized_op must be called from the same thread.
6384  */
6385 void
6386 end_synchronized_op(struct adapter *sc, int flags)
6387 {
6388 
6389 	if (flags & LOCK_HELD)
6390 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6391 	else
6392 		ADAPTER_LOCK(sc);
6393 
6394 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6395 	CLR_BUSY(sc);
6396 	wakeup(&sc->flags);
6397 	ADAPTER_UNLOCK(sc);
6398 }
6399 
6400 static int
6401 cxgbe_init_synchronized(struct vi_info *vi)
6402 {
6403 	struct port_info *pi = vi->pi;
6404 	struct adapter *sc = pi->adapter;
6405 	if_t ifp = vi->ifp;
6406 	int rc = 0, i;
6407 	struct sge_txq *txq;
6408 
6409 	ASSERT_SYNCHRONIZED_OP(sc);
6410 
6411 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6412 		return (0);	/* already running */
6413 
6414 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6415 		return (rc);	/* error message displayed already */
6416 
6417 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6418 		return (rc); /* error message displayed already */
6419 
6420 	rc = update_mac_settings(ifp, XGMAC_ALL);
6421 	if (rc)
6422 		goto done;	/* error message displayed already */
6423 
6424 	PORT_LOCK(pi);
6425 	if (pi->up_vis == 0) {
6426 		t4_update_port_info(pi);
6427 		fixup_link_config(pi);
6428 		build_medialist(pi);
6429 		apply_link_config(pi);
6430 	}
6431 
6432 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6433 	if (rc != 0) {
6434 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6435 		PORT_UNLOCK(pi);
6436 		goto done;
6437 	}
6438 
6439 	/*
6440 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6441 	 * if this changes.
6442 	 */
6443 
6444 	for_each_txq(vi, i, txq) {
6445 		TXQ_LOCK(txq);
6446 		txq->eq.flags |= EQ_ENABLED;
6447 		TXQ_UNLOCK(txq);
6448 	}
6449 
6450 	/*
6451 	 * The first iq of the first port to come up is used for tracing.
6452 	 */
6453 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6454 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6455 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6456 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6457 		    V_QUEUENUMBER(sc->traceq));
6458 		pi->flags |= HAS_TRACEQ;
6459 	}
6460 
6461 	/* all ok */
6462 	pi->up_vis++;
6463 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6464 	if (pi->link_cfg.link_ok)
6465 		t4_os_link_changed(pi);
6466 	PORT_UNLOCK(pi);
6467 
6468 	mtx_lock(&vi->tick_mtx);
6469 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6470 		callout_reset(&vi->tick, hz, vi_tick, vi);
6471 	else
6472 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6473 	mtx_unlock(&vi->tick_mtx);
6474 done:
6475 	if (rc != 0)
6476 		cxgbe_uninit_synchronized(vi);
6477 
6478 	return (rc);
6479 }
6480 
6481 /*
6482  * Idempotent.
6483  */
6484 static int
6485 cxgbe_uninit_synchronized(struct vi_info *vi)
6486 {
6487 	struct port_info *pi = vi->pi;
6488 	struct adapter *sc = pi->adapter;
6489 	if_t ifp = vi->ifp;
6490 	int rc, i;
6491 	struct sge_txq *txq;
6492 
6493 	ASSERT_SYNCHRONIZED_OP(sc);
6494 
6495 	if (!(vi->flags & VI_INIT_DONE)) {
6496 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6497 			KASSERT(0, ("uninited VI is running"));
6498 			if_printf(ifp, "uninited VI with running ifnet.  "
6499 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6500 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6501 			    if_getdrvflags(ifp));
6502 		}
6503 		return (0);
6504 	}
6505 
6506 	/*
6507 	 * Disable the VI so that all its data in either direction is discarded
6508 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6509 	 * tick) intact as the TP can deliver negative advice or data that it's
6510 	 * holding in its RAM (for an offloaded connection) even after the VI is
6511 	 * disabled.
6512 	 */
6513 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6514 	if (rc) {
6515 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6516 		return (rc);
6517 	}
6518 
6519 	for_each_txq(vi, i, txq) {
6520 		TXQ_LOCK(txq);
6521 		txq->eq.flags &= ~EQ_ENABLED;
6522 		TXQ_UNLOCK(txq);
6523 	}
6524 
6525 	mtx_lock(&vi->tick_mtx);
6526 	callout_stop(&vi->tick);
6527 	mtx_unlock(&vi->tick_mtx);
6528 
6529 	PORT_LOCK(pi);
6530 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6531 		PORT_UNLOCK(pi);
6532 		return (0);
6533 	}
6534 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6535 	pi->up_vis--;
6536 	if (pi->up_vis > 0) {
6537 		PORT_UNLOCK(pi);
6538 		return (0);
6539 	}
6540 
6541 	pi->link_cfg.link_ok = false;
6542 	pi->link_cfg.speed = 0;
6543 	pi->link_cfg.link_down_rc = 255;
6544 	t4_os_link_changed(pi);
6545 	PORT_UNLOCK(pi);
6546 
6547 	return (0);
6548 }
6549 
6550 /*
6551  * It is ok for this function to fail midway and return right away.  t4_detach
6552  * will walk the entire sc->irq list and clean up whatever is valid.
6553  */
6554 int
6555 t4_setup_intr_handlers(struct adapter *sc)
6556 {
6557 	int rc, rid, p, q, v;
6558 	char s[8];
6559 	struct irq *irq;
6560 	struct port_info *pi;
6561 	struct vi_info *vi;
6562 	struct sge *sge = &sc->sge;
6563 	struct sge_rxq *rxq;
6564 #ifdef TCP_OFFLOAD
6565 	struct sge_ofld_rxq *ofld_rxq;
6566 #endif
6567 #ifdef DEV_NETMAP
6568 	struct sge_nm_rxq *nm_rxq;
6569 #endif
6570 #ifdef RSS
6571 	int nbuckets = rss_getnumbuckets();
6572 #endif
6573 
6574 	/*
6575 	 * Setup interrupts.
6576 	 */
6577 	irq = &sc->irq[0];
6578 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6579 	if (forwarding_intr_to_fwq(sc))
6580 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6581 
6582 	/* Multiple interrupts. */
6583 	if (sc->flags & IS_VF)
6584 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6585 		    ("%s: too few intr.", __func__));
6586 	else
6587 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6588 		    ("%s: too few intr.", __func__));
6589 
6590 	/* The first one is always error intr on PFs */
6591 	if (!(sc->flags & IS_VF)) {
6592 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6593 		if (rc != 0)
6594 			return (rc);
6595 		irq++;
6596 		rid++;
6597 	}
6598 
6599 	/* The second one is always the firmware event queue (first on VFs) */
6600 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6601 	if (rc != 0)
6602 		return (rc);
6603 	irq++;
6604 	rid++;
6605 
6606 	for_each_port(sc, p) {
6607 		pi = sc->port[p];
6608 		for_each_vi(pi, v, vi) {
6609 			vi->first_intr = rid - 1;
6610 
6611 			if (vi->nnmrxq > 0) {
6612 				int n = max(vi->nrxq, vi->nnmrxq);
6613 
6614 				rxq = &sge->rxq[vi->first_rxq];
6615 #ifdef DEV_NETMAP
6616 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6617 #endif
6618 				for (q = 0; q < n; q++) {
6619 					snprintf(s, sizeof(s), "%x%c%x", p,
6620 					    'a' + v, q);
6621 					if (q < vi->nrxq)
6622 						irq->rxq = rxq++;
6623 #ifdef DEV_NETMAP
6624 					if (q < vi->nnmrxq)
6625 						irq->nm_rxq = nm_rxq++;
6626 
6627 					if (irq->nm_rxq != NULL &&
6628 					    irq->rxq == NULL) {
6629 						/* Netmap rx only */
6630 						rc = t4_alloc_irq(sc, irq, rid,
6631 						    t4_nm_intr, irq->nm_rxq, s);
6632 					}
6633 					if (irq->nm_rxq != NULL &&
6634 					    irq->rxq != NULL) {
6635 						/* NIC and Netmap rx */
6636 						rc = t4_alloc_irq(sc, irq, rid,
6637 						    t4_vi_intr, irq, s);
6638 					}
6639 #endif
6640 					if (irq->rxq != NULL &&
6641 					    irq->nm_rxq == NULL) {
6642 						/* NIC rx only */
6643 						rc = t4_alloc_irq(sc, irq, rid,
6644 						    t4_intr, irq->rxq, s);
6645 					}
6646 					if (rc != 0)
6647 						return (rc);
6648 #ifdef RSS
6649 					if (q < vi->nrxq) {
6650 						bus_bind_intr(sc->dev, irq->res,
6651 						    rss_getcpu(q % nbuckets));
6652 					}
6653 #endif
6654 					irq++;
6655 					rid++;
6656 					vi->nintr++;
6657 				}
6658 			} else {
6659 				for_each_rxq(vi, q, rxq) {
6660 					snprintf(s, sizeof(s), "%x%c%x", p,
6661 					    'a' + v, q);
6662 					rc = t4_alloc_irq(sc, irq, rid,
6663 					    t4_intr, rxq, s);
6664 					if (rc != 0)
6665 						return (rc);
6666 #ifdef RSS
6667 					bus_bind_intr(sc->dev, irq->res,
6668 					    rss_getcpu(q % nbuckets));
6669 #endif
6670 					irq++;
6671 					rid++;
6672 					vi->nintr++;
6673 				}
6674 			}
6675 #ifdef TCP_OFFLOAD
6676 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6677 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6678 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6679 				    ofld_rxq, s);
6680 				if (rc != 0)
6681 					return (rc);
6682 				irq++;
6683 				rid++;
6684 				vi->nintr++;
6685 			}
6686 #endif
6687 		}
6688 	}
6689 	MPASS(irq == &sc->irq[sc->intr_count]);
6690 
6691 	return (0);
6692 }
6693 
6694 static void
6695 write_global_rss_key(struct adapter *sc)
6696 {
6697 #ifdef RSS
6698 	int i;
6699 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6700 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6701 
6702 	CTASSERT(RSS_KEYSIZE == 40);
6703 
6704 	rss_getkey((void *)&raw_rss_key[0]);
6705 	for (i = 0; i < nitems(rss_key); i++) {
6706 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6707 	}
6708 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6709 #endif
6710 }
6711 
6712 /*
6713  * Idempotent.
6714  */
6715 static int
6716 adapter_full_init(struct adapter *sc)
6717 {
6718 	int rc, i;
6719 
6720 	ASSERT_SYNCHRONIZED_OP(sc);
6721 
6722 	/*
6723 	 * queues that belong to the adapter (not any particular port).
6724 	 */
6725 	rc = t4_setup_adapter_queues(sc);
6726 	if (rc != 0)
6727 		return (rc);
6728 
6729 	MPASS(sc->params.nports <= nitems(sc->tq));
6730 	for (i = 0; i < sc->params.nports; i++) {
6731 		if (sc->tq[i] != NULL)
6732 			continue;
6733 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6734 		    taskqueue_thread_enqueue, &sc->tq[i]);
6735 		if (sc->tq[i] == NULL) {
6736 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6737 			return (ENOMEM);
6738 		}
6739 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6740 		    device_get_nameunit(sc->dev), i);
6741 	}
6742 
6743 	if (!(sc->flags & IS_VF)) {
6744 		write_global_rss_key(sc);
6745 		t4_intr_enable(sc);
6746 	}
6747 	return (0);
6748 }
6749 
6750 int
6751 adapter_init(struct adapter *sc)
6752 {
6753 	int rc;
6754 
6755 	ASSERT_SYNCHRONIZED_OP(sc);
6756 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6757 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6758 	    ("%s: FULL_INIT_DONE already", __func__));
6759 
6760 	rc = adapter_full_init(sc);
6761 	if (rc != 0)
6762 		adapter_full_uninit(sc);
6763 	else
6764 		sc->flags |= FULL_INIT_DONE;
6765 
6766 	return (rc);
6767 }
6768 
6769 /*
6770  * Idempotent.
6771  */
6772 static void
6773 adapter_full_uninit(struct adapter *sc)
6774 {
6775 	int i;
6776 
6777 	t4_teardown_adapter_queues(sc);
6778 
6779 	for (i = 0; i < nitems(sc->tq); i++) {
6780 		if (sc->tq[i] == NULL)
6781 			continue;
6782 		taskqueue_free(sc->tq[i]);
6783 		sc->tq[i] = NULL;
6784 	}
6785 
6786 	sc->flags &= ~FULL_INIT_DONE;
6787 }
6788 
6789 #ifdef RSS
6790 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6791     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6792     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6793     RSS_HASHTYPE_RSS_UDP_IPV6)
6794 
6795 /* Translates kernel hash types to hardware. */
6796 static int
6797 hashconfig_to_hashen(int hashconfig)
6798 {
6799 	int hashen = 0;
6800 
6801 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6802 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6803 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6804 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6805 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6806 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6807 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6808 	}
6809 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6810 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6811 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6812 	}
6813 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6814 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6815 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6816 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6817 
6818 	return (hashen);
6819 }
6820 
6821 /* Translates hardware hash types to kernel. */
6822 static int
6823 hashen_to_hashconfig(int hashen)
6824 {
6825 	int hashconfig = 0;
6826 
6827 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6828 		/*
6829 		 * If UDP hashing was enabled it must have been enabled for
6830 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6831 		 * enabling any 4-tuple hash is nonsense configuration.
6832 		 */
6833 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6834 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6835 
6836 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6837 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6838 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6839 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6840 	}
6841 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6842 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6843 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6844 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6845 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6846 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6847 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6848 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6849 
6850 	return (hashconfig);
6851 }
6852 #endif
6853 
6854 /*
6855  * Idempotent.
6856  */
6857 static int
6858 vi_full_init(struct vi_info *vi)
6859 {
6860 	struct adapter *sc = vi->adapter;
6861 	struct sge_rxq *rxq;
6862 	int rc, i, j;
6863 #ifdef RSS
6864 	int nbuckets = rss_getnumbuckets();
6865 	int hashconfig = rss_gethashconfig();
6866 	int extra;
6867 #endif
6868 
6869 	ASSERT_SYNCHRONIZED_OP(sc);
6870 
6871 	/*
6872 	 * Allocate tx/rx/fl queues for this VI.
6873 	 */
6874 	rc = t4_setup_vi_queues(vi);
6875 	if (rc != 0)
6876 		return (rc);
6877 
6878 	/*
6879 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6880 	 */
6881 	if (vi->nrxq > vi->rss_size) {
6882 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6883 		    "some queues will never receive traffic.\n", vi->nrxq,
6884 		    vi->rss_size);
6885 	} else if (vi->rss_size % vi->nrxq) {
6886 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6887 		    "expect uneven traffic distribution.\n", vi->nrxq,
6888 		    vi->rss_size);
6889 	}
6890 #ifdef RSS
6891 	if (vi->nrxq != nbuckets) {
6892 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6893 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6894 	}
6895 #endif
6896 	if (vi->rss == NULL)
6897 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6898 		    M_ZERO | M_WAITOK);
6899 	for (i = 0; i < vi->rss_size;) {
6900 #ifdef RSS
6901 		j = rss_get_indirection_to_bucket(i);
6902 		j %= vi->nrxq;
6903 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6904 		vi->rss[i++] = rxq->iq.abs_id;
6905 #else
6906 		for_each_rxq(vi, j, rxq) {
6907 			vi->rss[i++] = rxq->iq.abs_id;
6908 			if (i == vi->rss_size)
6909 				break;
6910 		}
6911 #endif
6912 	}
6913 
6914 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6915 	    vi->rss, vi->rss_size);
6916 	if (rc != 0) {
6917 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6918 		return (rc);
6919 	}
6920 
6921 #ifdef RSS
6922 	vi->hashen = hashconfig_to_hashen(hashconfig);
6923 
6924 	/*
6925 	 * We may have had to enable some hashes even though the global config
6926 	 * wants them disabled.  This is a potential problem that must be
6927 	 * reported to the user.
6928 	 */
6929 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6930 
6931 	/*
6932 	 * If we consider only the supported hash types, then the enabled hashes
6933 	 * are a superset of the requested hashes.  In other words, there cannot
6934 	 * be any supported hash that was requested but not enabled, but there
6935 	 * can be hashes that were not requested but had to be enabled.
6936 	 */
6937 	extra &= SUPPORTED_RSS_HASHTYPES;
6938 	MPASS((extra & hashconfig) == 0);
6939 
6940 	if (extra) {
6941 		CH_ALERT(vi,
6942 		    "global RSS config (0x%x) cannot be accommodated.\n",
6943 		    hashconfig);
6944 	}
6945 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6946 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6947 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6948 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6949 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6950 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6951 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6952 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6953 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6954 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6955 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6956 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6957 #else
6958 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6959 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6960 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6961 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6962 #endif
6963 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6964 	    0, 0);
6965 	if (rc != 0) {
6966 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6967 		return (rc);
6968 	}
6969 
6970 	return (0);
6971 }
6972 
6973 int
6974 vi_init(struct vi_info *vi)
6975 {
6976 	int rc;
6977 
6978 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6979 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6980 	    ("%s: VI_INIT_DONE already", __func__));
6981 
6982 	rc = vi_full_init(vi);
6983 	if (rc != 0)
6984 		vi_full_uninit(vi);
6985 	else
6986 		vi->flags |= VI_INIT_DONE;
6987 
6988 	return (rc);
6989 }
6990 
6991 /*
6992  * Idempotent.
6993  */
6994 static void
6995 vi_full_uninit(struct vi_info *vi)
6996 {
6997 
6998 	if (vi->flags & VI_INIT_DONE) {
6999 		quiesce_vi(vi);
7000 		free(vi->rss, M_CXGBE);
7001 		free(vi->nm_rss, M_CXGBE);
7002 	}
7003 
7004 	t4_teardown_vi_queues(vi);
7005 	vi->flags &= ~VI_INIT_DONE;
7006 }
7007 
7008 static void
7009 quiesce_txq(struct sge_txq *txq)
7010 {
7011 	struct sge_eq *eq = &txq->eq;
7012 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7013 
7014 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7015 	MPASS(!(eq->flags & EQ_ENABLED));
7016 
7017 	/* Wait for the mp_ring to empty. */
7018 	while (!mp_ring_is_idle(txq->r)) {
7019 		mp_ring_check_drainage(txq->r, 4096);
7020 		pause("rquiesce", 1);
7021 	}
7022 	MPASS(txq->txp.npkt == 0);
7023 
7024 	if (eq->flags & EQ_HW_ALLOCATED) {
7025 		/*
7026 		 * Hardware is alive and working normally.  Wait for it to
7027 		 * finish and then wait for the driver to catch up and reclaim
7028 		 * all descriptors.
7029 		 */
7030 		while (spg->cidx != htobe16(eq->pidx))
7031 			pause("equiesce", 1);
7032 		while (eq->cidx != eq->pidx)
7033 			pause("dquiesce", 1);
7034 	} else {
7035 		/*
7036 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7037 		 * descriptors directly.
7038 		 */
7039 		TXQ_LOCK(txq);
7040 		while (eq->cidx != eq->pidx) {
7041 			struct mbuf *m, *nextpkt;
7042 			struct tx_sdesc *txsd;
7043 
7044 			txsd = &txq->sdesc[eq->cidx];
7045 			for (m = txsd->m; m != NULL; m = nextpkt) {
7046 				nextpkt = m->m_nextpkt;
7047 				m->m_nextpkt = NULL;
7048 				m_freem(m);
7049 			}
7050 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7051 		}
7052 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7053 		TXQ_UNLOCK(txq);
7054 	}
7055 }
7056 
7057 static void
7058 quiesce_wrq(struct sge_wrq *wrq)
7059 {
7060 	struct wrqe *wr;
7061 
7062 	TXQ_LOCK(wrq);
7063 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7064 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7065 #ifdef INVARIANTS
7066 		wrq->nwr_pending--;
7067 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7068 #endif
7069 		free(wr, M_CXGBE);
7070 	}
7071 	MPASS(wrq->nwr_pending == 0);
7072 	MPASS(wrq->ndesc_needed == 0);
7073 	wrq->nwr_pending = 0;
7074 	wrq->ndesc_needed = 0;
7075 	TXQ_UNLOCK(wrq);
7076 }
7077 
7078 static void
7079 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7080 {
7081 	/* Synchronize with the interrupt handler */
7082 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7083 		pause("iqfree", 1);
7084 
7085 	if (fl != NULL) {
7086 		MPASS(iq->flags & IQ_HAS_FL);
7087 
7088 		mtx_lock(&sc->sfl_lock);
7089 		FL_LOCK(fl);
7090 		fl->flags |= FL_DOOMED;
7091 		FL_UNLOCK(fl);
7092 		callout_stop(&sc->sfl_callout);
7093 		mtx_unlock(&sc->sfl_lock);
7094 
7095 		KASSERT((fl->flags & FL_STARVING) == 0,
7096 		    ("%s: still starving", __func__));
7097 
7098 		/* Release all buffers if hardware is no longer available. */
7099 		if (!(iq->flags & IQ_HW_ALLOCATED))
7100 			free_fl_buffers(sc, fl);
7101 	}
7102 }
7103 
7104 /*
7105  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7106  * that no new work is being enqueued by the hardware or the driver.  That part
7107  * should be arranged before calling this function.
7108  */
7109 static void
7110 quiesce_vi(struct vi_info *vi)
7111 {
7112 	int i;
7113 	struct adapter *sc = vi->adapter;
7114 	struct sge_rxq *rxq;
7115 	struct sge_txq *txq;
7116 #ifdef TCP_OFFLOAD
7117 	struct sge_ofld_rxq *ofld_rxq;
7118 #endif
7119 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7120 	struct sge_ofld_txq *ofld_txq;
7121 #endif
7122 
7123 	if (!(vi->flags & VI_INIT_DONE))
7124 		return;
7125 
7126 	for_each_txq(vi, i, txq) {
7127 		quiesce_txq(txq);
7128 	}
7129 
7130 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7131 	for_each_ofld_txq(vi, i, ofld_txq) {
7132 		quiesce_wrq(&ofld_txq->wrq);
7133 	}
7134 #endif
7135 
7136 	for_each_rxq(vi, i, rxq) {
7137 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7138 	}
7139 
7140 #ifdef TCP_OFFLOAD
7141 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7142 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7143 	}
7144 #endif
7145 }
7146 
7147 static int
7148 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7149     driver_intr_t *handler, void *arg, char *name)
7150 {
7151 	int rc;
7152 
7153 	irq->rid = rid;
7154 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7155 	    RF_SHAREABLE | RF_ACTIVE);
7156 	if (irq->res == NULL) {
7157 		device_printf(sc->dev,
7158 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7159 		return (ENOMEM);
7160 	}
7161 
7162 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7163 	    NULL, handler, arg, &irq->tag);
7164 	if (rc != 0) {
7165 		device_printf(sc->dev,
7166 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7167 		    rid, name, rc);
7168 	} else if (name)
7169 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7170 
7171 	return (rc);
7172 }
7173 
7174 static int
7175 t4_free_irq(struct adapter *sc, struct irq *irq)
7176 {
7177 	if (irq->tag)
7178 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7179 	if (irq->res)
7180 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7181 
7182 	bzero(irq, sizeof(*irq));
7183 
7184 	return (0);
7185 }
7186 
7187 static void
7188 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7189 {
7190 
7191 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7192 	t4_get_regs(sc, buf, regs->len);
7193 }
7194 
7195 #define	A_PL_INDIR_CMD	0x1f8
7196 
7197 #define	S_PL_AUTOINC	31
7198 #define	M_PL_AUTOINC	0x1U
7199 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7200 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7201 
7202 #define	S_PL_VFID	20
7203 #define	M_PL_VFID	0xffU
7204 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7205 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7206 
7207 #define	S_PL_ADDR	0
7208 #define	M_PL_ADDR	0xfffffU
7209 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7210 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7211 
7212 #define	A_PL_INDIR_DATA	0x1fc
7213 
7214 static uint64_t
7215 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7216 {
7217 	u32 stats[2];
7218 
7219 	if (sc->flags & IS_VF) {
7220 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7221 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7222 	} else {
7223 		mtx_assert(&sc->reg_lock, MA_OWNED);
7224 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7225 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7226 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7227 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7228 	}
7229 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7230 }
7231 
7232 static void
7233 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7234 {
7235 
7236 #define GET_STAT(name) \
7237 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7238 
7239 	if (!(sc->flags & IS_VF))
7240 		mtx_lock(&sc->reg_lock);
7241 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7242 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7243 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7244 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7245 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7246 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7247 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7248 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7249 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7250 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7251 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7252 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7253 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7254 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7255 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7256 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7257 	if (!(sc->flags & IS_VF))
7258 		mtx_unlock(&sc->reg_lock);
7259 
7260 #undef GET_STAT
7261 }
7262 
7263 static void
7264 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7265 {
7266 	int reg;
7267 
7268 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7269 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7270 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7271 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7272 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7273 }
7274 
7275 static void
7276 vi_refresh_stats(struct vi_info *vi)
7277 {
7278 	struct timeval tv;
7279 	const struct timeval interval = {0, 250000};	/* 250ms */
7280 
7281 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7282 
7283 	if (vi->flags & VI_SKIP_STATS)
7284 		return;
7285 
7286 	getmicrotime(&tv);
7287 	timevalsub(&tv, &interval);
7288 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7289 		return;
7290 
7291 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7292 	getmicrotime(&vi->last_refreshed);
7293 }
7294 
7295 static void
7296 cxgbe_refresh_stats(struct vi_info *vi)
7297 {
7298 	u_int i, v, tnl_cong_drops, chan_map;
7299 	struct timeval tv;
7300 	const struct timeval interval = {0, 250000};	/* 250ms */
7301 	struct port_info *pi;
7302 	struct adapter *sc;
7303 
7304 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7305 
7306 	if (vi->flags & VI_SKIP_STATS)
7307 		return;
7308 
7309 	getmicrotime(&tv);
7310 	timevalsub(&tv, &interval);
7311 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7312 		return;
7313 
7314 	pi = vi->pi;
7315 	sc = vi->adapter;
7316 	tnl_cong_drops = 0;
7317 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7318 	chan_map = pi->rx_e_chan_map;
7319 	while (chan_map) {
7320 		i = ffs(chan_map) - 1;
7321 		mtx_lock(&sc->reg_lock);
7322 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7323 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7324 		mtx_unlock(&sc->reg_lock);
7325 		tnl_cong_drops += v;
7326 		chan_map &= ~(1 << i);
7327 	}
7328 	pi->tnl_cong_drops = tnl_cong_drops;
7329 	getmicrotime(&vi->last_refreshed);
7330 }
7331 
7332 static void
7333 cxgbe_tick(void *arg)
7334 {
7335 	struct vi_info *vi = arg;
7336 
7337 	MPASS(IS_MAIN_VI(vi));
7338 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7339 
7340 	cxgbe_refresh_stats(vi);
7341 	callout_schedule(&vi->tick, hz);
7342 }
7343 
7344 static void
7345 vi_tick(void *arg)
7346 {
7347 	struct vi_info *vi = arg;
7348 
7349 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7350 
7351 	vi_refresh_stats(vi);
7352 	callout_schedule(&vi->tick, hz);
7353 }
7354 
7355 /*
7356  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7357  */
7358 static char *caps_decoder[] = {
7359 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7360 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7361 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7362 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7363 	    "\006HASHFILTER\007ETHOFLD",
7364 	"\20\001TOE",					/* 4: TOE */
7365 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7366 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7367 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7368 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7369 	    "\007T10DIF"
7370 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7371 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7372 	    "\004TLS_HW",
7373 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7374 		    "\004PO_INITIATOR\005PO_TARGET",
7375 };
7376 
7377 void
7378 t4_sysctls(struct adapter *sc)
7379 {
7380 	struct sysctl_ctx_list *ctx = &sc->ctx;
7381 	struct sysctl_oid *oid;
7382 	struct sysctl_oid_list *children, *c0;
7383 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7384 
7385 	/*
7386 	 * dev.t4nex.X.
7387 	 */
7388 	oid = device_get_sysctl_tree(sc->dev);
7389 	c0 = children = SYSCTL_CHILDREN(oid);
7390 
7391 	sc->sc_do_rxcopy = 1;
7392 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7393 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7394 
7395 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7396 	    sc->params.nports, "# of ports");
7397 
7398 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7399 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7400 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7401 	    "available doorbells");
7402 
7403 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7404 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7405 
7406 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7407 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7408 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7409 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7410 
7411 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7412 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7413 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7414 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7415 
7416 	t4_sge_sysctls(sc, ctx, children);
7417 
7418 	sc->lro_timeout = 100;
7419 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7420 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7421 
7422 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7423 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7424 
7425 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7426 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7427 
7428 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7429 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7430 
7431 	if (sc->flags & IS_VF)
7432 		return;
7433 
7434 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7435 	    NULL, chip_rev(sc), "chip hardware revision");
7436 
7437 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7438 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7439 
7440 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7441 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7442 
7443 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7444 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7445 
7446 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7447 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7448 
7449 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7450 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7451 
7452 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7453 	    sc->er_version, 0, "expansion ROM version");
7454 
7455 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7456 	    sc->bs_version, 0, "bootstrap firmware version");
7457 
7458 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7459 	    NULL, sc->params.scfg_vers, "serial config version");
7460 
7461 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7462 	    NULL, sc->params.vpd_vers, "VPD version");
7463 
7464 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7465 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7466 
7467 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7468 	    sc->cfcsum, "config file checksum");
7469 
7470 #define SYSCTL_CAP(name, n, text) \
7471 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7472 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7473 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7474 	    "available " text " capabilities")
7475 
7476 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7477 	SYSCTL_CAP(linkcaps, 1, "link");
7478 	SYSCTL_CAP(switchcaps, 2, "switch");
7479 	SYSCTL_CAP(niccaps, 3, "NIC");
7480 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7481 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7482 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7483 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7484 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7485 #undef SYSCTL_CAP
7486 
7487 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7488 	    NULL, sc->tids.nftids, "number of filters");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7491 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7492 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7493 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7494 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7495 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7496 
7497 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7498 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7499 	    sysctl_loadavg, "A",
7500 	    "microprocessor load averages (debug firmwares only)");
7501 
7502 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7503 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7504 	    "I", "core Vdd (in mV)");
7505 
7506 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7507 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7508 	    sysctl_cpus, "A", "local CPUs");
7509 
7510 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7511 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7512 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7513 
7514 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7515 	    &sc->swintr, 0, "software triggered interrupts");
7516 
7517 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7518 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7519 	    "1 = reset adapter, 0 = zero reset counter");
7520 
7521 	/*
7522 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7523 	 */
7524 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7525 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7526 	    "logs and miscellaneous information");
7527 	children = SYSCTL_CHILDREN(oid);
7528 
7529 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7530 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7531 	    sysctl_cctrl, "A", "congestion control");
7532 
7533 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7534 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7535 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7536 
7537 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7538 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7539 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7540 
7541 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7542 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7543 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7544 
7545 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7546 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7547 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7548 
7549 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7550 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7551 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7552 
7553 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7554 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7555 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7556 
7557 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7558 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7559 	    sysctl_cim_la, "A", "CIM logic analyzer");
7560 
7561 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7562 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7563 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7564 
7565 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7566 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7567 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7568 
7569 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7570 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7571 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7572 
7573 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7574 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7575 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7576 
7577 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7578 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7579 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7580 
7581 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7582 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7583 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7584 
7585 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7586 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7587 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7588 
7589 	if (chip_id(sc) > CHELSIO_T4) {
7590 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7591 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7592 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7593 		    "CIM OBQ 6 (SGE0-RX)");
7594 
7595 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7596 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7597 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7598 		    "CIM OBQ 7 (SGE1-RX)");
7599 	}
7600 
7601 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7602 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7603 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7604 
7605 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7606 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7608 
7609 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7610 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 	    sysctl_cpl_stats, "A", "CPL statistics");
7612 
7613 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7614 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7615 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7616 
7617 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7618 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7619 	    sysctl_tid_stats, "A", "tid stats");
7620 
7621 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7622 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7623 	    sysctl_devlog, "A", "firmware's device log");
7624 
7625 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7626 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7627 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7628 
7629 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7630 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7631 	    sysctl_hw_sched, "A", "hardware scheduler ");
7632 
7633 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7634 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7635 	    sysctl_l2t, "A", "hardware L2 table");
7636 
7637 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7638 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7639 	    sysctl_smt, "A", "hardware source MAC table");
7640 
7641 #ifdef INET6
7642 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7643 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7644 	    sysctl_clip, "A", "active CLIP table entries");
7645 #endif
7646 
7647 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7648 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7649 	    sysctl_lb_stats, "A", "loopback statistics");
7650 
7651 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7652 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7653 	    sysctl_meminfo, "A", "memory regions");
7654 
7655 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7656 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7657 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7658 	    "A", "MPS TCAM entries");
7659 
7660 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7661 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7662 	    sysctl_path_mtus, "A", "path MTUs");
7663 
7664 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7665 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7666 	    sysctl_pm_stats, "A", "PM statistics");
7667 
7668 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7669 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7670 	    sysctl_rdma_stats, "A", "RDMA statistics");
7671 
7672 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7673 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7674 	    sysctl_tcp_stats, "A", "TCP statistics");
7675 
7676 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7677 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7678 	    sysctl_tids, "A", "TID information");
7679 
7680 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7681 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7682 	    sysctl_tp_err_stats, "A", "TP error statistics");
7683 
7684 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7685 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7686 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7687 
7688 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7689 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7690 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7691 
7692 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7693 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7694 	    sysctl_tp_la, "A", "TP logic analyzer");
7695 
7696 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7697 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7698 	    sysctl_tx_rate, "A", "Tx rate");
7699 
7700 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7701 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7702 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7703 
7704 	if (chip_id(sc) >= CHELSIO_T5) {
7705 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7706 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7707 		    sysctl_wcwr_stats, "A", "write combined work requests");
7708 	}
7709 
7710 #ifdef KERN_TLS
7711 	if (is_ktls(sc)) {
7712 		/*
7713 		 * dev.t4nex.0.tls.
7714 		 */
7715 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7716 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7717 		children = SYSCTL_CHILDREN(oid);
7718 
7719 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7720 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7721 		    "keys in work requests (1) or attempt to store TLS keys "
7722 		    "in card memory.");
7723 
7724 		if (is_t6(sc))
7725 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7726 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7727 			    "combine TCB field updates with TLS record work "
7728 			    "requests.");
7729 	}
7730 #endif
7731 
7732 #ifdef TCP_OFFLOAD
7733 	if (is_offload(sc)) {
7734 		int i;
7735 		char s[4];
7736 
7737 		/*
7738 		 * dev.t4nex.X.toe.
7739 		 */
7740 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7741 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7742 		children = SYSCTL_CHILDREN(oid);
7743 
7744 		sc->tt.cong_algorithm = -1;
7745 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7746 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7747 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7748 		    "3 = highspeed)");
7749 
7750 		sc->tt.sndbuf = -1;
7751 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7752 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7753 
7754 		sc->tt.ddp = 0;
7755 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7756 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7757 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7758 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7759 
7760 		sc->tt.rx_coalesce = -1;
7761 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7762 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7763 
7764 		sc->tt.tls = 0;
7765 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7766 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7767 		    "Inline TLS allowed");
7768 
7769 		sc->tt.tx_align = -1;
7770 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7771 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7772 
7773 		sc->tt.tx_zcopy = 0;
7774 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7775 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7776 		    "Enable zero-copy aio_write(2)");
7777 
7778 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7779 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7780 		    "cop_managed_offloading", CTLFLAG_RW,
7781 		    &sc->tt.cop_managed_offloading, 0,
7782 		    "COP (Connection Offload Policy) controls all TOE offload");
7783 
7784 		sc->tt.autorcvbuf_inc = 16 * 1024;
7785 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7786 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7787 		    "autorcvbuf increment");
7788 
7789 		sc->tt.update_hc_on_pmtu_change = 1;
7790 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7791 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7792 		    &sc->tt.update_hc_on_pmtu_change, 0,
7793 		    "Update hostcache entry if the PMTU changes");
7794 
7795 		sc->tt.iso = 1;
7796 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7797 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7798 
7799 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7800 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7801 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7802 
7803 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7804 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7805 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7806 
7807 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7808 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7809 		    sysctl_tp_tick, "A", "DACK tick (us)");
7810 
7811 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7812 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7813 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7814 
7815 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7816 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7817 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7818 		    "Minimum retransmit interval (us)");
7819 
7820 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7821 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7822 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7823 		    "Maximum retransmit interval (us)");
7824 
7825 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7826 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7827 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7828 		    "Persist timer min (us)");
7829 
7830 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7831 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7832 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7833 		    "Persist timer max (us)");
7834 
7835 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7836 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7837 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7838 		    "Keepalive idle timer (us)");
7839 
7840 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7841 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7842 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7843 		    "Keepalive interval timer (us)");
7844 
7845 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7846 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7847 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7848 
7849 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7850 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7851 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7852 		    "FINWAIT2 timer (us)");
7853 
7854 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7855 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7856 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7857 		    "Number of SYN retransmissions before abort");
7858 
7859 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7860 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7861 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7862 		    "Number of retransmissions before abort");
7863 
7864 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7865 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7866 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7867 		    "Number of keepalive probes before abort");
7868 
7869 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7870 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7871 		    "TOE retransmit backoffs");
7872 		children = SYSCTL_CHILDREN(oid);
7873 		for (i = 0; i < 16; i++) {
7874 			snprintf(s, sizeof(s), "%u", i);
7875 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7876 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7877 			    i, sysctl_tp_backoff, "IU",
7878 			    "TOE retransmit backoff");
7879 		}
7880 	}
7881 #endif
7882 }
7883 
7884 void
7885 vi_sysctls(struct vi_info *vi)
7886 {
7887 	struct sysctl_ctx_list *ctx = &vi->ctx;
7888 	struct sysctl_oid *oid;
7889 	struct sysctl_oid_list *children;
7890 
7891 	/*
7892 	 * dev.v?(cxgbe|cxl).X.
7893 	 */
7894 	oid = device_get_sysctl_tree(vi->dev);
7895 	children = SYSCTL_CHILDREN(oid);
7896 
7897 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7898 	    vi->viid, "VI identifer");
7899 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7900 	    &vi->nrxq, 0, "# of rx queues");
7901 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7902 	    &vi->ntxq, 0, "# of tx queues");
7903 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7904 	    &vi->first_rxq, 0, "index of first rx queue");
7905 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7906 	    &vi->first_txq, 0, "index of first tx queue");
7907 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7908 	    vi->rss_base, "start of RSS indirection table");
7909 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7910 	    vi->rss_size, "size of RSS indirection table");
7911 
7912 	if (IS_MAIN_VI(vi)) {
7913 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7914 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7915 		    sysctl_noflowq, "IU",
7916 		    "Reserve queue 0 for non-flowid packets");
7917 	}
7918 
7919 	if (vi->adapter->flags & IS_VF) {
7920 		MPASS(vi->flags & TX_USES_VM_WR);
7921 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7922 		    NULL, 1, "use VM work requests for transmit");
7923 	} else {
7924 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7925 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7926 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7927 	}
7928 
7929 #ifdef TCP_OFFLOAD
7930 	if (vi->nofldrxq != 0) {
7931 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7932 		    &vi->nofldrxq, 0,
7933 		    "# of rx queues for offloaded TCP connections");
7934 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7935 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7936 		    "index of first TOE rx queue");
7937 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7938 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7939 		    sysctl_holdoff_tmr_idx_ofld, "I",
7940 		    "holdoff timer index for TOE queues");
7941 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7942 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7943 		    sysctl_holdoff_pktc_idx_ofld, "I",
7944 		    "holdoff packet counter index for TOE queues");
7945 	}
7946 #endif
7947 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7948 	if (vi->nofldtxq != 0) {
7949 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7950 		    &vi->nofldtxq, 0,
7951 		    "# of tx queues for TOE/ETHOFLD");
7952 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7953 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7954 		    "index of first TOE/ETHOFLD tx queue");
7955 	}
7956 #endif
7957 #ifdef DEV_NETMAP
7958 	if (vi->nnmrxq != 0) {
7959 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7960 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7961 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7962 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7963 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7964 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7965 		    "index of first netmap rx queue");
7966 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7967 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7968 		    "index of first netmap tx queue");
7969 	}
7970 #endif
7971 
7972 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7973 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7974 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7975 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7976 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7977 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7978 
7979 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7980 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7981 	    sysctl_qsize_rxq, "I", "rx queue size");
7982 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7983 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7984 	    sysctl_qsize_txq, "I", "tx queue size");
7985 }
7986 
7987 static void
7988 cxgbe_sysctls(struct port_info *pi)
7989 {
7990 	struct sysctl_ctx_list *ctx = &pi->ctx;
7991 	struct sysctl_oid *oid;
7992 	struct sysctl_oid_list *children, *children2;
7993 	struct adapter *sc = pi->adapter;
7994 	int i;
7995 	char name[16];
7996 	static char *tc_flags = {"\20\1USER"};
7997 
7998 	/*
7999 	 * dev.cxgbe.X.
8000 	 */
8001 	oid = device_get_sysctl_tree(pi->dev);
8002 	children = SYSCTL_CHILDREN(oid);
8003 
8004 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
8005 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8006 	    sysctl_linkdnrc, "A", "reason why link is down");
8007 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8008 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8009 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8010 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8011 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8012 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8013 		    sysctl_btphy, "I", "PHY firmware version");
8014 	}
8015 
8016 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8017 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8018 	    sysctl_pause_settings, "A",
8019 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8020 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8021 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8022 	    "FEC in use on the link");
8023 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8024 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8025 	    sysctl_requested_fec, "A",
8026 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8027 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8028 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8029 	    "FEC recommended by the cable/transceiver");
8030 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8031 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8032 	    sysctl_autoneg, "I",
8033 	    "autonegotiation (-1 = not supported)");
8034 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8035 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8036 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8037 
8038 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8039 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8040 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8041 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8042 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8043 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8044 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8045 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8046 
8047 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8048 	    port_top_speed(pi), "max speed (in Gbps)");
8049 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8050 	    pi->mps_bg_map, "MPS buffer group map");
8051 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8052 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8053 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8054 	    pi->tx_chan, "TP tx c-channel");
8055 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8056 	    pi->rx_chan, "TP rx c-channel");
8057 
8058 	if (sc->flags & IS_VF)
8059 		return;
8060 
8061 	/*
8062 	 * dev.(cxgbe|cxl).X.tc.
8063 	 */
8064 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8065 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8066 	    "Tx scheduler traffic classes (cl_rl)");
8067 	children2 = SYSCTL_CHILDREN(oid);
8068 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8069 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8070 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8071 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8072 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8073 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8074 	for (i = 0; i < sc->params.nsched_cls; i++) {
8075 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8076 
8077 		snprintf(name, sizeof(name), "%d", i);
8078 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8079 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8080 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8081 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8082 		    CTLFLAG_RD, &tc->state, 0, "current state");
8083 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8084 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8085 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8086 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8087 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8088 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8089 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8090 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8091 		    "traffic class parameters");
8092 	}
8093 
8094 	/*
8095 	 * dev.cxgbe.X.stats.
8096 	 */
8097 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8098 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8099 	children = SYSCTL_CHILDREN(oid);
8100 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8101 	    &pi->tx_parse_error, 0,
8102 	    "# of tx packets with invalid length or # of segments");
8103 
8104 #define T4_REGSTAT(name, stat, desc) \
8105     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8106 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8107 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8108         sysctl_handle_t4_reg64, "QU", desc)
8109 
8110 /* We get these from port_stats and they may be stale by up to 1s */
8111 #define T4_PORTSTAT(name, desc) \
8112 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8113 	    &pi->stats.name, desc)
8114 
8115 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8116 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8117 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8118 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8119 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8120 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8121 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8122 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8123 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8124 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8125 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8126 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8127 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8128 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8129 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8130 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8131 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8132 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8133 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8134 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8135 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8136 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8137 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8138 
8139 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8140 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8141 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8142 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8143 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8144 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8145 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8146 	if (is_t6(sc)) {
8147 		T4_PORTSTAT(rx_fcs_err,
8148 		    "# of frames received with bad FCS since last link up");
8149 	} else {
8150 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8151 		    "# of frames received with bad FCS");
8152 	}
8153 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8154 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8155 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8156 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8157 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8158 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8159 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8160 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8161 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8162 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8163 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8164 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8165 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8166 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8167 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8168 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8169 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8170 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8171 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8172 
8173 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8174 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8175 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8176 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8177 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8178 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8179 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8180 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8181 
8182 #undef T4_REGSTAT
8183 #undef T4_PORTSTAT
8184 }
8185 
8186 static int
8187 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8188 {
8189 	int rc, *i, space = 0;
8190 	struct sbuf sb;
8191 
8192 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8193 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8194 		if (space)
8195 			sbuf_printf(&sb, " ");
8196 		sbuf_printf(&sb, "%d", *i);
8197 		space = 1;
8198 	}
8199 	rc = sbuf_finish(&sb);
8200 	sbuf_delete(&sb);
8201 	return (rc);
8202 }
8203 
8204 static int
8205 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8206 {
8207 	int rc;
8208 	struct sbuf *sb;
8209 
8210 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8211 	if (sb == NULL)
8212 		return (ENOMEM);
8213 
8214 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8215 	rc = sbuf_finish(sb);
8216 	sbuf_delete(sb);
8217 
8218 	return (rc);
8219 }
8220 
8221 static int
8222 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8223 {
8224 	int rc;
8225 	struct sbuf *sb;
8226 
8227 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8228 	if (sb == NULL)
8229 		return (ENOMEM);
8230 
8231 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8232 	rc = sbuf_finish(sb);
8233 	sbuf_delete(sb);
8234 
8235 	return (rc);
8236 }
8237 
8238 static int
8239 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8240 {
8241 	struct port_info *pi = arg1;
8242 	int op = arg2;
8243 	struct adapter *sc = pi->adapter;
8244 	u_int v;
8245 	int rc;
8246 
8247 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8248 	if (rc)
8249 		return (rc);
8250 	if (hw_off_limits(sc))
8251 		rc = ENXIO;
8252 	else {
8253 		/* XXX: magic numbers */
8254 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8255 		    op ? 0x20 : 0xc820, &v);
8256 	}
8257 	end_synchronized_op(sc, 0);
8258 	if (rc)
8259 		return (rc);
8260 	if (op == 0)
8261 		v /= 256;
8262 
8263 	rc = sysctl_handle_int(oidp, &v, 0, req);
8264 	return (rc);
8265 }
8266 
8267 static int
8268 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8269 {
8270 	struct vi_info *vi = arg1;
8271 	int rc, val;
8272 
8273 	val = vi->rsrv_noflowq;
8274 	rc = sysctl_handle_int(oidp, &val, 0, req);
8275 	if (rc != 0 || req->newptr == NULL)
8276 		return (rc);
8277 
8278 	if ((val >= 1) && (vi->ntxq > 1))
8279 		vi->rsrv_noflowq = 1;
8280 	else
8281 		vi->rsrv_noflowq = 0;
8282 
8283 	return (rc);
8284 }
8285 
8286 static int
8287 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8288 {
8289 	struct vi_info *vi = arg1;
8290 	struct adapter *sc = vi->adapter;
8291 	int rc, val, i;
8292 
8293 	MPASS(!(sc->flags & IS_VF));
8294 
8295 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8296 	rc = sysctl_handle_int(oidp, &val, 0, req);
8297 	if (rc != 0 || req->newptr == NULL)
8298 		return (rc);
8299 
8300 	if (val != 0 && val != 1)
8301 		return (EINVAL);
8302 
8303 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8304 	    "t4txvm");
8305 	if (rc)
8306 		return (rc);
8307 	if (hw_off_limits(sc))
8308 		rc = ENXIO;
8309 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8310 		/*
8311 		 * We don't want parse_pkt to run with one setting (VF or PF)
8312 		 * and then eth_tx to see a different setting but still use
8313 		 * stale information calculated by parse_pkt.
8314 		 */
8315 		rc = EBUSY;
8316 	} else {
8317 		struct port_info *pi = vi->pi;
8318 		struct sge_txq *txq;
8319 		uint32_t ctrl0;
8320 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8321 
8322 		if (val) {
8323 			vi->flags |= TX_USES_VM_WR;
8324 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8325 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8326 			    V_TXPKT_INTF(pi->tx_chan));
8327 			if (!(sc->flags & IS_VF))
8328 				npkt--;
8329 		} else {
8330 			vi->flags &= ~TX_USES_VM_WR;
8331 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8332 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8333 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8334 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8335 		}
8336 		for_each_txq(vi, i, txq) {
8337 			txq->cpl_ctrl0 = ctrl0;
8338 			txq->txp.max_npkt = npkt;
8339 		}
8340 	}
8341 	end_synchronized_op(sc, LOCK_HELD);
8342 	return (rc);
8343 }
8344 
8345 static int
8346 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8347 {
8348 	struct vi_info *vi = arg1;
8349 	struct adapter *sc = vi->adapter;
8350 	int idx, rc, i;
8351 	struct sge_rxq *rxq;
8352 	uint8_t v;
8353 
8354 	idx = vi->tmr_idx;
8355 
8356 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8357 	if (rc != 0 || req->newptr == NULL)
8358 		return (rc);
8359 
8360 	if (idx < 0 || idx >= SGE_NTIMERS)
8361 		return (EINVAL);
8362 
8363 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8364 	    "t4tmr");
8365 	if (rc)
8366 		return (rc);
8367 
8368 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8369 	for_each_rxq(vi, i, rxq) {
8370 #ifdef atomic_store_rel_8
8371 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8372 #else
8373 		rxq->iq.intr_params = v;
8374 #endif
8375 	}
8376 	vi->tmr_idx = idx;
8377 
8378 	end_synchronized_op(sc, LOCK_HELD);
8379 	return (0);
8380 }
8381 
8382 static int
8383 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8384 {
8385 	struct vi_info *vi = arg1;
8386 	struct adapter *sc = vi->adapter;
8387 	int idx, rc;
8388 
8389 	idx = vi->pktc_idx;
8390 
8391 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8392 	if (rc != 0 || req->newptr == NULL)
8393 		return (rc);
8394 
8395 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8396 		return (EINVAL);
8397 
8398 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8399 	    "t4pktc");
8400 	if (rc)
8401 		return (rc);
8402 
8403 	if (vi->flags & VI_INIT_DONE)
8404 		rc = EBUSY; /* cannot be changed once the queues are created */
8405 	else
8406 		vi->pktc_idx = idx;
8407 
8408 	end_synchronized_op(sc, LOCK_HELD);
8409 	return (rc);
8410 }
8411 
8412 static int
8413 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8414 {
8415 	struct vi_info *vi = arg1;
8416 	struct adapter *sc = vi->adapter;
8417 	int qsize, rc;
8418 
8419 	qsize = vi->qsize_rxq;
8420 
8421 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8422 	if (rc != 0 || req->newptr == NULL)
8423 		return (rc);
8424 
8425 	if (qsize < 128 || (qsize & 7))
8426 		return (EINVAL);
8427 
8428 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8429 	    "t4rxqs");
8430 	if (rc)
8431 		return (rc);
8432 
8433 	if (vi->flags & VI_INIT_DONE)
8434 		rc = EBUSY; /* cannot be changed once the queues are created */
8435 	else
8436 		vi->qsize_rxq = qsize;
8437 
8438 	end_synchronized_op(sc, LOCK_HELD);
8439 	return (rc);
8440 }
8441 
8442 static int
8443 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8444 {
8445 	struct vi_info *vi = arg1;
8446 	struct adapter *sc = vi->adapter;
8447 	int qsize, rc;
8448 
8449 	qsize = vi->qsize_txq;
8450 
8451 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8452 	if (rc != 0 || req->newptr == NULL)
8453 		return (rc);
8454 
8455 	if (qsize < 128 || qsize > 65536)
8456 		return (EINVAL);
8457 
8458 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8459 	    "t4txqs");
8460 	if (rc)
8461 		return (rc);
8462 
8463 	if (vi->flags & VI_INIT_DONE)
8464 		rc = EBUSY; /* cannot be changed once the queues are created */
8465 	else
8466 		vi->qsize_txq = qsize;
8467 
8468 	end_synchronized_op(sc, LOCK_HELD);
8469 	return (rc);
8470 }
8471 
8472 static int
8473 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8474 {
8475 	struct port_info *pi = arg1;
8476 	struct adapter *sc = pi->adapter;
8477 	struct link_config *lc = &pi->link_cfg;
8478 	int rc;
8479 
8480 	if (req->newptr == NULL) {
8481 		struct sbuf *sb;
8482 		static char *bits = "\20\1RX\2TX\3AUTO";
8483 
8484 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8485 		if (sb == NULL)
8486 			return (ENOMEM);
8487 
8488 		if (lc->link_ok) {
8489 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8490 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8491 		} else {
8492 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8493 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8494 		}
8495 		rc = sbuf_finish(sb);
8496 		sbuf_delete(sb);
8497 	} else {
8498 		char s[2];
8499 		int n;
8500 
8501 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8502 		    PAUSE_AUTONEG));
8503 		s[1] = 0;
8504 
8505 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8506 		if (rc != 0)
8507 			return(rc);
8508 
8509 		if (s[1] != 0)
8510 			return (EINVAL);
8511 		if (s[0] < '0' || s[0] > '9')
8512 			return (EINVAL);	/* not a number */
8513 		n = s[0] - '0';
8514 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8515 			return (EINVAL);	/* some other bit is set too */
8516 
8517 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8518 		    "t4PAUSE");
8519 		if (rc)
8520 			return (rc);
8521 		if (!hw_off_limits(sc)) {
8522 			PORT_LOCK(pi);
8523 			lc->requested_fc = n;
8524 			fixup_link_config(pi);
8525 			if (pi->up_vis > 0)
8526 				rc = apply_link_config(pi);
8527 			set_current_media(pi);
8528 			PORT_UNLOCK(pi);
8529 		}
8530 		end_synchronized_op(sc, 0);
8531 	}
8532 
8533 	return (rc);
8534 }
8535 
8536 static int
8537 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8538 {
8539 	struct port_info *pi = arg1;
8540 	struct link_config *lc = &pi->link_cfg;
8541 	int rc;
8542 	struct sbuf *sb;
8543 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8544 
8545 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8546 	if (sb == NULL)
8547 		return (ENOMEM);
8548 	if (lc->link_ok)
8549 		sbuf_printf(sb, "%b", lc->fec, bits);
8550 	else
8551 		sbuf_printf(sb, "no link");
8552 	rc = sbuf_finish(sb);
8553 	sbuf_delete(sb);
8554 
8555 	return (rc);
8556 }
8557 
8558 static int
8559 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8560 {
8561 	struct port_info *pi = arg1;
8562 	struct adapter *sc = pi->adapter;
8563 	struct link_config *lc = &pi->link_cfg;
8564 	int rc;
8565 	int8_t old;
8566 
8567 	if (req->newptr == NULL) {
8568 		struct sbuf *sb;
8569 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8570 		    "\5RSVD3\6auto\7module";
8571 
8572 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8573 		if (sb == NULL)
8574 			return (ENOMEM);
8575 
8576 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8577 		rc = sbuf_finish(sb);
8578 		sbuf_delete(sb);
8579 	} else {
8580 		char s[8];
8581 		int n;
8582 
8583 		snprintf(s, sizeof(s), "%d",
8584 		    lc->requested_fec == FEC_AUTO ? -1 :
8585 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8586 
8587 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8588 		if (rc != 0)
8589 			return(rc);
8590 
8591 		n = strtol(&s[0], NULL, 0);
8592 		if (n < 0 || n & FEC_AUTO)
8593 			n = FEC_AUTO;
8594 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8595 			return (EINVAL);/* some other bit is set too */
8596 
8597 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8598 		    "t4reqf");
8599 		if (rc)
8600 			return (rc);
8601 		PORT_LOCK(pi);
8602 		old = lc->requested_fec;
8603 		if (n == FEC_AUTO)
8604 			lc->requested_fec = FEC_AUTO;
8605 		else if (n == 0 || n == FEC_NONE)
8606 			lc->requested_fec = FEC_NONE;
8607 		else {
8608 			if ((lc->pcaps |
8609 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8610 			    lc->pcaps) {
8611 				rc = ENOTSUP;
8612 				goto done;
8613 			}
8614 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8615 			    FEC_MODULE);
8616 		}
8617 		if (!hw_off_limits(sc)) {
8618 			fixup_link_config(pi);
8619 			if (pi->up_vis > 0) {
8620 				rc = apply_link_config(pi);
8621 				if (rc != 0) {
8622 					lc->requested_fec = old;
8623 					if (rc == FW_EPROTO)
8624 						rc = ENOTSUP;
8625 				}
8626 			}
8627 		}
8628 done:
8629 		PORT_UNLOCK(pi);
8630 		end_synchronized_op(sc, 0);
8631 	}
8632 
8633 	return (rc);
8634 }
8635 
8636 static int
8637 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8638 {
8639 	struct port_info *pi = arg1;
8640 	struct adapter *sc = pi->adapter;
8641 	struct link_config *lc = &pi->link_cfg;
8642 	int rc;
8643 	int8_t fec;
8644 	struct sbuf *sb;
8645 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8646 
8647 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8648 	if (sb == NULL)
8649 		return (ENOMEM);
8650 
8651 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8652 		rc = EBUSY;
8653 		goto done;
8654 	}
8655 	if (hw_off_limits(sc)) {
8656 		rc = ENXIO;
8657 		goto done;
8658 	}
8659 	PORT_LOCK(pi);
8660 	if (pi->up_vis == 0) {
8661 		/*
8662 		 * If all the interfaces are administratively down the firmware
8663 		 * does not report transceiver changes.  Refresh port info here.
8664 		 * This is the only reason we have a synchronized op in this
8665 		 * function.  Just PORT_LOCK would have been enough otherwise.
8666 		 */
8667 		t4_update_port_info(pi);
8668 	}
8669 
8670 	fec = lc->fec_hint;
8671 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8672 	    !fec_supported(lc->pcaps)) {
8673 		PORT_UNLOCK(pi);
8674 		sbuf_printf(sb, "n/a");
8675 	} else {
8676 		if (fec == 0)
8677 			fec = FEC_NONE;
8678 		PORT_UNLOCK(pi);
8679 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8680 	}
8681 	rc = sbuf_finish(sb);
8682 done:
8683 	sbuf_delete(sb);
8684 	end_synchronized_op(sc, 0);
8685 
8686 	return (rc);
8687 }
8688 
8689 static int
8690 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8691 {
8692 	struct port_info *pi = arg1;
8693 	struct adapter *sc = pi->adapter;
8694 	struct link_config *lc = &pi->link_cfg;
8695 	int rc, val;
8696 
8697 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8698 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8699 	else
8700 		val = -1;
8701 	rc = sysctl_handle_int(oidp, &val, 0, req);
8702 	if (rc != 0 || req->newptr == NULL)
8703 		return (rc);
8704 	if (val == 0)
8705 		val = AUTONEG_DISABLE;
8706 	else if (val == 1)
8707 		val = AUTONEG_ENABLE;
8708 	else
8709 		val = AUTONEG_AUTO;
8710 
8711 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8712 	    "t4aneg");
8713 	if (rc)
8714 		return (rc);
8715 	PORT_LOCK(pi);
8716 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8717 		rc = ENOTSUP;
8718 		goto done;
8719 	}
8720 	lc->requested_aneg = val;
8721 	if (!hw_off_limits(sc)) {
8722 		fixup_link_config(pi);
8723 		if (pi->up_vis > 0)
8724 			rc = apply_link_config(pi);
8725 		set_current_media(pi);
8726 	}
8727 done:
8728 	PORT_UNLOCK(pi);
8729 	end_synchronized_op(sc, 0);
8730 	return (rc);
8731 }
8732 
8733 static int
8734 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8735 {
8736 	struct port_info *pi = arg1;
8737 	struct adapter *sc = pi->adapter;
8738 	struct link_config *lc = &pi->link_cfg;
8739 	int rc, val;
8740 
8741 	val = lc->force_fec;
8742 	MPASS(val >= -1 && val <= 1);
8743 	rc = sysctl_handle_int(oidp, &val, 0, req);
8744 	if (rc != 0 || req->newptr == NULL)
8745 		return (rc);
8746 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8747 		return (ENOTSUP);
8748 	if (val < -1 || val > 1)
8749 		return (EINVAL);
8750 
8751 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8752 	if (rc)
8753 		return (rc);
8754 	PORT_LOCK(pi);
8755 	lc->force_fec = val;
8756 	if (!hw_off_limits(sc)) {
8757 		fixup_link_config(pi);
8758 		if (pi->up_vis > 0)
8759 			rc = apply_link_config(pi);
8760 	}
8761 	PORT_UNLOCK(pi);
8762 	end_synchronized_op(sc, 0);
8763 	return (rc);
8764 }
8765 
8766 static int
8767 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8768 {
8769 	struct adapter *sc = arg1;
8770 	int rc, reg = arg2;
8771 	uint64_t val;
8772 
8773 	mtx_lock(&sc->reg_lock);
8774 	if (hw_off_limits(sc))
8775 		rc = ENXIO;
8776 	else {
8777 		rc = 0;
8778 		val = t4_read_reg64(sc, reg);
8779 	}
8780 	mtx_unlock(&sc->reg_lock);
8781 	if (rc == 0)
8782 		rc = sysctl_handle_64(oidp, &val, 0, req);
8783 	return (rc);
8784 }
8785 
8786 static int
8787 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8788 {
8789 	struct adapter *sc = arg1;
8790 	int rc, t;
8791 	uint32_t param, val;
8792 
8793 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8794 	if (rc)
8795 		return (rc);
8796 	if (hw_off_limits(sc))
8797 		rc = ENXIO;
8798 	else {
8799 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8800 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8801 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8802 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8803 	}
8804 	end_synchronized_op(sc, 0);
8805 	if (rc)
8806 		return (rc);
8807 
8808 	/* unknown is returned as 0 but we display -1 in that case */
8809 	t = val == 0 ? -1 : val;
8810 
8811 	rc = sysctl_handle_int(oidp, &t, 0, req);
8812 	return (rc);
8813 }
8814 
8815 static int
8816 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8817 {
8818 	struct adapter *sc = arg1;
8819 	int rc;
8820 	uint32_t param, val;
8821 
8822 	if (sc->params.core_vdd == 0) {
8823 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8824 		    "t4vdd");
8825 		if (rc)
8826 			return (rc);
8827 		if (hw_off_limits(sc))
8828 			rc = ENXIO;
8829 		else {
8830 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8831 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8832 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8833 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8834 			    &param, &val);
8835 		}
8836 		end_synchronized_op(sc, 0);
8837 		if (rc)
8838 			return (rc);
8839 		sc->params.core_vdd = val;
8840 	}
8841 
8842 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8843 }
8844 
8845 static int
8846 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8847 {
8848 	struct adapter *sc = arg1;
8849 	int rc, v;
8850 	uint32_t param, val;
8851 
8852 	v = sc->sensor_resets;
8853 	rc = sysctl_handle_int(oidp, &v, 0, req);
8854 	if (rc != 0 || req->newptr == NULL || v <= 0)
8855 		return (rc);
8856 
8857 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8858 	    chip_id(sc) < CHELSIO_T5)
8859 		return (ENOTSUP);
8860 
8861 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8862 	if (rc)
8863 		return (rc);
8864 	if (hw_off_limits(sc))
8865 		rc = ENXIO;
8866 	else {
8867 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8868 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8869 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8870 		val = 1;
8871 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8872 	}
8873 	end_synchronized_op(sc, 0);
8874 	if (rc == 0)
8875 		sc->sensor_resets++;
8876 	return (rc);
8877 }
8878 
8879 static int
8880 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8881 {
8882 	struct adapter *sc = arg1;
8883 	struct sbuf *sb;
8884 	int rc;
8885 	uint32_t param, val;
8886 
8887 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8888 	if (rc)
8889 		return (rc);
8890 	if (hw_off_limits(sc))
8891 		rc = ENXIO;
8892 	else {
8893 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8894 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8895 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8896 	}
8897 	end_synchronized_op(sc, 0);
8898 	if (rc)
8899 		return (rc);
8900 
8901 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8902 	if (sb == NULL)
8903 		return (ENOMEM);
8904 
8905 	if (val == 0xffffffff) {
8906 		/* Only debug and custom firmwares report load averages. */
8907 		sbuf_printf(sb, "not available");
8908 	} else {
8909 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8910 		    (val >> 16) & 0xff);
8911 	}
8912 	rc = sbuf_finish(sb);
8913 	sbuf_delete(sb);
8914 
8915 	return (rc);
8916 }
8917 
8918 static int
8919 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8920 {
8921 	struct adapter *sc = arg1;
8922 	struct sbuf *sb;
8923 	int rc, i;
8924 	uint16_t incr[NMTUS][NCCTRL_WIN];
8925 	static const char *dec_fac[] = {
8926 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8927 		"0.9375"
8928 	};
8929 
8930 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8931 	if (sb == NULL)
8932 		return (ENOMEM);
8933 
8934 	rc = 0;
8935 	mtx_lock(&sc->reg_lock);
8936 	if (hw_off_limits(sc))
8937 		rc = ENXIO;
8938 	else
8939 		t4_read_cong_tbl(sc, incr);
8940 	mtx_unlock(&sc->reg_lock);
8941 	if (rc)
8942 		goto done;
8943 
8944 	for (i = 0; i < NCCTRL_WIN; ++i) {
8945 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8946 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8947 		    incr[5][i], incr[6][i], incr[7][i]);
8948 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8949 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8950 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8951 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8952 	}
8953 
8954 	rc = sbuf_finish(sb);
8955 done:
8956 	sbuf_delete(sb);
8957 	return (rc);
8958 }
8959 
8960 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8961 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8962 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8963 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8964 };
8965 
8966 static int
8967 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8968 {
8969 	struct adapter *sc = arg1;
8970 	struct sbuf *sb;
8971 	int rc, i, n, qid = arg2;
8972 	uint32_t *buf, *p;
8973 	char *qtype;
8974 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8975 
8976 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8977 	    ("%s: bad qid %d\n", __func__, qid));
8978 
8979 	if (qid < CIM_NUM_IBQ) {
8980 		/* inbound queue */
8981 		qtype = "IBQ";
8982 		n = 4 * CIM_IBQ_SIZE;
8983 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8984 		mtx_lock(&sc->reg_lock);
8985 		if (hw_off_limits(sc))
8986 			rc = -ENXIO;
8987 		else
8988 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8989 		mtx_unlock(&sc->reg_lock);
8990 	} else {
8991 		/* outbound queue */
8992 		qtype = "OBQ";
8993 		qid -= CIM_NUM_IBQ;
8994 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8995 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8996 		mtx_lock(&sc->reg_lock);
8997 		if (hw_off_limits(sc))
8998 			rc = -ENXIO;
8999 		else
9000 			rc = t4_read_cim_obq(sc, qid, buf, n);
9001 		mtx_unlock(&sc->reg_lock);
9002 	}
9003 
9004 	if (rc < 0) {
9005 		rc = -rc;
9006 		goto done;
9007 	}
9008 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9009 
9010 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9011 	if (sb == NULL) {
9012 		rc = ENOMEM;
9013 		goto done;
9014 	}
9015 
9016 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
9017 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9018 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9019 		    p[2], p[3]);
9020 
9021 	rc = sbuf_finish(sb);
9022 	sbuf_delete(sb);
9023 done:
9024 	free(buf, M_CXGBE);
9025 	return (rc);
9026 }
9027 
9028 static void
9029 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9030 {
9031 	uint32_t *p;
9032 
9033 	sbuf_printf(sb, "Status   Data      PC%s",
9034 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9035 	    "     LS0Stat  LS0Addr             LS0Data");
9036 
9037 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9038 		if (cfg & F_UPDBGLACAPTPCONLY) {
9039 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9040 			    p[6], p[7]);
9041 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9042 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9043 			    p[4] & 0xff, p[5] >> 8);
9044 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9045 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9046 			    p[1] & 0xf, p[2] >> 4);
9047 		} else {
9048 			sbuf_printf(sb,
9049 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9050 			    "%08x%08x%08x%08x",
9051 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9052 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9053 			    p[6], p[7]);
9054 		}
9055 	}
9056 }
9057 
9058 static void
9059 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9060 {
9061 	uint32_t *p;
9062 
9063 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9064 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9065 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9066 
9067 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9068 		if (cfg & F_UPDBGLACAPTPCONLY) {
9069 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9070 			    p[3] & 0xff, p[2], p[1], p[0]);
9071 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9072 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9073 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9074 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9075 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9076 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9077 			    p[6] >> 16);
9078 		} else {
9079 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9080 			    "%08x %08x %08x %08x %08x %08x",
9081 			    (p[9] >> 16) & 0xff,
9082 			    p[9] & 0xffff, p[8] >> 16,
9083 			    p[8] & 0xffff, p[7] >> 16,
9084 			    p[7] & 0xffff, p[6] >> 16,
9085 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9086 		}
9087 	}
9088 }
9089 
9090 static int
9091 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9092 {
9093 	uint32_t cfg, *buf;
9094 	int rc;
9095 
9096 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9097 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9098 	    M_ZERO | flags);
9099 	if (buf == NULL)
9100 		return (ENOMEM);
9101 
9102 	mtx_lock(&sc->reg_lock);
9103 	if (hw_off_limits(sc))
9104 		rc = ENXIO;
9105 	else {
9106 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9107 		if (rc == 0)
9108 			rc = -t4_cim_read_la(sc, buf, NULL);
9109 	}
9110 	mtx_unlock(&sc->reg_lock);
9111 	if (rc == 0) {
9112 		if (chip_id(sc) < CHELSIO_T6)
9113 			sbuf_cim_la4(sc, sb, buf, cfg);
9114 		else
9115 			sbuf_cim_la6(sc, sb, buf, cfg);
9116 	}
9117 	free(buf, M_CXGBE);
9118 	return (rc);
9119 }
9120 
9121 static int
9122 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9123 {
9124 	struct adapter *sc = arg1;
9125 	struct sbuf *sb;
9126 	int rc;
9127 
9128 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9129 	if (sb == NULL)
9130 		return (ENOMEM);
9131 
9132 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9133 	if (rc == 0)
9134 		rc = sbuf_finish(sb);
9135 	sbuf_delete(sb);
9136 	return (rc);
9137 }
9138 
9139 static void
9140 dump_cim_regs(struct adapter *sc)
9141 {
9142 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9143 	    device_get_nameunit(sc->dev),
9144 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9145 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9146 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9147 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9148 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9149 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9150 	    device_get_nameunit(sc->dev),
9151 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9152 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9153 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9154 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9155 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9156 }
9157 
9158 static void
9159 dump_cimla(struct adapter *sc)
9160 {
9161 	struct sbuf sb;
9162 	int rc;
9163 
9164 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9165 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9166 		    device_get_nameunit(sc->dev));
9167 		return;
9168 	}
9169 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9170 	if (rc == 0) {
9171 		rc = sbuf_finish(&sb);
9172 		if (rc == 0) {
9173 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9174 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9175 		}
9176 	}
9177 	sbuf_delete(&sb);
9178 }
9179 
9180 void
9181 t4_os_cim_err(struct adapter *sc)
9182 {
9183 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9184 }
9185 
9186 static int
9187 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9188 {
9189 	struct adapter *sc = arg1;
9190 	u_int i;
9191 	struct sbuf *sb;
9192 	uint32_t *buf, *p;
9193 	int rc;
9194 
9195 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9196 	if (sb == NULL)
9197 		return (ENOMEM);
9198 
9199 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9200 	    M_ZERO | M_WAITOK);
9201 
9202 	rc = 0;
9203 	mtx_lock(&sc->reg_lock);
9204 	if (hw_off_limits(sc))
9205 		rc = ENXIO;
9206 	else
9207 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9208 	mtx_unlock(&sc->reg_lock);
9209 	if (rc)
9210 		goto done;
9211 
9212 	p = buf;
9213 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9214 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9215 		    p[1], p[0]);
9216 	}
9217 
9218 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9219 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9220 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9221 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9222 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9223 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9224 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9225 		    p[0] & 1);
9226 	}
9227 	rc = sbuf_finish(sb);
9228 done:
9229 	sbuf_delete(sb);
9230 	free(buf, M_CXGBE);
9231 	return (rc);
9232 }
9233 
9234 static int
9235 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9236 {
9237 	struct adapter *sc = arg1;
9238 	u_int i;
9239 	struct sbuf *sb;
9240 	uint32_t *buf, *p;
9241 	int rc;
9242 
9243 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9244 	if (sb == NULL)
9245 		return (ENOMEM);
9246 
9247 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9248 	    M_ZERO | M_WAITOK);
9249 
9250 	rc = 0;
9251 	mtx_lock(&sc->reg_lock);
9252 	if (hw_off_limits(sc))
9253 		rc = ENXIO;
9254 	else
9255 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9256 	mtx_unlock(&sc->reg_lock);
9257 	if (rc)
9258 		goto done;
9259 
9260 	p = buf;
9261 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9262 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9263 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9264 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9265 		    p[4], p[3], p[2], p[1], p[0]);
9266 	}
9267 
9268 	sbuf_printf(sb, "\n\nCntl ID               Data");
9269 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9270 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9271 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9272 	}
9273 
9274 	rc = sbuf_finish(sb);
9275 done:
9276 	sbuf_delete(sb);
9277 	free(buf, M_CXGBE);
9278 	return (rc);
9279 }
9280 
9281 static int
9282 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9283 {
9284 	struct adapter *sc = arg1;
9285 	struct sbuf *sb;
9286 	int rc, i;
9287 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9288 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9289 	uint16_t thres[CIM_NUM_IBQ];
9290 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9291 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9292 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9293 
9294 	cim_num_obq = sc->chip_params->cim_num_obq;
9295 	if (is_t4(sc)) {
9296 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9297 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9298 	} else {
9299 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9300 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9301 	}
9302 	nq = CIM_NUM_IBQ + cim_num_obq;
9303 
9304 	mtx_lock(&sc->reg_lock);
9305 	if (hw_off_limits(sc))
9306 		rc = ENXIO;
9307 	else {
9308 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9309 		if (rc == 0) {
9310 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9311 			    obq_wr);
9312 			if (rc == 0)
9313 				t4_read_cimq_cfg(sc, base, size, thres);
9314 		}
9315 	}
9316 	mtx_unlock(&sc->reg_lock);
9317 	if (rc)
9318 		return (rc);
9319 
9320 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9321 	if (sb == NULL)
9322 		return (ENOMEM);
9323 
9324 	sbuf_printf(sb,
9325 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9326 
9327 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9328 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9329 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9330 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9331 		    G_QUEREMFLITS(p[2]) * 16);
9332 	for ( ; i < nq; i++, p += 4, wr += 2)
9333 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9334 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9335 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9336 		    G_QUEREMFLITS(p[2]) * 16);
9337 
9338 	rc = sbuf_finish(sb);
9339 	sbuf_delete(sb);
9340 
9341 	return (rc);
9342 }
9343 
9344 static int
9345 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9346 {
9347 	struct adapter *sc = arg1;
9348 	struct sbuf *sb;
9349 	int rc;
9350 	struct tp_cpl_stats stats;
9351 
9352 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9353 	if (sb == NULL)
9354 		return (ENOMEM);
9355 
9356 	rc = 0;
9357 	mtx_lock(&sc->reg_lock);
9358 	if (hw_off_limits(sc))
9359 		rc = ENXIO;
9360 	else
9361 		t4_tp_get_cpl_stats(sc, &stats, 0);
9362 	mtx_unlock(&sc->reg_lock);
9363 	if (rc)
9364 		goto done;
9365 
9366 	if (sc->chip_params->nchan > 2) {
9367 		sbuf_printf(sb, "                 channel 0  channel 1"
9368 		    "  channel 2  channel 3");
9369 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9370 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9371 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9372 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9373 	} else {
9374 		sbuf_printf(sb, "                 channel 0  channel 1");
9375 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9376 		    stats.req[0], stats.req[1]);
9377 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9378 		    stats.rsp[0], stats.rsp[1]);
9379 	}
9380 
9381 	rc = sbuf_finish(sb);
9382 done:
9383 	sbuf_delete(sb);
9384 	return (rc);
9385 }
9386 
9387 static int
9388 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9389 {
9390 	struct adapter *sc = arg1;
9391 	struct sbuf *sb;
9392 	int rc;
9393 	struct tp_usm_stats stats;
9394 
9395 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9396 	if (sb == NULL)
9397 		return (ENOMEM);
9398 
9399 	rc = 0;
9400 	mtx_lock(&sc->reg_lock);
9401 	if (hw_off_limits(sc))
9402 		rc = ENXIO;
9403 	else
9404 		t4_get_usm_stats(sc, &stats, 1);
9405 	mtx_unlock(&sc->reg_lock);
9406 	if (rc == 0) {
9407 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9408 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9409 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9410 		rc = sbuf_finish(sb);
9411 	}
9412 	sbuf_delete(sb);
9413 
9414 	return (rc);
9415 }
9416 
9417 static int
9418 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9419 {
9420 	struct adapter *sc = arg1;
9421 	struct sbuf *sb;
9422 	int rc;
9423 	struct tp_tid_stats stats;
9424 
9425 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9426 	if (sb == NULL)
9427 		return (ENOMEM);
9428 
9429 	rc = 0;
9430 	mtx_lock(&sc->reg_lock);
9431 	if (hw_off_limits(sc))
9432 		rc = ENXIO;
9433 	else
9434 		t4_tp_get_tid_stats(sc, &stats, 1);
9435 	mtx_unlock(&sc->reg_lock);
9436 	if (rc == 0) {
9437 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9438 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9439 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9440 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9441 		rc = sbuf_finish(sb);
9442 	}
9443 	sbuf_delete(sb);
9444 
9445 	return (rc);
9446 }
9447 
9448 static const char * const devlog_level_strings[] = {
9449 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9450 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9451 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9452 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9453 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9454 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9455 };
9456 
9457 static const char * const devlog_facility_strings[] = {
9458 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9459 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9460 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9461 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9462 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9463 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9464 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9465 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9466 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9467 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9468 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9469 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9470 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9471 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9472 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9473 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9474 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9475 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9476 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9477 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9478 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9479 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9480 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9481 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9482 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9483 };
9484 
9485 static int
9486 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9487 {
9488 	int i, j, rc, nentries, first = 0;
9489 	struct devlog_params *dparams = &sc->params.devlog;
9490 	struct fw_devlog_e *buf, *e;
9491 	uint64_t ftstamp = UINT64_MAX;
9492 
9493 	if (dparams->addr == 0)
9494 		return (ENXIO);
9495 
9496 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9497 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9498 	if (buf == NULL)
9499 		return (ENOMEM);
9500 
9501 	mtx_lock(&sc->reg_lock);
9502 	if (hw_off_limits(sc))
9503 		rc = ENXIO;
9504 	else
9505 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9506 		    dparams->size);
9507 	mtx_unlock(&sc->reg_lock);
9508 	if (rc != 0)
9509 		goto done;
9510 
9511 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9512 	for (i = 0; i < nentries; i++) {
9513 		e = &buf[i];
9514 
9515 		if (e->timestamp == 0)
9516 			break;	/* end */
9517 
9518 		e->timestamp = be64toh(e->timestamp);
9519 		e->seqno = be32toh(e->seqno);
9520 		for (j = 0; j < 8; j++)
9521 			e->params[j] = be32toh(e->params[j]);
9522 
9523 		if (e->timestamp < ftstamp) {
9524 			ftstamp = e->timestamp;
9525 			first = i;
9526 		}
9527 	}
9528 
9529 	if (buf[first].timestamp == 0)
9530 		goto done;	/* nothing in the log */
9531 
9532 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9533 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9534 
9535 	i = first;
9536 	do {
9537 		e = &buf[i];
9538 		if (e->timestamp == 0)
9539 			break;	/* end */
9540 
9541 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9542 		    e->seqno, e->timestamp,
9543 		    (e->level < nitems(devlog_level_strings) ?
9544 			devlog_level_strings[e->level] : "UNKNOWN"),
9545 		    (e->facility < nitems(devlog_facility_strings) ?
9546 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9547 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9548 		    e->params[2], e->params[3], e->params[4],
9549 		    e->params[5], e->params[6], e->params[7]);
9550 
9551 		if (++i == nentries)
9552 			i = 0;
9553 	} while (i != first);
9554 done:
9555 	free(buf, M_CXGBE);
9556 	return (rc);
9557 }
9558 
9559 static int
9560 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9561 {
9562 	struct adapter *sc = arg1;
9563 	int rc;
9564 	struct sbuf *sb;
9565 
9566 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9567 	if (sb == NULL)
9568 		return (ENOMEM);
9569 
9570 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9571 	if (rc == 0)
9572 		rc = sbuf_finish(sb);
9573 	sbuf_delete(sb);
9574 	return (rc);
9575 }
9576 
9577 static void
9578 dump_devlog(struct adapter *sc)
9579 {
9580 	int rc;
9581 	struct sbuf sb;
9582 
9583 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9584 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9585 		    device_get_nameunit(sc->dev));
9586 		return;
9587 	}
9588 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9589 	if (rc == 0) {
9590 		rc = sbuf_finish(&sb);
9591 		if (rc == 0) {
9592 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9593 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9594 		}
9595 	}
9596 	sbuf_delete(&sb);
9597 }
9598 
9599 static int
9600 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9601 {
9602 	struct adapter *sc = arg1;
9603 	struct sbuf *sb;
9604 	int rc;
9605 	struct tp_fcoe_stats stats[MAX_NCHAN];
9606 	int i, nchan = sc->chip_params->nchan;
9607 
9608 	rc = 0;
9609 	mtx_lock(&sc->reg_lock);
9610 	if (hw_off_limits(sc))
9611 		rc = ENXIO;
9612 	else {
9613 		for (i = 0; i < nchan; i++)
9614 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9615 	}
9616 	mtx_unlock(&sc->reg_lock);
9617 	if (rc != 0)
9618 		return (rc);
9619 
9620 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9621 	if (sb == NULL)
9622 		return (ENOMEM);
9623 
9624 	if (nchan > 2) {
9625 		sbuf_printf(sb, "                   channel 0        channel 1"
9626 		    "        channel 2        channel 3");
9627 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9628 		    stats[0].octets_ddp, stats[1].octets_ddp,
9629 		    stats[2].octets_ddp, stats[3].octets_ddp);
9630 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9631 		    stats[0].frames_ddp, stats[1].frames_ddp,
9632 		    stats[2].frames_ddp, stats[3].frames_ddp);
9633 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9634 		    stats[0].frames_drop, stats[1].frames_drop,
9635 		    stats[2].frames_drop, stats[3].frames_drop);
9636 	} else {
9637 		sbuf_printf(sb, "                   channel 0        channel 1");
9638 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9639 		    stats[0].octets_ddp, stats[1].octets_ddp);
9640 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9641 		    stats[0].frames_ddp, stats[1].frames_ddp);
9642 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9643 		    stats[0].frames_drop, stats[1].frames_drop);
9644 	}
9645 
9646 	rc = sbuf_finish(sb);
9647 	sbuf_delete(sb);
9648 
9649 	return (rc);
9650 }
9651 
9652 static int
9653 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9654 {
9655 	struct adapter *sc = arg1;
9656 	struct sbuf *sb;
9657 	int rc, i;
9658 	unsigned int map, kbps, ipg, mode;
9659 	unsigned int pace_tab[NTX_SCHED];
9660 
9661 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9662 	if (sb == NULL)
9663 		return (ENOMEM);
9664 
9665 	mtx_lock(&sc->reg_lock);
9666 	if (hw_off_limits(sc)) {
9667 		mtx_unlock(&sc->reg_lock);
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 	mtx_unlock(&sc->reg_lock);
9676 
9677 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9678 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9679 
9680 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9681 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9682 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9683 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9684 		if (kbps)
9685 			sbuf_printf(sb, "%9u     ", kbps);
9686 		else
9687 			sbuf_printf(sb, " disabled     ");
9688 
9689 		if (ipg)
9690 			sbuf_printf(sb, "%13u        ", ipg);
9691 		else
9692 			sbuf_printf(sb, "     disabled        ");
9693 
9694 		if (pace_tab[i])
9695 			sbuf_printf(sb, "%10u", pace_tab[i]);
9696 		else
9697 			sbuf_printf(sb, "  disabled");
9698 	}
9699 	rc = sbuf_finish(sb);
9700 done:
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 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9724 	if (sb == NULL)
9725 		return (ENOMEM);
9726 
9727 	memset(s, 0, sizeof(s));
9728 
9729 	rc = 0;
9730 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9731 		mtx_lock(&sc->reg_lock);
9732 		if (hw_off_limits(sc))
9733 			rc = ENXIO;
9734 		else {
9735 			t4_get_lb_stats(sc, i, &s[0]);
9736 			t4_get_lb_stats(sc, i + 1, &s[1]);
9737 		}
9738 		mtx_unlock(&sc->reg_lock);
9739 		if (rc != 0)
9740 			break;
9741 
9742 		p0 = &s[0].octets;
9743 		p1 = &s[1].octets;
9744 		sbuf_printf(sb, "%s                       Loopback %u"
9745 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9746 
9747 		for (j = 0; j < nitems(stat_name); j++)
9748 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9749 				   *p0++, *p1++);
9750 	}
9751 
9752 	if (rc == 0)
9753 		rc = sbuf_finish(sb);
9754 	sbuf_delete(sb);
9755 
9756 	return (rc);
9757 }
9758 
9759 static int
9760 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9761 {
9762 	int rc = 0;
9763 	struct port_info *pi = arg1;
9764 	struct link_config *lc = &pi->link_cfg;
9765 	struct sbuf *sb;
9766 
9767 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9768 	if (sb == NULL)
9769 		return (ENOMEM);
9770 
9771 	if (lc->link_ok || lc->link_down_rc == 255)
9772 		sbuf_printf(sb, "n/a");
9773 	else
9774 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9775 
9776 	rc = sbuf_finish(sb);
9777 	sbuf_delete(sb);
9778 
9779 	return (rc);
9780 }
9781 
9782 struct mem_desc {
9783 	u_int base;
9784 	u_int limit;
9785 	u_int idx;
9786 };
9787 
9788 static int
9789 mem_desc_cmp(const void *a, const void *b)
9790 {
9791 	const u_int v1 = ((const struct mem_desc *)a)->base;
9792 	const u_int v2 = ((const struct mem_desc *)b)->base;
9793 
9794 	if (v1 < v2)
9795 		return (-1);
9796 	else if (v1 > v2)
9797 		return (1);
9798 
9799 	return (0);
9800 }
9801 
9802 static void
9803 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9804     unsigned int to)
9805 {
9806 	unsigned int size;
9807 
9808 	if (from == to)
9809 		return;
9810 
9811 	size = to - from + 1;
9812 	if (size == 0)
9813 		return;
9814 
9815 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9816 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9817 }
9818 
9819 static int
9820 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9821 {
9822 	struct adapter *sc = arg1;
9823 	struct sbuf *sb;
9824 	int rc, i, n;
9825 	uint32_t lo, hi, used, free, alloc;
9826 	static const char *memory[] = {
9827 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9828 	};
9829 	static const char *region[] = {
9830 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9831 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9832 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9833 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9834 		"RQUDP region:", "PBL region:", "TXPBL region:",
9835 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9836 		"ULPTX state:", "On-chip queues:",
9837 	};
9838 	struct mem_desc avail[4];
9839 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9840 	struct mem_desc *md = mem;
9841 
9842 	rc = sysctl_wire_old_buffer(req, 0);
9843 	if (rc != 0)
9844 		return (rc);
9845 
9846 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9847 	if (sb == NULL)
9848 		return (ENOMEM);
9849 
9850 	for (i = 0; i < nitems(mem); i++) {
9851 		mem[i].limit = 0;
9852 		mem[i].idx = i;
9853 	}
9854 
9855 	mtx_lock(&sc->reg_lock);
9856 	if (hw_off_limits(sc)) {
9857 		rc = ENXIO;
9858 		goto done;
9859 	}
9860 
9861 	/* Find and sort the populated memory ranges */
9862 	i = 0;
9863 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9864 	if (lo & F_EDRAM0_ENABLE) {
9865 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9866 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9867 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9868 		avail[i].idx = 0;
9869 		i++;
9870 	}
9871 	if (lo & F_EDRAM1_ENABLE) {
9872 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9873 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9874 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9875 		avail[i].idx = 1;
9876 		i++;
9877 	}
9878 	if (lo & F_EXT_MEM_ENABLE) {
9879 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9880 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9881 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9882 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9883 		i++;
9884 	}
9885 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9886 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9887 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9888 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9889 		avail[i].idx = 4;
9890 		i++;
9891 	}
9892 	if (is_t6(sc) && lo & F_HMA_MUX) {
9893 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9894 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9895 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9896 		avail[i].idx = 5;
9897 		i++;
9898 	}
9899 	MPASS(i <= nitems(avail));
9900 	if (!i)                                    /* no memory available */
9901 		goto done;
9902 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9903 
9904 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9905 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9906 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9907 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9908 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9909 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9910 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9911 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9912 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9913 
9914 	/* the next few have explicit upper bounds */
9915 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9916 	md->limit = md->base - 1 +
9917 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9918 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9919 	md++;
9920 
9921 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9922 	md->limit = md->base - 1 +
9923 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9924 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9925 	md++;
9926 
9927 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9928 		if (chip_id(sc) <= CHELSIO_T5)
9929 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9930 		else
9931 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9932 		md->limit = 0;
9933 	} else {
9934 		md->base = 0;
9935 		md->idx = nitems(region);  /* hide it */
9936 	}
9937 	md++;
9938 
9939 #define ulp_region(reg) \
9940 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9941 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9942 
9943 	ulp_region(RX_ISCSI);
9944 	ulp_region(RX_TDDP);
9945 	ulp_region(TX_TPT);
9946 	ulp_region(RX_STAG);
9947 	ulp_region(RX_RQ);
9948 	ulp_region(RX_RQUDP);
9949 	ulp_region(RX_PBL);
9950 	ulp_region(TX_PBL);
9951 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9952 		ulp_region(RX_TLS_KEY);
9953 	}
9954 #undef ulp_region
9955 
9956 	md->base = 0;
9957 	if (is_t4(sc))
9958 		md->idx = nitems(region);
9959 	else {
9960 		uint32_t size = 0;
9961 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9962 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9963 
9964 		if (is_t5(sc)) {
9965 			if (sge_ctrl & F_VFIFO_ENABLE)
9966 				size = fifo_size << 2;
9967 		} else
9968 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9969 
9970 		if (size) {
9971 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9972 			md->limit = md->base + size - 1;
9973 		} else
9974 			md->idx = nitems(region);
9975 	}
9976 	md++;
9977 
9978 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9979 	md->limit = 0;
9980 	md++;
9981 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9982 	md->limit = 0;
9983 	md++;
9984 
9985 	md->base = sc->vres.ocq.start;
9986 	if (sc->vres.ocq.size)
9987 		md->limit = md->base + sc->vres.ocq.size - 1;
9988 	else
9989 		md->idx = nitems(region);  /* hide it */
9990 	md++;
9991 
9992 	/* add any address-space holes, there can be up to 3 */
9993 	for (n = 0; n < i - 1; n++)
9994 		if (avail[n].limit < avail[n + 1].base)
9995 			(md++)->base = avail[n].limit;
9996 	if (avail[n].limit)
9997 		(md++)->base = avail[n].limit;
9998 
9999 	n = md - mem;
10000 	MPASS(n <= nitems(mem));
10001 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
10002 
10003 	for (lo = 0; lo < i; lo++)
10004 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
10005 				avail[lo].limit - 1);
10006 
10007 	sbuf_printf(sb, "\n");
10008 	for (i = 0; i < n; i++) {
10009 		if (mem[i].idx >= nitems(region))
10010 			continue;                        /* skip holes */
10011 		if (!mem[i].limit)
10012 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10013 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10014 				mem[i].limit);
10015 	}
10016 
10017 	sbuf_printf(sb, "\n");
10018 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10019 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10020 	mem_region_show(sb, "uP RAM:", lo, hi);
10021 
10022 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10023 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10024 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10025 
10026 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10027 	for (i = 0, free = 0; i < 2; i++)
10028 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10029 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10030 		   G_PMRXMAXPAGE(lo), free,
10031 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10032 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10033 
10034 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10035 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10036 	for (i = 0, free = 0; i < 4; i++)
10037 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10038 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10039 		   G_PMTXMAXPAGE(lo), free,
10040 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10041 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10042 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10043 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10044 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10045 
10046 	for (i = 0; i < 4; i++) {
10047 		if (chip_id(sc) > CHELSIO_T5)
10048 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10049 		else
10050 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10051 		if (is_t5(sc)) {
10052 			used = G_T5_USED(lo);
10053 			alloc = G_T5_ALLOC(lo);
10054 		} else {
10055 			used = G_USED(lo);
10056 			alloc = G_ALLOC(lo);
10057 		}
10058 		/* For T6 these are MAC buffer groups */
10059 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10060 		    i, used, alloc);
10061 	}
10062 	for (i = 0; i < sc->chip_params->nchan; i++) {
10063 		if (chip_id(sc) > CHELSIO_T5)
10064 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10065 		else
10066 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10067 		if (is_t5(sc)) {
10068 			used = G_T5_USED(lo);
10069 			alloc = G_T5_ALLOC(lo);
10070 		} else {
10071 			used = G_USED(lo);
10072 			alloc = G_ALLOC(lo);
10073 		}
10074 		/* For T6 these are MAC buffer groups */
10075 		sbuf_printf(sb,
10076 		    "\nLoopback %d using %u pages out of %u allocated",
10077 		    i, used, alloc);
10078 	}
10079 done:
10080 	mtx_unlock(&sc->reg_lock);
10081 	if (rc == 0)
10082 		rc = sbuf_finish(sb);
10083 	sbuf_delete(sb);
10084 	return (rc);
10085 }
10086 
10087 static inline void
10088 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10089 {
10090 	*mask = x | y;
10091 	y = htobe64(y);
10092 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10093 }
10094 
10095 static int
10096 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10097 {
10098 	struct adapter *sc = arg1;
10099 	struct sbuf *sb;
10100 	int rc, i;
10101 
10102 	MPASS(chip_id(sc) <= CHELSIO_T5);
10103 
10104 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10105 	if (sb == NULL)
10106 		return (ENOMEM);
10107 
10108 	sbuf_printf(sb,
10109 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10110 	    "  VF              Replication             P0 P1 P2 P3  ML");
10111 	rc = 0;
10112 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10113 		uint64_t tcamx, tcamy, mask;
10114 		uint32_t cls_lo, cls_hi;
10115 		uint8_t addr[ETHER_ADDR_LEN];
10116 
10117 		mtx_lock(&sc->reg_lock);
10118 		if (hw_off_limits(sc))
10119 			rc = ENXIO;
10120 		else {
10121 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10122 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10123 		}
10124 		mtx_unlock(&sc->reg_lock);
10125 		if (rc != 0)
10126 			break;
10127 		if (tcamx & tcamy)
10128 			continue;
10129 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10130 		mtx_lock(&sc->reg_lock);
10131 		if (hw_off_limits(sc))
10132 			rc = ENXIO;
10133 		else {
10134 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10135 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10136 		}
10137 		mtx_unlock(&sc->reg_lock);
10138 		if (rc != 0)
10139 			break;
10140 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10141 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10142 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10143 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10144 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10145 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10146 
10147 		if (cls_lo & F_REPLICATE) {
10148 			struct fw_ldst_cmd ldst_cmd;
10149 
10150 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10151 			ldst_cmd.op_to_addrspace =
10152 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10153 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10154 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10155 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10156 			ldst_cmd.u.mps.rplc.fid_idx =
10157 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10158 				V_FW_LDST_CMD_IDX(i));
10159 
10160 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10161 			    "t4mps");
10162 			if (rc)
10163 				break;
10164 			if (hw_off_limits(sc))
10165 				rc = ENXIO;
10166 			else
10167 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10168 				    sizeof(ldst_cmd), &ldst_cmd);
10169 			end_synchronized_op(sc, 0);
10170 			if (rc != 0)
10171 				break;
10172 			else {
10173 				sbuf_printf(sb, " %08x %08x %08x %08x",
10174 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10175 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10176 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10177 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10178 			}
10179 		} else
10180 			sbuf_printf(sb, "%36s", "");
10181 
10182 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10183 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10184 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10185 	}
10186 
10187 	if (rc)
10188 		(void) sbuf_finish(sb);
10189 	else
10190 		rc = sbuf_finish(sb);
10191 	sbuf_delete(sb);
10192 
10193 	return (rc);
10194 }
10195 
10196 static int
10197 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10198 {
10199 	struct adapter *sc = arg1;
10200 	struct sbuf *sb;
10201 	int rc, i;
10202 
10203 	MPASS(chip_id(sc) > CHELSIO_T5);
10204 
10205 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10206 	if (sb == NULL)
10207 		return (ENOMEM);
10208 
10209 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10210 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10211 	    "                           Replication"
10212 	    "                                    P0 P1 P2 P3  ML\n");
10213 
10214 	rc = 0;
10215 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10216 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10217 		uint16_t ivlan;
10218 		uint64_t tcamx, tcamy, val, mask;
10219 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10220 		uint8_t addr[ETHER_ADDR_LEN];
10221 
10222 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10223 		if (i < 256)
10224 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10225 		else
10226 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10227 		mtx_lock(&sc->reg_lock);
10228 		if (hw_off_limits(sc))
10229 			rc = ENXIO;
10230 		else {
10231 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10232 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10233 			tcamy = G_DMACH(val) << 32;
10234 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10235 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10236 		}
10237 		mtx_unlock(&sc->reg_lock);
10238 		if (rc != 0)
10239 			break;
10240 
10241 		lookup_type = G_DATALKPTYPE(data2);
10242 		port_num = G_DATAPORTNUM(data2);
10243 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10244 			/* Inner header VNI */
10245 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10246 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10247 			dip_hit = data2 & F_DATADIPHIT;
10248 			vlan_vld = 0;
10249 		} else {
10250 			vniy = 0;
10251 			dip_hit = 0;
10252 			vlan_vld = data2 & F_DATAVIDH2;
10253 			ivlan = G_VIDL(val);
10254 		}
10255 
10256 		ctl |= V_CTLXYBITSEL(1);
10257 		mtx_lock(&sc->reg_lock);
10258 		if (hw_off_limits(sc))
10259 			rc = ENXIO;
10260 		else {
10261 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10262 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10263 			tcamx = G_DMACH(val) << 32;
10264 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10265 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10266 		}
10267 		mtx_unlock(&sc->reg_lock);
10268 		if (rc != 0)
10269 			break;
10270 
10271 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10272 			/* Inner header VNI mask */
10273 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10274 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10275 		} else
10276 			vnix = 0;
10277 
10278 		if (tcamx & tcamy)
10279 			continue;
10280 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10281 
10282 		mtx_lock(&sc->reg_lock);
10283 		if (hw_off_limits(sc))
10284 			rc = ENXIO;
10285 		else {
10286 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10287 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10288 		}
10289 		mtx_unlock(&sc->reg_lock);
10290 		if (rc != 0)
10291 			break;
10292 
10293 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10294 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10295 			    "%012jx %06x %06x    -    -   %3c"
10296 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10297 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10298 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10299 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10300 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10301 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10302 		} else {
10303 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10304 			    "%012jx    -       -   ", i, addr[0], addr[1],
10305 			    addr[2], addr[3], addr[4], addr[5],
10306 			    (uintmax_t)mask);
10307 
10308 			if (vlan_vld)
10309 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10310 			else
10311 				sbuf_printf(sb, "  -    N     ");
10312 
10313 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10314 			    lookup_type ? 'I' : 'O', port_num,
10315 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10316 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10317 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10318 		}
10319 
10320 
10321 		if (cls_lo & F_T6_REPLICATE) {
10322 			struct fw_ldst_cmd ldst_cmd;
10323 
10324 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10325 			ldst_cmd.op_to_addrspace =
10326 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10327 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10328 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10329 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10330 			ldst_cmd.u.mps.rplc.fid_idx =
10331 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10332 				V_FW_LDST_CMD_IDX(i));
10333 
10334 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10335 			    "t6mps");
10336 			if (rc)
10337 				break;
10338 			if (hw_off_limits(sc))
10339 				rc = ENXIO;
10340 			else
10341 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10342 				    sizeof(ldst_cmd), &ldst_cmd);
10343 			end_synchronized_op(sc, 0);
10344 			if (rc != 0)
10345 				break;
10346 			else {
10347 				sbuf_printf(sb, " %08x %08x %08x %08x"
10348 				    " %08x %08x %08x %08x",
10349 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10350 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10351 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10352 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10353 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10354 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10355 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10356 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10357 			}
10358 		} else
10359 			sbuf_printf(sb, "%72s", "");
10360 
10361 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10362 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10363 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10364 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10365 	}
10366 
10367 	if (rc)
10368 		(void) sbuf_finish(sb);
10369 	else
10370 		rc = sbuf_finish(sb);
10371 	sbuf_delete(sb);
10372 
10373 	return (rc);
10374 }
10375 
10376 static int
10377 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10378 {
10379 	struct adapter *sc = arg1;
10380 	struct sbuf *sb;
10381 	int rc;
10382 	uint16_t mtus[NMTUS];
10383 
10384 	rc = 0;
10385 	mtx_lock(&sc->reg_lock);
10386 	if (hw_off_limits(sc))
10387 		rc = ENXIO;
10388 	else
10389 		t4_read_mtu_tbl(sc, mtus, NULL);
10390 	mtx_unlock(&sc->reg_lock);
10391 	if (rc != 0)
10392 		return (rc);
10393 
10394 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10395 	if (sb == NULL)
10396 		return (ENOMEM);
10397 
10398 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10399 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10400 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10401 	    mtus[14], mtus[15]);
10402 
10403 	rc = sbuf_finish(sb);
10404 	sbuf_delete(sb);
10405 
10406 	return (rc);
10407 }
10408 
10409 static int
10410 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10411 {
10412 	struct adapter *sc = arg1;
10413 	struct sbuf *sb;
10414 	int rc, i;
10415 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10416 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10417 	static const char *tx_stats[MAX_PM_NSTATS] = {
10418 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10419 		"Tx FIFO wait", NULL, "Tx latency"
10420 	};
10421 	static const char *rx_stats[MAX_PM_NSTATS] = {
10422 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10423 		"Rx FIFO wait", NULL, "Rx latency"
10424 	};
10425 
10426 	rc = 0;
10427 	mtx_lock(&sc->reg_lock);
10428 	if (hw_off_limits(sc))
10429 		rc = ENXIO;
10430 	else {
10431 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10432 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10433 	}
10434 	mtx_unlock(&sc->reg_lock);
10435 	if (rc != 0)
10436 		return (rc);
10437 
10438 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10439 	if (sb == NULL)
10440 		return (ENOMEM);
10441 
10442 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10443 	for (i = 0; i < 4; i++) {
10444 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10445 		    tx_cyc[i]);
10446 	}
10447 
10448 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10449 	for (i = 0; i < 4; i++) {
10450 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10451 		    rx_cyc[i]);
10452 	}
10453 
10454 	if (chip_id(sc) > CHELSIO_T5) {
10455 		sbuf_printf(sb,
10456 		    "\n              Total wait      Total occupancy");
10457 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10458 		    tx_cyc[i]);
10459 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10460 		    rx_cyc[i]);
10461 
10462 		i += 2;
10463 		MPASS(i < nitems(tx_stats));
10464 
10465 		sbuf_printf(sb,
10466 		    "\n                   Reads           Total wait");
10467 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10468 		    tx_cyc[i]);
10469 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10470 		    rx_cyc[i]);
10471 	}
10472 
10473 	rc = sbuf_finish(sb);
10474 	sbuf_delete(sb);
10475 
10476 	return (rc);
10477 }
10478 
10479 static int
10480 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10481 {
10482 	struct adapter *sc = arg1;
10483 	struct sbuf *sb;
10484 	int rc;
10485 	struct tp_rdma_stats stats;
10486 
10487 	rc = 0;
10488 	mtx_lock(&sc->reg_lock);
10489 	if (hw_off_limits(sc))
10490 		rc = ENXIO;
10491 	else
10492 		t4_tp_get_rdma_stats(sc, &stats, 0);
10493 	mtx_unlock(&sc->reg_lock);
10494 	if (rc != 0)
10495 		return (rc);
10496 
10497 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10498 	if (sb == NULL)
10499 		return (ENOMEM);
10500 
10501 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10502 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10503 
10504 	rc = sbuf_finish(sb);
10505 	sbuf_delete(sb);
10506 
10507 	return (rc);
10508 }
10509 
10510 static int
10511 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10512 {
10513 	struct adapter *sc = arg1;
10514 	struct sbuf *sb;
10515 	int rc;
10516 	struct tp_tcp_stats v4, v6;
10517 
10518 	rc = 0;
10519 	mtx_lock(&sc->reg_lock);
10520 	if (hw_off_limits(sc))
10521 		rc = ENXIO;
10522 	else
10523 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10524 	mtx_unlock(&sc->reg_lock);
10525 	if (rc != 0)
10526 		return (rc);
10527 
10528 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10529 	if (sb == NULL)
10530 		return (ENOMEM);
10531 
10532 	sbuf_printf(sb,
10533 	    "                                IP                 IPv6\n");
10534 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10535 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10536 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10537 	    v4.tcp_in_segs, v6.tcp_in_segs);
10538 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10539 	    v4.tcp_out_segs, v6.tcp_out_segs);
10540 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10541 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10542 
10543 	rc = sbuf_finish(sb);
10544 	sbuf_delete(sb);
10545 
10546 	return (rc);
10547 }
10548 
10549 static int
10550 sysctl_tids(SYSCTL_HANDLER_ARGS)
10551 {
10552 	struct adapter *sc = arg1;
10553 	struct sbuf *sb;
10554 	int rc;
10555 	uint32_t x, y;
10556 	struct tid_info *t = &sc->tids;
10557 
10558 	rc = 0;
10559 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10560 	if (sb == NULL)
10561 		return (ENOMEM);
10562 
10563 	if (t->natids) {
10564 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10565 		    t->atids_in_use);
10566 	}
10567 
10568 	if (t->nhpftids) {
10569 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10570 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10571 	}
10572 
10573 	if (t->ntids) {
10574 		bool hashen = false;
10575 
10576 		mtx_lock(&sc->reg_lock);
10577 		if (hw_off_limits(sc))
10578 			rc = ENXIO;
10579 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10580 			hashen = true;
10581 			if (chip_id(sc) <= CHELSIO_T5) {
10582 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10583 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10584 			} else {
10585 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10586 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10587 			}
10588 		}
10589 		mtx_unlock(&sc->reg_lock);
10590 		if (rc != 0)
10591 			goto done;
10592 
10593 		sbuf_printf(sb, "TID range: ");
10594 		if (hashen) {
10595 			if (x)
10596 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10597 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10598 		} else {
10599 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10600 			    t->ntids - 1);
10601 		}
10602 		sbuf_printf(sb, ", in use: %u\n",
10603 		    atomic_load_acq_int(&t->tids_in_use));
10604 	}
10605 
10606 	if (t->nstids) {
10607 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10608 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10609 	}
10610 
10611 	if (t->nftids) {
10612 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10613 		    t->ftid_end, t->ftids_in_use);
10614 	}
10615 
10616 	if (t->netids) {
10617 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10618 		    t->etid_base + t->netids - 1, t->etids_in_use);
10619 	}
10620 
10621 	mtx_lock(&sc->reg_lock);
10622 	if (hw_off_limits(sc))
10623 		rc = ENXIO;
10624 	else {
10625 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10626 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10627 	}
10628 	mtx_unlock(&sc->reg_lock);
10629 	if (rc != 0)
10630 		goto done;
10631 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10632 done:
10633 	if (rc == 0)
10634 		rc = sbuf_finish(sb);
10635 	else
10636 		(void)sbuf_finish(sb);
10637 	sbuf_delete(sb);
10638 
10639 	return (rc);
10640 }
10641 
10642 static int
10643 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10644 {
10645 	struct adapter *sc = arg1;
10646 	struct sbuf *sb;
10647 	int rc;
10648 	struct tp_err_stats stats;
10649 
10650 	rc = 0;
10651 	mtx_lock(&sc->reg_lock);
10652 	if (hw_off_limits(sc))
10653 		rc = ENXIO;
10654 	else
10655 		t4_tp_get_err_stats(sc, &stats, 0);
10656 	mtx_unlock(&sc->reg_lock);
10657 	if (rc != 0)
10658 		return (rc);
10659 
10660 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10661 	if (sb == NULL)
10662 		return (ENOMEM);
10663 
10664 	if (sc->chip_params->nchan > 2) {
10665 		sbuf_printf(sb, "                 channel 0  channel 1"
10666 		    "  channel 2  channel 3\n");
10667 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10668 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10669 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10670 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10671 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10672 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10673 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10674 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10675 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10676 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10677 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10678 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10679 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10680 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10681 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10682 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10683 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10684 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10685 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10686 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10687 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10688 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10689 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10690 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10691 	} else {
10692 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10693 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10694 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10695 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10696 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10697 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10698 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10699 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10700 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10701 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10702 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10703 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10704 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10705 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10706 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10707 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10708 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10709 	}
10710 
10711 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10712 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10713 
10714 	rc = sbuf_finish(sb);
10715 	sbuf_delete(sb);
10716 
10717 	return (rc);
10718 }
10719 
10720 static int
10721 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10722 {
10723 	struct adapter *sc = arg1;
10724 	struct sbuf *sb;
10725 	int rc;
10726 	struct tp_tnl_stats stats;
10727 
10728 	rc = 0;
10729 	mtx_lock(&sc->reg_lock);
10730 	if (hw_off_limits(sc))
10731 		rc = ENXIO;
10732 	else
10733 		t4_tp_get_tnl_stats(sc, &stats, 1);
10734 	mtx_unlock(&sc->reg_lock);
10735 	if (rc != 0)
10736 		return (rc);
10737 
10738 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10739 	if (sb == NULL)
10740 		return (ENOMEM);
10741 
10742 	if (sc->chip_params->nchan > 2) {
10743 		sbuf_printf(sb, "           channel 0  channel 1"
10744 		    "  channel 2  channel 3\n");
10745 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10746 		    stats.out_pkt[0], stats.out_pkt[1],
10747 		    stats.out_pkt[2], stats.out_pkt[3]);
10748 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10749 		    stats.in_pkt[0], stats.in_pkt[1],
10750 		    stats.in_pkt[2], stats.in_pkt[3]);
10751 	} else {
10752 		sbuf_printf(sb, "           channel 0  channel 1\n");
10753 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10754 		    stats.out_pkt[0], stats.out_pkt[1]);
10755 		sbuf_printf(sb, "InPkts:   %10u %10u",
10756 		    stats.in_pkt[0], stats.in_pkt[1]);
10757 	}
10758 
10759 	rc = sbuf_finish(sb);
10760 	sbuf_delete(sb);
10761 
10762 	return (rc);
10763 }
10764 
10765 static int
10766 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10767 {
10768 	struct adapter *sc = arg1;
10769 	struct tp_params *tpp = &sc->params.tp;
10770 	u_int mask;
10771 	int rc;
10772 
10773 	mask = tpp->la_mask >> 16;
10774 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10775 	if (rc != 0 || req->newptr == NULL)
10776 		return (rc);
10777 	if (mask > 0xffff)
10778 		return (EINVAL);
10779 	mtx_lock(&sc->reg_lock);
10780 	if (hw_off_limits(sc))
10781 		rc = ENXIO;
10782 	else {
10783 		tpp->la_mask = mask << 16;
10784 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10785 		    tpp->la_mask);
10786 	}
10787 	mtx_unlock(&sc->reg_lock);
10788 
10789 	return (rc);
10790 }
10791 
10792 struct field_desc {
10793 	const char *name;
10794 	u_int start;
10795 	u_int width;
10796 };
10797 
10798 static void
10799 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10800 {
10801 	char buf[32];
10802 	int line_size = 0;
10803 
10804 	while (f->name) {
10805 		uint64_t mask = (1ULL << f->width) - 1;
10806 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10807 		    ((uintmax_t)v >> f->start) & mask);
10808 
10809 		if (line_size + len >= 79) {
10810 			line_size = 8;
10811 			sbuf_printf(sb, "\n        ");
10812 		}
10813 		sbuf_printf(sb, "%s ", buf);
10814 		line_size += len + 1;
10815 		f++;
10816 	}
10817 	sbuf_printf(sb, "\n");
10818 }
10819 
10820 static const struct field_desc tp_la0[] = {
10821 	{ "RcfOpCodeOut", 60, 4 },
10822 	{ "State", 56, 4 },
10823 	{ "WcfState", 52, 4 },
10824 	{ "RcfOpcSrcOut", 50, 2 },
10825 	{ "CRxError", 49, 1 },
10826 	{ "ERxError", 48, 1 },
10827 	{ "SanityFailed", 47, 1 },
10828 	{ "SpuriousMsg", 46, 1 },
10829 	{ "FlushInputMsg", 45, 1 },
10830 	{ "FlushInputCpl", 44, 1 },
10831 	{ "RssUpBit", 43, 1 },
10832 	{ "RssFilterHit", 42, 1 },
10833 	{ "Tid", 32, 10 },
10834 	{ "InitTcb", 31, 1 },
10835 	{ "LineNumber", 24, 7 },
10836 	{ "Emsg", 23, 1 },
10837 	{ "EdataOut", 22, 1 },
10838 	{ "Cmsg", 21, 1 },
10839 	{ "CdataOut", 20, 1 },
10840 	{ "EreadPdu", 19, 1 },
10841 	{ "CreadPdu", 18, 1 },
10842 	{ "TunnelPkt", 17, 1 },
10843 	{ "RcfPeerFin", 16, 1 },
10844 	{ "RcfReasonOut", 12, 4 },
10845 	{ "TxCchannel", 10, 2 },
10846 	{ "RcfTxChannel", 8, 2 },
10847 	{ "RxEchannel", 6, 2 },
10848 	{ "RcfRxChannel", 5, 1 },
10849 	{ "RcfDataOutSrdy", 4, 1 },
10850 	{ "RxDvld", 3, 1 },
10851 	{ "RxOoDvld", 2, 1 },
10852 	{ "RxCongestion", 1, 1 },
10853 	{ "TxCongestion", 0, 1 },
10854 	{ NULL }
10855 };
10856 
10857 static const struct field_desc tp_la1[] = {
10858 	{ "CplCmdIn", 56, 8 },
10859 	{ "CplCmdOut", 48, 8 },
10860 	{ "ESynOut", 47, 1 },
10861 	{ "EAckOut", 46, 1 },
10862 	{ "EFinOut", 45, 1 },
10863 	{ "ERstOut", 44, 1 },
10864 	{ "SynIn", 43, 1 },
10865 	{ "AckIn", 42, 1 },
10866 	{ "FinIn", 41, 1 },
10867 	{ "RstIn", 40, 1 },
10868 	{ "DataIn", 39, 1 },
10869 	{ "DataInVld", 38, 1 },
10870 	{ "PadIn", 37, 1 },
10871 	{ "RxBufEmpty", 36, 1 },
10872 	{ "RxDdp", 35, 1 },
10873 	{ "RxFbCongestion", 34, 1 },
10874 	{ "TxFbCongestion", 33, 1 },
10875 	{ "TxPktSumSrdy", 32, 1 },
10876 	{ "RcfUlpType", 28, 4 },
10877 	{ "Eread", 27, 1 },
10878 	{ "Ebypass", 26, 1 },
10879 	{ "Esave", 25, 1 },
10880 	{ "Static0", 24, 1 },
10881 	{ "Cread", 23, 1 },
10882 	{ "Cbypass", 22, 1 },
10883 	{ "Csave", 21, 1 },
10884 	{ "CPktOut", 20, 1 },
10885 	{ "RxPagePoolFull", 18, 2 },
10886 	{ "RxLpbkPkt", 17, 1 },
10887 	{ "TxLpbkPkt", 16, 1 },
10888 	{ "RxVfValid", 15, 1 },
10889 	{ "SynLearned", 14, 1 },
10890 	{ "SetDelEntry", 13, 1 },
10891 	{ "SetInvEntry", 12, 1 },
10892 	{ "CpcmdDvld", 11, 1 },
10893 	{ "CpcmdSave", 10, 1 },
10894 	{ "RxPstructsFull", 8, 2 },
10895 	{ "EpcmdDvld", 7, 1 },
10896 	{ "EpcmdFlush", 6, 1 },
10897 	{ "EpcmdTrimPrefix", 5, 1 },
10898 	{ "EpcmdTrimPostfix", 4, 1 },
10899 	{ "ERssIp4Pkt", 3, 1 },
10900 	{ "ERssIp6Pkt", 2, 1 },
10901 	{ "ERssTcpUdpPkt", 1, 1 },
10902 	{ "ERssFceFipPkt", 0, 1 },
10903 	{ NULL }
10904 };
10905 
10906 static const struct field_desc tp_la2[] = {
10907 	{ "CplCmdIn", 56, 8 },
10908 	{ "MpsVfVld", 55, 1 },
10909 	{ "MpsPf", 52, 3 },
10910 	{ "MpsVf", 44, 8 },
10911 	{ "SynIn", 43, 1 },
10912 	{ "AckIn", 42, 1 },
10913 	{ "FinIn", 41, 1 },
10914 	{ "RstIn", 40, 1 },
10915 	{ "DataIn", 39, 1 },
10916 	{ "DataInVld", 38, 1 },
10917 	{ "PadIn", 37, 1 },
10918 	{ "RxBufEmpty", 36, 1 },
10919 	{ "RxDdp", 35, 1 },
10920 	{ "RxFbCongestion", 34, 1 },
10921 	{ "TxFbCongestion", 33, 1 },
10922 	{ "TxPktSumSrdy", 32, 1 },
10923 	{ "RcfUlpType", 28, 4 },
10924 	{ "Eread", 27, 1 },
10925 	{ "Ebypass", 26, 1 },
10926 	{ "Esave", 25, 1 },
10927 	{ "Static0", 24, 1 },
10928 	{ "Cread", 23, 1 },
10929 	{ "Cbypass", 22, 1 },
10930 	{ "Csave", 21, 1 },
10931 	{ "CPktOut", 20, 1 },
10932 	{ "RxPagePoolFull", 18, 2 },
10933 	{ "RxLpbkPkt", 17, 1 },
10934 	{ "TxLpbkPkt", 16, 1 },
10935 	{ "RxVfValid", 15, 1 },
10936 	{ "SynLearned", 14, 1 },
10937 	{ "SetDelEntry", 13, 1 },
10938 	{ "SetInvEntry", 12, 1 },
10939 	{ "CpcmdDvld", 11, 1 },
10940 	{ "CpcmdSave", 10, 1 },
10941 	{ "RxPstructsFull", 8, 2 },
10942 	{ "EpcmdDvld", 7, 1 },
10943 	{ "EpcmdFlush", 6, 1 },
10944 	{ "EpcmdTrimPrefix", 5, 1 },
10945 	{ "EpcmdTrimPostfix", 4, 1 },
10946 	{ "ERssIp4Pkt", 3, 1 },
10947 	{ "ERssIp6Pkt", 2, 1 },
10948 	{ "ERssTcpUdpPkt", 1, 1 },
10949 	{ "ERssFceFipPkt", 0, 1 },
10950 	{ NULL }
10951 };
10952 
10953 static void
10954 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10955 {
10956 
10957 	field_desc_show(sb, *p, tp_la0);
10958 }
10959 
10960 static void
10961 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10962 {
10963 
10964 	if (idx)
10965 		sbuf_printf(sb, "\n");
10966 	field_desc_show(sb, p[0], tp_la0);
10967 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10968 		field_desc_show(sb, p[1], tp_la0);
10969 }
10970 
10971 static void
10972 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10973 {
10974 
10975 	if (idx)
10976 		sbuf_printf(sb, "\n");
10977 	field_desc_show(sb, p[0], tp_la0);
10978 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10979 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10980 }
10981 
10982 static int
10983 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10984 {
10985 	struct adapter *sc = arg1;
10986 	struct sbuf *sb;
10987 	uint64_t *buf, *p;
10988 	int rc;
10989 	u_int i, inc;
10990 	void (*show_func)(struct sbuf *, uint64_t *, int);
10991 
10992 	rc = 0;
10993 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10994 	if (sb == NULL)
10995 		return (ENOMEM);
10996 
10997 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10998 
10999 	mtx_lock(&sc->reg_lock);
11000 	if (hw_off_limits(sc))
11001 		rc = ENXIO;
11002 	else {
11003 		t4_tp_read_la(sc, buf, NULL);
11004 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11005 		case 2:
11006 			inc = 2;
11007 			show_func = tp_la_show2;
11008 			break;
11009 		case 3:
11010 			inc = 2;
11011 			show_func = tp_la_show3;
11012 			break;
11013 		default:
11014 			inc = 1;
11015 			show_func = tp_la_show;
11016 		}
11017 	}
11018 	mtx_unlock(&sc->reg_lock);
11019 	if (rc != 0)
11020 		goto done;
11021 
11022 	p = buf;
11023 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11024 		(*show_func)(sb, p, i);
11025 	rc = sbuf_finish(sb);
11026 done:
11027 	sbuf_delete(sb);
11028 	free(buf, M_CXGBE);
11029 	return (rc);
11030 }
11031 
11032 static int
11033 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11034 {
11035 	struct adapter *sc = arg1;
11036 	struct sbuf *sb;
11037 	int rc;
11038 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11039 
11040 	rc = 0;
11041 	mtx_lock(&sc->reg_lock);
11042 	if (hw_off_limits(sc))
11043 		rc = ENXIO;
11044 	else
11045 		t4_get_chan_txrate(sc, nrate, orate);
11046 	mtx_unlock(&sc->reg_lock);
11047 	if (rc != 0)
11048 		return (rc);
11049 
11050 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11051 	if (sb == NULL)
11052 		return (ENOMEM);
11053 
11054 	if (sc->chip_params->nchan > 2) {
11055 		sbuf_printf(sb, "              channel 0   channel 1"
11056 		    "   channel 2   channel 3\n");
11057 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11058 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11059 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11060 		    orate[0], orate[1], orate[2], orate[3]);
11061 	} else {
11062 		sbuf_printf(sb, "              channel 0   channel 1\n");
11063 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11064 		    nrate[0], nrate[1]);
11065 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11066 		    orate[0], orate[1]);
11067 	}
11068 
11069 	rc = sbuf_finish(sb);
11070 	sbuf_delete(sb);
11071 
11072 	return (rc);
11073 }
11074 
11075 static int
11076 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11077 {
11078 	struct adapter *sc = arg1;
11079 	struct sbuf *sb;
11080 	uint32_t *buf, *p;
11081 	int rc, i;
11082 
11083 	rc = 0;
11084 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11085 	if (sb == NULL)
11086 		return (ENOMEM);
11087 
11088 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11089 	    M_ZERO | M_WAITOK);
11090 
11091 	mtx_lock(&sc->reg_lock);
11092 	if (hw_off_limits(sc))
11093 		rc = ENXIO;
11094 	else
11095 		t4_ulprx_read_la(sc, buf);
11096 	mtx_unlock(&sc->reg_lock);
11097 	if (rc != 0)
11098 		goto done;
11099 
11100 	p = buf;
11101 	sbuf_printf(sb, "      Pcmd        Type   Message"
11102 	    "                Data");
11103 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11104 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11105 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11106 	}
11107 	rc = sbuf_finish(sb);
11108 done:
11109 	sbuf_delete(sb);
11110 	free(buf, M_CXGBE);
11111 	return (rc);
11112 }
11113 
11114 static int
11115 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11116 {
11117 	struct adapter *sc = arg1;
11118 	struct sbuf *sb;
11119 	int rc;
11120 	uint32_t cfg, s1, s2;
11121 
11122 	MPASS(chip_id(sc) >= CHELSIO_T5);
11123 
11124 	rc = 0;
11125 	mtx_lock(&sc->reg_lock);
11126 	if (hw_off_limits(sc))
11127 		rc = ENXIO;
11128 	else {
11129 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11130 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11131 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11132 	}
11133 	mtx_unlock(&sc->reg_lock);
11134 	if (rc != 0)
11135 		return (rc);
11136 
11137 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11138 	if (sb == NULL)
11139 		return (ENOMEM);
11140 
11141 	if (G_STATSOURCE_T5(cfg) == 7) {
11142 		int mode;
11143 
11144 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11145 		if (mode == 0)
11146 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11147 		else if (mode == 1)
11148 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11149 		else
11150 			sbuf_printf(sb, "unknown mode %d", mode);
11151 	}
11152 	rc = sbuf_finish(sb);
11153 	sbuf_delete(sb);
11154 
11155 	return (rc);
11156 }
11157 
11158 static int
11159 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11160 {
11161 	struct adapter *sc = arg1;
11162 	enum cpu_sets op = arg2;
11163 	cpuset_t cpuset;
11164 	struct sbuf *sb;
11165 	int i, rc;
11166 
11167 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11168 
11169 	CPU_ZERO(&cpuset);
11170 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11171 	if (rc != 0)
11172 		return (rc);
11173 
11174 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11175 	if (sb == NULL)
11176 		return (ENOMEM);
11177 
11178 	CPU_FOREACH(i)
11179 		sbuf_printf(sb, "%d ", i);
11180 	rc = sbuf_finish(sb);
11181 	sbuf_delete(sb);
11182 
11183 	return (rc);
11184 }
11185 
11186 static int
11187 sysctl_reset(SYSCTL_HANDLER_ARGS)
11188 {
11189 	struct adapter *sc = arg1;
11190 	u_int val;
11191 	int rc;
11192 
11193 	val = atomic_load_int(&sc->num_resets);
11194 	rc = sysctl_handle_int(oidp, &val, 0, req);
11195 	if (rc != 0 || req->newptr == NULL)
11196 		return (rc);
11197 
11198 	if (val == 0) {
11199 		/* Zero out the counter that tracks reset. */
11200 		atomic_store_int(&sc->num_resets, 0);
11201 		return (0);
11202 	}
11203 
11204 	if (val != 1)
11205 		return (EINVAL);	/* 0 or 1 are the only legal values */
11206 
11207 	if (hw_off_limits(sc))		/* harmless race */
11208 		return (EALREADY);
11209 
11210 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11211 	return (0);
11212 }
11213 
11214 #ifdef TCP_OFFLOAD
11215 static int
11216 sysctl_tls(SYSCTL_HANDLER_ARGS)
11217 {
11218 	struct adapter *sc = arg1;
11219 	int i, j, v, rc;
11220 	struct vi_info *vi;
11221 
11222 	v = sc->tt.tls;
11223 	rc = sysctl_handle_int(oidp, &v, 0, req);
11224 	if (rc != 0 || req->newptr == NULL)
11225 		return (rc);
11226 
11227 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11228 		return (ENOTSUP);
11229 
11230 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11231 	if (rc)
11232 		return (rc);
11233 	if (hw_off_limits(sc))
11234 		rc = ENXIO;
11235 	else {
11236 		sc->tt.tls = !!v;
11237 		for_each_port(sc, i) {
11238 			for_each_vi(sc->port[i], j, vi) {
11239 				if (vi->flags & VI_INIT_DONE)
11240 					t4_update_fl_bufsize(vi->ifp);
11241 			}
11242 		}
11243 	}
11244 	end_synchronized_op(sc, 0);
11245 
11246 	return (rc);
11247 
11248 }
11249 
11250 static void
11251 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11252 {
11253 	u_int rem = val % factor;
11254 
11255 	if (rem == 0)
11256 		snprintf(buf, len, "%u", val / factor);
11257 	else {
11258 		while (rem % 10 == 0)
11259 			rem /= 10;
11260 		snprintf(buf, len, "%u.%u", val / factor, rem);
11261 	}
11262 }
11263 
11264 static int
11265 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11266 {
11267 	struct adapter *sc = arg1;
11268 	char buf[16];
11269 	u_int res, re;
11270 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11271 
11272 	mtx_lock(&sc->reg_lock);
11273 	if (hw_off_limits(sc))
11274 		res = (u_int)-1;
11275 	else
11276 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11277 	mtx_unlock(&sc->reg_lock);
11278 	if (res == (u_int)-1)
11279 		return (ENXIO);
11280 
11281 	switch (arg2) {
11282 	case 0:
11283 		/* timer_tick */
11284 		re = G_TIMERRESOLUTION(res);
11285 		break;
11286 	case 1:
11287 		/* TCP timestamp tick */
11288 		re = G_TIMESTAMPRESOLUTION(res);
11289 		break;
11290 	case 2:
11291 		/* DACK tick */
11292 		re = G_DELAYEDACKRESOLUTION(res);
11293 		break;
11294 	default:
11295 		return (EDOOFUS);
11296 	}
11297 
11298 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11299 
11300 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11301 }
11302 
11303 static int
11304 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11305 {
11306 	struct adapter *sc = arg1;
11307 	int rc;
11308 	u_int dack_tmr, dack_re, v;
11309 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11310 
11311 	mtx_lock(&sc->reg_lock);
11312 	if (hw_off_limits(sc))
11313 		rc = ENXIO;
11314 	else {
11315 		rc = 0;
11316 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11317 		    A_TP_TIMER_RESOLUTION));
11318 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11319 	}
11320 	mtx_unlock(&sc->reg_lock);
11321 	if (rc != 0)
11322 		return (rc);
11323 
11324 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11325 
11326 	return (sysctl_handle_int(oidp, &v, 0, req));
11327 }
11328 
11329 static int
11330 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11331 {
11332 	struct adapter *sc = arg1;
11333 	int rc, reg = arg2;
11334 	u_int tre;
11335 	u_long tp_tick_us, v;
11336 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11337 
11338 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11339 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11340 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11341 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11342 
11343 	mtx_lock(&sc->reg_lock);
11344 	if (hw_off_limits(sc))
11345 		rc = ENXIO;
11346 	else {
11347 		rc = 0;
11348 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11349 		tp_tick_us = (cclk_ps << tre) / 1000000;
11350 		if (reg == A_TP_INIT_SRTT)
11351 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11352 		else
11353 			v = tp_tick_us * t4_read_reg(sc, reg);
11354 	}
11355 	mtx_unlock(&sc->reg_lock);
11356 	if (rc != 0)
11357 		return (rc);
11358 	else
11359 		return (sysctl_handle_long(oidp, &v, 0, req));
11360 }
11361 
11362 /*
11363  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11364  * passed to this function.
11365  */
11366 static int
11367 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11368 {
11369 	struct adapter *sc = arg1;
11370 	int rc, idx = arg2;
11371 	u_int v;
11372 
11373 	MPASS(idx >= 0 && idx <= 24);
11374 
11375 	mtx_lock(&sc->reg_lock);
11376 	if (hw_off_limits(sc))
11377 		rc = ENXIO;
11378 	else {
11379 		rc = 0;
11380 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11381 	}
11382 	mtx_unlock(&sc->reg_lock);
11383 	if (rc != 0)
11384 		return (rc);
11385 	else
11386 		return (sysctl_handle_int(oidp, &v, 0, req));
11387 }
11388 
11389 static int
11390 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11391 {
11392 	struct adapter *sc = arg1;
11393 	int rc, idx = arg2;
11394 	u_int shift, v, r;
11395 
11396 	MPASS(idx >= 0 && idx < 16);
11397 
11398 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11399 	shift = (idx & 3) << 3;
11400 	mtx_lock(&sc->reg_lock);
11401 	if (hw_off_limits(sc))
11402 		rc = ENXIO;
11403 	else {
11404 		rc = 0;
11405 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11406 	}
11407 	mtx_unlock(&sc->reg_lock);
11408 	if (rc != 0)
11409 		return (rc);
11410 	else
11411 		return (sysctl_handle_int(oidp, &v, 0, req));
11412 }
11413 
11414 static int
11415 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11416 {
11417 	struct vi_info *vi = arg1;
11418 	struct adapter *sc = vi->adapter;
11419 	int idx, rc, i;
11420 	struct sge_ofld_rxq *ofld_rxq;
11421 	uint8_t v;
11422 
11423 	idx = vi->ofld_tmr_idx;
11424 
11425 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11426 	if (rc != 0 || req->newptr == NULL)
11427 		return (rc);
11428 
11429 	if (idx < 0 || idx >= SGE_NTIMERS)
11430 		return (EINVAL);
11431 
11432 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11433 	    "t4otmr");
11434 	if (rc)
11435 		return (rc);
11436 
11437 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11438 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11439 #ifdef atomic_store_rel_8
11440 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11441 #else
11442 		ofld_rxq->iq.intr_params = v;
11443 #endif
11444 	}
11445 	vi->ofld_tmr_idx = idx;
11446 
11447 	end_synchronized_op(sc, LOCK_HELD);
11448 	return (0);
11449 }
11450 
11451 static int
11452 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11453 {
11454 	struct vi_info *vi = arg1;
11455 	struct adapter *sc = vi->adapter;
11456 	int idx, rc;
11457 
11458 	idx = vi->ofld_pktc_idx;
11459 
11460 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11461 	if (rc != 0 || req->newptr == NULL)
11462 		return (rc);
11463 
11464 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11465 		return (EINVAL);
11466 
11467 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11468 	    "t4opktc");
11469 	if (rc)
11470 		return (rc);
11471 
11472 	if (vi->flags & VI_INIT_DONE)
11473 		rc = EBUSY; /* cannot be changed once the queues are created */
11474 	else
11475 		vi->ofld_pktc_idx = idx;
11476 
11477 	end_synchronized_op(sc, LOCK_HELD);
11478 	return (rc);
11479 }
11480 #endif
11481 
11482 static int
11483 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11484 {
11485 	int rc;
11486 
11487 	if (cntxt->cid > M_CTXTQID)
11488 		return (EINVAL);
11489 
11490 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11491 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11492 		return (EINVAL);
11493 
11494 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11495 	if (rc)
11496 		return (rc);
11497 
11498 	if (hw_off_limits(sc)) {
11499 		rc = ENXIO;
11500 		goto done;
11501 	}
11502 
11503 	if (sc->flags & FW_OK) {
11504 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11505 		    &cntxt->data[0]);
11506 		if (rc == 0)
11507 			goto done;
11508 	}
11509 
11510 	/*
11511 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11512 	 * the backdoor.
11513 	 */
11514 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11515 done:
11516 	end_synchronized_op(sc, 0);
11517 	return (rc);
11518 }
11519 
11520 static int
11521 load_fw(struct adapter *sc, struct t4_data *fw)
11522 {
11523 	int rc;
11524 	uint8_t *fw_data;
11525 
11526 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11527 	if (rc)
11528 		return (rc);
11529 
11530 	if (hw_off_limits(sc)) {
11531 		rc = ENXIO;
11532 		goto done;
11533 	}
11534 
11535 	/*
11536 	 * The firmware, with the sole exception of the memory parity error
11537 	 * handler, runs from memory and not flash.  It is almost always safe to
11538 	 * install a new firmware on a running system.  Just set bit 1 in
11539 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11540 	 */
11541 	if (sc->flags & FULL_INIT_DONE &&
11542 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11543 		rc = EBUSY;
11544 		goto done;
11545 	}
11546 
11547 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11548 
11549 	rc = copyin(fw->data, fw_data, fw->len);
11550 	if (rc == 0)
11551 		rc = -t4_load_fw(sc, fw_data, fw->len);
11552 
11553 	free(fw_data, M_CXGBE);
11554 done:
11555 	end_synchronized_op(sc, 0);
11556 	return (rc);
11557 }
11558 
11559 static int
11560 load_cfg(struct adapter *sc, struct t4_data *cfg)
11561 {
11562 	int rc;
11563 	uint8_t *cfg_data = NULL;
11564 
11565 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11566 	if (rc)
11567 		return (rc);
11568 
11569 	if (hw_off_limits(sc)) {
11570 		rc = ENXIO;
11571 		goto done;
11572 	}
11573 
11574 	if (cfg->len == 0) {
11575 		/* clear */
11576 		rc = -t4_load_cfg(sc, NULL, 0);
11577 		goto done;
11578 	}
11579 
11580 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11581 
11582 	rc = copyin(cfg->data, cfg_data, cfg->len);
11583 	if (rc == 0)
11584 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11585 
11586 	free(cfg_data, M_CXGBE);
11587 done:
11588 	end_synchronized_op(sc, 0);
11589 	return (rc);
11590 }
11591 
11592 static int
11593 load_boot(struct adapter *sc, struct t4_bootrom *br)
11594 {
11595 	int rc;
11596 	uint8_t *br_data = NULL;
11597 	u_int offset;
11598 
11599 	if (br->len > 1024 * 1024)
11600 		return (EFBIG);
11601 
11602 	if (br->pf_offset == 0) {
11603 		/* pfidx */
11604 		if (br->pfidx_addr > 7)
11605 			return (EINVAL);
11606 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11607 		    A_PCIE_PF_EXPROM_OFST)));
11608 	} else if (br->pf_offset == 1) {
11609 		/* offset */
11610 		offset = G_OFFSET(br->pfidx_addr);
11611 	} else {
11612 		return (EINVAL);
11613 	}
11614 
11615 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11616 	if (rc)
11617 		return (rc);
11618 
11619 	if (hw_off_limits(sc)) {
11620 		rc = ENXIO;
11621 		goto done;
11622 	}
11623 
11624 	if (br->len == 0) {
11625 		/* clear */
11626 		rc = -t4_load_boot(sc, NULL, offset, 0);
11627 		goto done;
11628 	}
11629 
11630 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11631 
11632 	rc = copyin(br->data, br_data, br->len);
11633 	if (rc == 0)
11634 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11635 
11636 	free(br_data, M_CXGBE);
11637 done:
11638 	end_synchronized_op(sc, 0);
11639 	return (rc);
11640 }
11641 
11642 static int
11643 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11644 {
11645 	int rc;
11646 	uint8_t *bc_data = NULL;
11647 
11648 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11649 	if (rc)
11650 		return (rc);
11651 
11652 	if (hw_off_limits(sc)) {
11653 		rc = ENXIO;
11654 		goto done;
11655 	}
11656 
11657 	if (bc->len == 0) {
11658 		/* clear */
11659 		rc = -t4_load_bootcfg(sc, NULL, 0);
11660 		goto done;
11661 	}
11662 
11663 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11664 
11665 	rc = copyin(bc->data, bc_data, bc->len);
11666 	if (rc == 0)
11667 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11668 
11669 	free(bc_data, M_CXGBE);
11670 done:
11671 	end_synchronized_op(sc, 0);
11672 	return (rc);
11673 }
11674 
11675 static int
11676 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11677 {
11678 	int rc;
11679 	struct cudbg_init *cudbg;
11680 	void *handle, *buf;
11681 
11682 	/* buf is large, don't block if no memory is available */
11683 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11684 	if (buf == NULL)
11685 		return (ENOMEM);
11686 
11687 	handle = cudbg_alloc_handle();
11688 	if (handle == NULL) {
11689 		rc = ENOMEM;
11690 		goto done;
11691 	}
11692 
11693 	cudbg = cudbg_get_init(handle);
11694 	cudbg->adap = sc;
11695 	cudbg->print = (cudbg_print_cb)printf;
11696 
11697 #ifndef notyet
11698 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11699 	    __func__, dump->wr_flash, dump->len, dump->data);
11700 #endif
11701 
11702 	if (dump->wr_flash)
11703 		cudbg->use_flash = 1;
11704 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11705 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11706 
11707 	rc = cudbg_collect(handle, buf, &dump->len);
11708 	if (rc != 0)
11709 		goto done;
11710 
11711 	rc = copyout(buf, dump->data, dump->len);
11712 done:
11713 	cudbg_free_handle(handle);
11714 	free(buf, M_CXGBE);
11715 	return (rc);
11716 }
11717 
11718 static void
11719 free_offload_policy(struct t4_offload_policy *op)
11720 {
11721 	struct offload_rule *r;
11722 	int i;
11723 
11724 	if (op == NULL)
11725 		return;
11726 
11727 	r = &op->rule[0];
11728 	for (i = 0; i < op->nrules; i++, r++) {
11729 		free(r->bpf_prog.bf_insns, M_CXGBE);
11730 	}
11731 	free(op->rule, M_CXGBE);
11732 	free(op, M_CXGBE);
11733 }
11734 
11735 static int
11736 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11737 {
11738 	int i, rc, len;
11739 	struct t4_offload_policy *op, *old;
11740 	struct bpf_program *bf;
11741 	const struct offload_settings *s;
11742 	struct offload_rule *r;
11743 	void *u;
11744 
11745 	if (!is_offload(sc))
11746 		return (ENODEV);
11747 
11748 	if (uop->nrules == 0) {
11749 		/* Delete installed policies. */
11750 		op = NULL;
11751 		goto set_policy;
11752 	} else if (uop->nrules > 256) { /* arbitrary */
11753 		return (E2BIG);
11754 	}
11755 
11756 	/* Copy userspace offload policy to kernel */
11757 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11758 	op->nrules = uop->nrules;
11759 	len = op->nrules * sizeof(struct offload_rule);
11760 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11761 	rc = copyin(uop->rule, op->rule, len);
11762 	if (rc) {
11763 		free(op->rule, M_CXGBE);
11764 		free(op, M_CXGBE);
11765 		return (rc);
11766 	}
11767 
11768 	r = &op->rule[0];
11769 	for (i = 0; i < op->nrules; i++, r++) {
11770 
11771 		/* Validate open_type */
11772 		if (r->open_type != OPEN_TYPE_LISTEN &&
11773 		    r->open_type != OPEN_TYPE_ACTIVE &&
11774 		    r->open_type != OPEN_TYPE_PASSIVE &&
11775 		    r->open_type != OPEN_TYPE_DONTCARE) {
11776 error:
11777 			/*
11778 			 * Rules 0 to i have malloc'd filters that need to be
11779 			 * freed.  Rules i+1 to nrules have userspace pointers
11780 			 * and should be left alone.
11781 			 */
11782 			op->nrules = i;
11783 			free_offload_policy(op);
11784 			return (rc);
11785 		}
11786 
11787 		/* Validate settings */
11788 		s = &r->settings;
11789 		if ((s->offload != 0 && s->offload != 1) ||
11790 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11791 		    s->sched_class < -1 ||
11792 		    s->sched_class >= sc->params.nsched_cls) {
11793 			rc = EINVAL;
11794 			goto error;
11795 		}
11796 
11797 		bf = &r->bpf_prog;
11798 		u = bf->bf_insns;	/* userspace ptr */
11799 		bf->bf_insns = NULL;
11800 		if (bf->bf_len == 0) {
11801 			/* legal, matches everything */
11802 			continue;
11803 		}
11804 		len = bf->bf_len * sizeof(*bf->bf_insns);
11805 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11806 		rc = copyin(u, bf->bf_insns, len);
11807 		if (rc != 0)
11808 			goto error;
11809 
11810 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11811 			rc = EINVAL;
11812 			goto error;
11813 		}
11814 	}
11815 set_policy:
11816 	rw_wlock(&sc->policy_lock);
11817 	old = sc->policy;
11818 	sc->policy = op;
11819 	rw_wunlock(&sc->policy_lock);
11820 	free_offload_policy(old);
11821 
11822 	return (0);
11823 }
11824 
11825 #define MAX_READ_BUF_SIZE (128 * 1024)
11826 static int
11827 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11828 {
11829 	uint32_t addr, remaining, n;
11830 	uint32_t *buf;
11831 	int rc;
11832 	uint8_t *dst;
11833 
11834 	mtx_lock(&sc->reg_lock);
11835 	if (hw_off_limits(sc))
11836 		rc = ENXIO;
11837 	else
11838 		rc = validate_mem_range(sc, mr->addr, mr->len);
11839 	mtx_unlock(&sc->reg_lock);
11840 	if (rc != 0)
11841 		return (rc);
11842 
11843 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11844 	addr = mr->addr;
11845 	remaining = mr->len;
11846 	dst = (void *)mr->data;
11847 
11848 	while (remaining) {
11849 		n = min(remaining, MAX_READ_BUF_SIZE);
11850 		mtx_lock(&sc->reg_lock);
11851 		if (hw_off_limits(sc))
11852 			rc = ENXIO;
11853 		else
11854 			read_via_memwin(sc, 2, addr, buf, n);
11855 		mtx_unlock(&sc->reg_lock);
11856 		if (rc != 0)
11857 			break;
11858 
11859 		rc = copyout(buf, dst, n);
11860 		if (rc != 0)
11861 			break;
11862 
11863 		dst += n;
11864 		remaining -= n;
11865 		addr += n;
11866 	}
11867 
11868 	free(buf, M_CXGBE);
11869 	return (rc);
11870 }
11871 #undef MAX_READ_BUF_SIZE
11872 
11873 static int
11874 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11875 {
11876 	int rc;
11877 
11878 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11879 		return (EINVAL);
11880 
11881 	if (i2cd->len > sizeof(i2cd->data))
11882 		return (EFBIG);
11883 
11884 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11885 	if (rc)
11886 		return (rc);
11887 	if (hw_off_limits(sc))
11888 		rc = ENXIO;
11889 	else
11890 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11891 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11892 	end_synchronized_op(sc, 0);
11893 
11894 	return (rc);
11895 }
11896 
11897 static int
11898 clear_stats(struct adapter *sc, u_int port_id)
11899 {
11900 	int i, v, chan_map;
11901 	struct port_info *pi;
11902 	struct vi_info *vi;
11903 	struct sge_rxq *rxq;
11904 	struct sge_txq *txq;
11905 	struct sge_wrq *wrq;
11906 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11907 	struct sge_ofld_txq *ofld_txq;
11908 #endif
11909 #ifdef TCP_OFFLOAD
11910 	struct sge_ofld_rxq *ofld_rxq;
11911 #endif
11912 
11913 	if (port_id >= sc->params.nports)
11914 		return (EINVAL);
11915 	pi = sc->port[port_id];
11916 	if (pi == NULL)
11917 		return (EIO);
11918 
11919 	mtx_lock(&sc->reg_lock);
11920 	if (!hw_off_limits(sc)) {
11921 		/* MAC stats */
11922 		t4_clr_port_stats(sc, pi->tx_chan);
11923 		if (is_t6(sc)) {
11924 			if (pi->fcs_reg != -1)
11925 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11926 			else
11927 				pi->stats.rx_fcs_err = 0;
11928 		}
11929 		for_each_vi(pi, v, vi) {
11930 			if (vi->flags & VI_INIT_DONE)
11931 				t4_clr_vi_stats(sc, vi->vin);
11932 		}
11933 		chan_map = pi->rx_e_chan_map;
11934 		v = 0;	/* reuse */
11935 		while (chan_map) {
11936 			i = ffs(chan_map) - 1;
11937 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11938 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11939 			chan_map &= ~(1 << i);
11940 		}
11941 	}
11942 	mtx_unlock(&sc->reg_lock);
11943 	pi->tx_parse_error = 0;
11944 	pi->tnl_cong_drops = 0;
11945 
11946 	/*
11947 	 * Since this command accepts a port, clear stats for
11948 	 * all VIs on this port.
11949 	 */
11950 	for_each_vi(pi, v, vi) {
11951 		if (vi->flags & VI_INIT_DONE) {
11952 
11953 			for_each_rxq(vi, i, rxq) {
11954 #if defined(INET) || defined(INET6)
11955 				rxq->lro.lro_queued = 0;
11956 				rxq->lro.lro_flushed = 0;
11957 #endif
11958 				rxq->rxcsum = 0;
11959 				rxq->vlan_extraction = 0;
11960 				rxq->vxlan_rxcsum = 0;
11961 
11962 				rxq->fl.cl_allocated = 0;
11963 				rxq->fl.cl_recycled = 0;
11964 				rxq->fl.cl_fast_recycled = 0;
11965 			}
11966 
11967 			for_each_txq(vi, i, txq) {
11968 				txq->txcsum = 0;
11969 				txq->tso_wrs = 0;
11970 				txq->vlan_insertion = 0;
11971 				txq->imm_wrs = 0;
11972 				txq->sgl_wrs = 0;
11973 				txq->txpkt_wrs = 0;
11974 				txq->txpkts0_wrs = 0;
11975 				txq->txpkts1_wrs = 0;
11976 				txq->txpkts0_pkts = 0;
11977 				txq->txpkts1_pkts = 0;
11978 				txq->txpkts_flush = 0;
11979 				txq->raw_wrs = 0;
11980 				txq->vxlan_tso_wrs = 0;
11981 				txq->vxlan_txcsum = 0;
11982 				txq->kern_tls_records = 0;
11983 				txq->kern_tls_short = 0;
11984 				txq->kern_tls_partial = 0;
11985 				txq->kern_tls_full = 0;
11986 				txq->kern_tls_octets = 0;
11987 				txq->kern_tls_waste = 0;
11988 				txq->kern_tls_options = 0;
11989 				txq->kern_tls_header = 0;
11990 				txq->kern_tls_fin = 0;
11991 				txq->kern_tls_fin_short = 0;
11992 				txq->kern_tls_cbc = 0;
11993 				txq->kern_tls_gcm = 0;
11994 				mp_ring_reset_stats(txq->r);
11995 			}
11996 
11997 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11998 			for_each_ofld_txq(vi, i, ofld_txq) {
11999 				ofld_txq->wrq.tx_wrs_direct = 0;
12000 				ofld_txq->wrq.tx_wrs_copied = 0;
12001 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12002 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12003 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12004 				counter_u64_zero(ofld_txq->tx_aio_jobs);
12005 				counter_u64_zero(ofld_txq->tx_aio_octets);
12006 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12007 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12008 			}
12009 #endif
12010 #ifdef TCP_OFFLOAD
12011 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12012 				ofld_rxq->fl.cl_allocated = 0;
12013 				ofld_rxq->fl.cl_recycled = 0;
12014 				ofld_rxq->fl.cl_fast_recycled = 0;
12015 				counter_u64_zero(
12016 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12017 				counter_u64_zero(
12018 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12019 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12020 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12021 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12022 				ofld_rxq->rx_iscsi_fl_octets = 0;
12023 				ofld_rxq->rx_aio_ddp_jobs = 0;
12024 				ofld_rxq->rx_aio_ddp_octets = 0;
12025 				ofld_rxq->rx_toe_tls_records = 0;
12026 				ofld_rxq->rx_toe_tls_octets = 0;
12027 				ofld_rxq->rx_toe_ddp_octets = 0;
12028 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12029 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12030 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12031 			}
12032 #endif
12033 
12034 			if (IS_MAIN_VI(vi)) {
12035 				wrq = &sc->sge.ctrlq[pi->port_id];
12036 				wrq->tx_wrs_direct = 0;
12037 				wrq->tx_wrs_copied = 0;
12038 			}
12039 		}
12040 	}
12041 
12042 	return (0);
12043 }
12044 
12045 static int
12046 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12047 {
12048 #ifdef INET6
12049 	struct in6_addr in6;
12050 
12051 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12052 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12053 		return (0);
12054 	else
12055 		return (EIO);
12056 #else
12057 	return (ENOTSUP);
12058 #endif
12059 }
12060 
12061 static int
12062 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12063 {
12064 #ifdef INET6
12065 	struct in6_addr in6;
12066 
12067 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12068 	return (t4_release_clip_addr(sc, &in6));
12069 #else
12070 	return (ENOTSUP);
12071 #endif
12072 }
12073 
12074 int
12075 t4_os_find_pci_capability(struct adapter *sc, int cap)
12076 {
12077 	int i;
12078 
12079 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12080 }
12081 
12082 int
12083 t4_os_pci_save_state(struct adapter *sc)
12084 {
12085 	device_t dev;
12086 	struct pci_devinfo *dinfo;
12087 
12088 	dev = sc->dev;
12089 	dinfo = device_get_ivars(dev);
12090 
12091 	pci_cfg_save(dev, dinfo, 0);
12092 	return (0);
12093 }
12094 
12095 int
12096 t4_os_pci_restore_state(struct adapter *sc)
12097 {
12098 	device_t dev;
12099 	struct pci_devinfo *dinfo;
12100 
12101 	dev = sc->dev;
12102 	dinfo = device_get_ivars(dev);
12103 
12104 	pci_cfg_restore(dev, dinfo);
12105 	return (0);
12106 }
12107 
12108 void
12109 t4_os_portmod_changed(struct port_info *pi)
12110 {
12111 	struct adapter *sc = pi->adapter;
12112 	struct vi_info *vi;
12113 	if_t ifp;
12114 	static const char *mod_str[] = {
12115 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12116 	};
12117 
12118 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12119 	    ("%s: port_type %u", __func__, pi->port_type));
12120 
12121 	vi = &pi->vi[0];
12122 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12123 		PORT_LOCK(pi);
12124 		build_medialist(pi);
12125 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12126 			fixup_link_config(pi);
12127 			apply_link_config(pi);
12128 		}
12129 		PORT_UNLOCK(pi);
12130 		end_synchronized_op(sc, LOCK_HELD);
12131 	}
12132 
12133 	ifp = vi->ifp;
12134 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12135 		if_printf(ifp, "transceiver unplugged.\n");
12136 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12137 		if_printf(ifp, "unknown transceiver inserted.\n");
12138 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12139 		if_printf(ifp, "unsupported transceiver inserted.\n");
12140 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12141 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12142 		    port_top_speed(pi), mod_str[pi->mod_type]);
12143 	} else {
12144 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12145 		    pi->mod_type);
12146 	}
12147 }
12148 
12149 void
12150 t4_os_link_changed(struct port_info *pi)
12151 {
12152 	struct vi_info *vi;
12153 	if_t ifp;
12154 	struct link_config *lc = &pi->link_cfg;
12155 	struct adapter *sc = pi->adapter;
12156 	int v;
12157 
12158 	PORT_LOCK_ASSERT_OWNED(pi);
12159 
12160 	if (is_t6(sc)) {
12161 		if (lc->link_ok) {
12162 			if (lc->speed > 25000 ||
12163 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12164 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12165 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12166 			} else {
12167 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12168 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12169 			}
12170 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12171 			pi->stats.rx_fcs_err = 0;
12172 		} else {
12173 			pi->fcs_reg = -1;
12174 		}
12175 	} else {
12176 		MPASS(pi->fcs_reg != -1);
12177 		MPASS(pi->fcs_base == 0);
12178 	}
12179 
12180 	for_each_vi(pi, v, vi) {
12181 		ifp = vi->ifp;
12182 		if (ifp == NULL || IS_DETACHING(vi))
12183 			continue;
12184 
12185 		if (lc->link_ok) {
12186 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12187 			if_link_state_change(ifp, LINK_STATE_UP);
12188 		} else {
12189 			if_link_state_change(ifp, LINK_STATE_DOWN);
12190 		}
12191 	}
12192 }
12193 
12194 void
12195 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12196 {
12197 	struct adapter *sc;
12198 
12199 	sx_slock(&t4_list_lock);
12200 	SLIST_FOREACH(sc, &t4_list, link) {
12201 		/*
12202 		 * func should not make any assumptions about what state sc is
12203 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12204 		 */
12205 		func(sc, arg);
12206 	}
12207 	sx_sunlock(&t4_list_lock);
12208 }
12209 
12210 static int
12211 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12212     struct thread *td)
12213 {
12214 	int rc;
12215 	struct adapter *sc = dev->si_drv1;
12216 
12217 	rc = priv_check(td, PRIV_DRIVER);
12218 	if (rc != 0)
12219 		return (rc);
12220 
12221 	switch (cmd) {
12222 	case CHELSIO_T4_GETREG: {
12223 		struct t4_reg *edata = (struct t4_reg *)data;
12224 
12225 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12226 			return (EFAULT);
12227 
12228 		mtx_lock(&sc->reg_lock);
12229 		if (hw_off_limits(sc))
12230 			rc = ENXIO;
12231 		else if (edata->size == 4)
12232 			edata->val = t4_read_reg(sc, edata->addr);
12233 		else if (edata->size == 8)
12234 			edata->val = t4_read_reg64(sc, edata->addr);
12235 		else
12236 			rc = EINVAL;
12237 		mtx_unlock(&sc->reg_lock);
12238 
12239 		break;
12240 	}
12241 	case CHELSIO_T4_SETREG: {
12242 		struct t4_reg *edata = (struct t4_reg *)data;
12243 
12244 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12245 			return (EFAULT);
12246 
12247 		mtx_lock(&sc->reg_lock);
12248 		if (hw_off_limits(sc))
12249 			rc = ENXIO;
12250 		else if (edata->size == 4) {
12251 			if (edata->val & 0xffffffff00000000)
12252 				rc = EINVAL;
12253 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12254 		} else if (edata->size == 8)
12255 			t4_write_reg64(sc, edata->addr, edata->val);
12256 		else
12257 			rc = EINVAL;
12258 		mtx_unlock(&sc->reg_lock);
12259 
12260 		break;
12261 	}
12262 	case CHELSIO_T4_REGDUMP: {
12263 		struct t4_regdump *regs = (struct t4_regdump *)data;
12264 		int reglen = t4_get_regs_len(sc);
12265 		uint8_t *buf;
12266 
12267 		if (regs->len < reglen) {
12268 			regs->len = reglen; /* hint to the caller */
12269 			return (ENOBUFS);
12270 		}
12271 
12272 		regs->len = reglen;
12273 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12274 		mtx_lock(&sc->reg_lock);
12275 		if (hw_off_limits(sc))
12276 			rc = ENXIO;
12277 		else
12278 			get_regs(sc, regs, buf);
12279 		mtx_unlock(&sc->reg_lock);
12280 		if (rc == 0)
12281 			rc = copyout(buf, regs->data, reglen);
12282 		free(buf, M_CXGBE);
12283 		break;
12284 	}
12285 	case CHELSIO_T4_GET_FILTER_MODE:
12286 		rc = get_filter_mode(sc, (uint32_t *)data);
12287 		break;
12288 	case CHELSIO_T4_SET_FILTER_MODE:
12289 		rc = set_filter_mode(sc, *(uint32_t *)data);
12290 		break;
12291 	case CHELSIO_T4_SET_FILTER_MASK:
12292 		rc = set_filter_mask(sc, *(uint32_t *)data);
12293 		break;
12294 	case CHELSIO_T4_GET_FILTER:
12295 		rc = get_filter(sc, (struct t4_filter *)data);
12296 		break;
12297 	case CHELSIO_T4_SET_FILTER:
12298 		rc = set_filter(sc, (struct t4_filter *)data);
12299 		break;
12300 	case CHELSIO_T4_DEL_FILTER:
12301 		rc = del_filter(sc, (struct t4_filter *)data);
12302 		break;
12303 	case CHELSIO_T4_GET_SGE_CONTEXT:
12304 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12305 		break;
12306 	case CHELSIO_T4_LOAD_FW:
12307 		rc = load_fw(sc, (struct t4_data *)data);
12308 		break;
12309 	case CHELSIO_T4_GET_MEM:
12310 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12311 		break;
12312 	case CHELSIO_T4_GET_I2C:
12313 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12314 		break;
12315 	case CHELSIO_T4_CLEAR_STATS:
12316 		rc = clear_stats(sc, *(uint32_t *)data);
12317 		break;
12318 	case CHELSIO_T4_SCHED_CLASS:
12319 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12320 		break;
12321 	case CHELSIO_T4_SCHED_QUEUE:
12322 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12323 		break;
12324 	case CHELSIO_T4_GET_TRACER:
12325 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12326 		break;
12327 	case CHELSIO_T4_SET_TRACER:
12328 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12329 		break;
12330 	case CHELSIO_T4_LOAD_CFG:
12331 		rc = load_cfg(sc, (struct t4_data *)data);
12332 		break;
12333 	case CHELSIO_T4_LOAD_BOOT:
12334 		rc = load_boot(sc, (struct t4_bootrom *)data);
12335 		break;
12336 	case CHELSIO_T4_LOAD_BOOTCFG:
12337 		rc = load_bootcfg(sc, (struct t4_data *)data);
12338 		break;
12339 	case CHELSIO_T4_CUDBG_DUMP:
12340 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12341 		break;
12342 	case CHELSIO_T4_SET_OFLD_POLICY:
12343 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12344 		break;
12345 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12346 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12347 		break;
12348 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12349 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12350 		break;
12351 	default:
12352 		rc = ENOTTY;
12353 	}
12354 
12355 	return (rc);
12356 }
12357 
12358 #ifdef TCP_OFFLOAD
12359 static int
12360 toe_capability(struct vi_info *vi, bool enable)
12361 {
12362 	int rc;
12363 	struct port_info *pi = vi->pi;
12364 	struct adapter *sc = pi->adapter;
12365 
12366 	ASSERT_SYNCHRONIZED_OP(sc);
12367 
12368 	if (!is_offload(sc))
12369 		return (ENODEV);
12370 	if (hw_off_limits(sc))
12371 		return (ENXIO);
12372 
12373 	if (enable) {
12374 #ifdef KERN_TLS
12375 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12376 			int i, j, n;
12377 			struct port_info *p;
12378 			struct vi_info *v;
12379 
12380 			/*
12381 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12382 			 * on any ifnet.
12383 			 */
12384 			n = 0;
12385 			for_each_port(sc, i) {
12386 				p = sc->port[i];
12387 				for_each_vi(p, j, v) {
12388 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12389 						CH_WARN(sc,
12390 						    "%s has NIC TLS enabled.\n",
12391 						    device_get_nameunit(v->dev));
12392 						n++;
12393 					}
12394 				}
12395 			}
12396 			if (n > 0) {
12397 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12398 				    "associated with this adapter before "
12399 				    "trying to enable TOE.\n");
12400 				return (EAGAIN);
12401 			}
12402 			rc = t6_config_kern_tls(sc, false);
12403 			if (rc)
12404 				return (rc);
12405 		}
12406 #endif
12407 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12408 			/* TOE is already enabled. */
12409 			return (0);
12410 		}
12411 
12412 		/*
12413 		 * We need the port's queues around so that we're able to send
12414 		 * and receive CPLs to/from the TOE even if the ifnet for this
12415 		 * port has never been UP'd administratively.
12416 		 */
12417 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12418 			return (rc);
12419 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12420 		    ((rc = vi_init(&pi->vi[0])) != 0))
12421 			return (rc);
12422 
12423 		if (isset(&sc->offload_map, pi->port_id)) {
12424 			/* TOE is enabled on another VI of this port. */
12425 			pi->uld_vis++;
12426 			return (0);
12427 		}
12428 
12429 		if (!uld_active(sc, ULD_TOM)) {
12430 			rc = t4_activate_uld(sc, ULD_TOM);
12431 			if (rc == EAGAIN) {
12432 				log(LOG_WARNING,
12433 				    "You must kldload t4_tom.ko before trying "
12434 				    "to enable TOE on a cxgbe interface.\n");
12435 			}
12436 			if (rc != 0)
12437 				return (rc);
12438 			KASSERT(sc->tom_softc != NULL,
12439 			    ("%s: TOM activated but softc NULL", __func__));
12440 			KASSERT(uld_active(sc, ULD_TOM),
12441 			    ("%s: TOM activated but flag not set", __func__));
12442 		}
12443 
12444 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12445 		if (!uld_active(sc, ULD_IWARP))
12446 			(void) t4_activate_uld(sc, ULD_IWARP);
12447 		if (!uld_active(sc, ULD_ISCSI))
12448 			(void) t4_activate_uld(sc, ULD_ISCSI);
12449 
12450 		pi->uld_vis++;
12451 		setbit(&sc->offload_map, pi->port_id);
12452 	} else {
12453 		pi->uld_vis--;
12454 
12455 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12456 			return (0);
12457 
12458 		KASSERT(uld_active(sc, ULD_TOM),
12459 		    ("%s: TOM never initialized?", __func__));
12460 		clrbit(&sc->offload_map, pi->port_id);
12461 	}
12462 
12463 	return (0);
12464 }
12465 
12466 /*
12467  * Add an upper layer driver to the global list.
12468  */
12469 int
12470 t4_register_uld(struct uld_info *ui, int id)
12471 {
12472 	int rc;
12473 
12474 	if (id < 0 || id > ULD_MAX)
12475 		return (EINVAL);
12476 	sx_xlock(&t4_uld_list_lock);
12477 	if (t4_uld_list[id] != NULL)
12478 		rc = EEXIST;
12479 	else {
12480 		t4_uld_list[id] = ui;
12481 		rc = 0;
12482 	}
12483 	sx_xunlock(&t4_uld_list_lock);
12484 	return (rc);
12485 }
12486 
12487 int
12488 t4_unregister_uld(struct uld_info *ui, int id)
12489 {
12490 
12491 	if (id < 0 || id > ULD_MAX)
12492 		return (EINVAL);
12493 	sx_xlock(&t4_uld_list_lock);
12494 	MPASS(t4_uld_list[id] == ui);
12495 	t4_uld_list[id] = NULL;
12496 	sx_xunlock(&t4_uld_list_lock);
12497 	return (0);
12498 }
12499 
12500 int
12501 t4_activate_uld(struct adapter *sc, int id)
12502 {
12503 	int rc;
12504 
12505 	ASSERT_SYNCHRONIZED_OP(sc);
12506 
12507 	if (id < 0 || id > ULD_MAX)
12508 		return (EINVAL);
12509 
12510 	/* Adapter needs to be initialized before any ULD can be activated. */
12511 	if (!(sc->flags & FULL_INIT_DONE)) {
12512 		rc = adapter_init(sc);
12513 		if (rc != 0)
12514 			return (rc);
12515 	}
12516 
12517 	sx_slock(&t4_uld_list_lock);
12518 	if (t4_uld_list[id] == NULL)
12519 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
12520 	else {
12521 		rc = t4_uld_list[id]->uld_activate(sc);
12522 		if (rc == 0)
12523 			setbit(&sc->active_ulds, id);
12524 	}
12525 	sx_sunlock(&t4_uld_list_lock);
12526 
12527 	return (rc);
12528 }
12529 
12530 int
12531 t4_deactivate_uld(struct adapter *sc, int id)
12532 {
12533 	int rc;
12534 
12535 	ASSERT_SYNCHRONIZED_OP(sc);
12536 
12537 	if (id < 0 || id > ULD_MAX)
12538 		return (EINVAL);
12539 
12540 	sx_slock(&t4_uld_list_lock);
12541 	if (t4_uld_list[id] == NULL)
12542 		rc = ENXIO;
12543 	else {
12544 		rc = t4_uld_list[id]->uld_deactivate(sc);
12545 		if (rc == 0)
12546 			clrbit(&sc->active_ulds, id);
12547 	}
12548 	sx_sunlock(&t4_uld_list_lock);
12549 
12550 	return (rc);
12551 }
12552 
12553 static int
12554 deactivate_all_uld(struct adapter *sc)
12555 {
12556 	int i, rc;
12557 
12558 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12559 	if (rc != 0)
12560 		return (ENXIO);
12561 	sx_slock(&t4_uld_list_lock);
12562 	for (i = 0; i <= ULD_MAX; i++) {
12563 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
12564 			continue;
12565 		rc = t4_uld_list[i]->uld_deactivate(sc);
12566 		if (rc != 0)
12567 			break;
12568 		clrbit(&sc->active_ulds, i);
12569 	}
12570 	sx_sunlock(&t4_uld_list_lock);
12571 	end_synchronized_op(sc, 0);
12572 
12573 	return (rc);
12574 }
12575 
12576 static void
12577 stop_all_uld(struct adapter *sc)
12578 {
12579 	int i;
12580 
12581 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
12582 		return;
12583 	sx_slock(&t4_uld_list_lock);
12584 	for (i = 0; i <= ULD_MAX; i++) {
12585 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12586 		    t4_uld_list[i]->uld_stop == NULL)
12587 			continue;
12588 		(void) t4_uld_list[i]->uld_stop(sc);
12589 	}
12590 	sx_sunlock(&t4_uld_list_lock);
12591 	end_synchronized_op(sc, 0);
12592 }
12593 
12594 static void
12595 restart_all_uld(struct adapter *sc)
12596 {
12597 	int i;
12598 
12599 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
12600 		return;
12601 	sx_slock(&t4_uld_list_lock);
12602 	for (i = 0; i <= ULD_MAX; i++) {
12603 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12604 		    t4_uld_list[i]->uld_restart == NULL)
12605 			continue;
12606 		(void) t4_uld_list[i]->uld_restart(sc);
12607 	}
12608 	sx_sunlock(&t4_uld_list_lock);
12609 	end_synchronized_op(sc, 0);
12610 }
12611 
12612 int
12613 uld_active(struct adapter *sc, int id)
12614 {
12615 
12616 	MPASS(id >= 0 && id <= ULD_MAX);
12617 
12618 	return (isset(&sc->active_ulds, id));
12619 }
12620 #endif
12621 
12622 #ifdef KERN_TLS
12623 static int
12624 ktls_capability(struct adapter *sc, bool enable)
12625 {
12626 	ASSERT_SYNCHRONIZED_OP(sc);
12627 
12628 	if (!is_ktls(sc))
12629 		return (ENODEV);
12630 	if (!is_t6(sc))
12631 		return (0);
12632 	if (hw_off_limits(sc))
12633 		return (ENXIO);
12634 
12635 	if (enable) {
12636 		if (sc->flags & KERN_TLS_ON)
12637 			return (0);	/* already on */
12638 		if (sc->offload_map != 0) {
12639 			CH_WARN(sc,
12640 			    "Disable TOE on all interfaces associated with "
12641 			    "this adapter before trying to enable NIC TLS.\n");
12642 			return (EAGAIN);
12643 		}
12644 		return (t6_config_kern_tls(sc, true));
12645 	} else {
12646 		/*
12647 		 * Nothing to do for disable.  If TOE is enabled sometime later
12648 		 * then toe_capability will reconfigure the hardware.
12649 		 */
12650 		return (0);
12651 	}
12652 }
12653 #endif
12654 
12655 /*
12656  * t  = ptr to tunable.
12657  * nc = number of CPUs.
12658  * c  = compiled in default for that tunable.
12659  */
12660 static void
12661 calculate_nqueues(int *t, int nc, const int c)
12662 {
12663 	int nq;
12664 
12665 	if (*t > 0)
12666 		return;
12667 	nq = *t < 0 ? -*t : c;
12668 	*t = min(nc, nq);
12669 }
12670 
12671 /*
12672  * Come up with reasonable defaults for some of the tunables, provided they're
12673  * not set by the user (in which case we'll use the values as is).
12674  */
12675 static void
12676 tweak_tunables(void)
12677 {
12678 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12679 
12680 	if (t4_ntxq < 1) {
12681 #ifdef RSS
12682 		t4_ntxq = rss_getnumbuckets();
12683 #else
12684 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12685 #endif
12686 	}
12687 
12688 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12689 
12690 	if (t4_nrxq < 1) {
12691 #ifdef RSS
12692 		t4_nrxq = rss_getnumbuckets();
12693 #else
12694 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12695 #endif
12696 	}
12697 
12698 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12699 
12700 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12701 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12702 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12703 #endif
12704 #ifdef TCP_OFFLOAD
12705 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12706 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12707 #endif
12708 
12709 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12710 	if (t4_toecaps_allowed == -1)
12711 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12712 #else
12713 	if (t4_toecaps_allowed == -1)
12714 		t4_toecaps_allowed = 0;
12715 #endif
12716 
12717 #ifdef TCP_OFFLOAD
12718 	if (t4_rdmacaps_allowed == -1) {
12719 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12720 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12721 	}
12722 
12723 	if (t4_iscsicaps_allowed == -1) {
12724 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12725 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12726 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12727 	}
12728 
12729 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12730 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12731 
12732 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12733 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12734 #else
12735 	if (t4_rdmacaps_allowed == -1)
12736 		t4_rdmacaps_allowed = 0;
12737 
12738 	if (t4_iscsicaps_allowed == -1)
12739 		t4_iscsicaps_allowed = 0;
12740 #endif
12741 
12742 #ifdef DEV_NETMAP
12743 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12744 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12745 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12746 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12747 #endif
12748 
12749 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12750 		t4_tmr_idx = TMR_IDX;
12751 
12752 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12753 		t4_pktc_idx = PKTC_IDX;
12754 
12755 	if (t4_qsize_txq < 128)
12756 		t4_qsize_txq = 128;
12757 
12758 	if (t4_qsize_rxq < 128)
12759 		t4_qsize_rxq = 128;
12760 	while (t4_qsize_rxq & 7)
12761 		t4_qsize_rxq++;
12762 
12763 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12764 
12765 	/*
12766 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12767 	 * VI for the port.  The rest are additional virtual interfaces on the
12768 	 * same physical port.  Note that the main VI does not have native
12769 	 * netmap support but the extra VIs do.
12770 	 *
12771 	 * Limit the number of VIs per port to the number of available
12772 	 * MAC addresses per port.
12773 	 */
12774 	if (t4_num_vis < 1)
12775 		t4_num_vis = 1;
12776 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12777 		t4_num_vis = nitems(vi_mac_funcs);
12778 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12779 	}
12780 
12781 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12782 		pcie_relaxed_ordering = 1;
12783 #if defined(__i386__) || defined(__amd64__)
12784 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12785 			pcie_relaxed_ordering = 0;
12786 #endif
12787 	}
12788 }
12789 
12790 #ifdef DDB
12791 static void
12792 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
12793 {
12794 	uint32_t base, j, off, pf, reg, save, win_pos;
12795 
12796 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12797 	save = t4_read_reg(sc, reg);
12798 	base = sc->memwin[2].mw_base;
12799 
12800 	if (is_t4(sc)) {
12801 		pf = 0;
12802 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
12803 	} else {
12804 		pf = V_PFNUM(sc->pf);
12805 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
12806 	}
12807 	off = addr - win_pos;
12808 	t4_write_reg(sc, reg, win_pos | pf);
12809 	t4_read_reg(sc, reg);
12810 
12811 	while (len > 0 && !db_pager_quit) {
12812 		uint32_t buf[8];
12813 		for (j = 0; j < 8; j++, off += 4)
12814 			buf[j] = htonl(t4_read_reg(sc, base + off));
12815 
12816 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12817 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12818 		    buf[7]);
12819 		if (len <= sizeof(buf))
12820 			len = 0;
12821 		else
12822 			len -= sizeof(buf);
12823 	}
12824 
12825 	t4_write_reg(sc, reg, save);
12826 	t4_read_reg(sc, reg);
12827 }
12828 
12829 static void
12830 t4_dump_tcb(struct adapter *sc, int tid)
12831 {
12832 	uint32_t tcb_addr;
12833 
12834 	/* Dump TCB for the tid */
12835 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12836 	tcb_addr += tid * TCB_SIZE;
12837 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
12838 }
12839 
12840 static void
12841 t4_dump_devlog(struct adapter *sc)
12842 {
12843 	struct devlog_params *dparams = &sc->params.devlog;
12844 	struct fw_devlog_e e;
12845 	int i, first, j, m, nentries, rc;
12846 	uint64_t ftstamp = UINT64_MAX;
12847 
12848 	if (dparams->start == 0) {
12849 		db_printf("devlog params not valid\n");
12850 		return;
12851 	}
12852 
12853 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12854 	m = fwmtype_to_hwmtype(dparams->memtype);
12855 
12856 	/* Find the first entry. */
12857 	first = -1;
12858 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12859 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12860 		    sizeof(e), (void *)&e);
12861 		if (rc != 0)
12862 			break;
12863 
12864 		if (e.timestamp == 0)
12865 			break;
12866 
12867 		e.timestamp = be64toh(e.timestamp);
12868 		if (e.timestamp < ftstamp) {
12869 			ftstamp = e.timestamp;
12870 			first = i;
12871 		}
12872 	}
12873 
12874 	if (first == -1)
12875 		return;
12876 
12877 	i = first;
12878 	do {
12879 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12880 		    sizeof(e), (void *)&e);
12881 		if (rc != 0)
12882 			return;
12883 
12884 		if (e.timestamp == 0)
12885 			return;
12886 
12887 		e.timestamp = be64toh(e.timestamp);
12888 		e.seqno = be32toh(e.seqno);
12889 		for (j = 0; j < 8; j++)
12890 			e.params[j] = be32toh(e.params[j]);
12891 
12892 		db_printf("%10d  %15ju  %8s  %8s  ",
12893 		    e.seqno, e.timestamp,
12894 		    (e.level < nitems(devlog_level_strings) ?
12895 			devlog_level_strings[e.level] : "UNKNOWN"),
12896 		    (e.facility < nitems(devlog_facility_strings) ?
12897 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12898 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12899 		    e.params[3], e.params[4], e.params[5], e.params[6],
12900 		    e.params[7]);
12901 
12902 		if (++i == nentries)
12903 			i = 0;
12904 	} while (i != first && !db_pager_quit);
12905 }
12906 
12907 static DB_DEFINE_TABLE(show, t4, show_t4);
12908 
12909 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12910 {
12911 	device_t dev;
12912 	int t;
12913 	bool valid;
12914 
12915 	valid = false;
12916 	t = db_read_token();
12917 	if (t == tIDENT) {
12918 		dev = device_lookup_by_name(db_tok_string);
12919 		valid = true;
12920 	}
12921 	db_skip_to_eol();
12922 	if (!valid) {
12923 		db_printf("usage: show t4 devlog <nexus>\n");
12924 		return;
12925 	}
12926 
12927 	if (dev == NULL) {
12928 		db_printf("device not found\n");
12929 		return;
12930 	}
12931 
12932 	t4_dump_devlog(device_get_softc(dev));
12933 }
12934 
12935 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12936 {
12937 	device_t dev;
12938 	int radix, tid, t;
12939 	bool valid;
12940 
12941 	valid = false;
12942 	radix = db_radix;
12943 	db_radix = 10;
12944 	t = db_read_token();
12945 	if (t == tIDENT) {
12946 		dev = device_lookup_by_name(db_tok_string);
12947 		t = db_read_token();
12948 		if (t == tNUMBER) {
12949 			tid = db_tok_number;
12950 			valid = true;
12951 		}
12952 	}
12953 	db_radix = radix;
12954 	db_skip_to_eol();
12955 	if (!valid) {
12956 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12957 		return;
12958 	}
12959 
12960 	if (dev == NULL) {
12961 		db_printf("device not found\n");
12962 		return;
12963 	}
12964 	if (tid < 0) {
12965 		db_printf("invalid tid\n");
12966 		return;
12967 	}
12968 
12969 	t4_dump_tcb(device_get_softc(dev), tid);
12970 }
12971 
12972 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
12973 {
12974 	device_t dev;
12975 	int radix, t;
12976 	bool valid;
12977 
12978 	valid = false;
12979 	radix = db_radix;
12980 	db_radix = 10;
12981 	t = db_read_token();
12982 	if (t == tIDENT) {
12983 		dev = device_lookup_by_name(db_tok_string);
12984 		t = db_read_token();
12985 		if (t == tNUMBER) {
12986 			addr = db_tok_number;
12987 			t = db_read_token();
12988 			if (t == tNUMBER) {
12989 				count = db_tok_number;
12990 				valid = true;
12991 			}
12992 		}
12993 	}
12994 	db_radix = radix;
12995 	db_skip_to_eol();
12996 	if (!valid) {
12997 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
12998 		return;
12999 	}
13000 
13001 	if (dev == NULL) {
13002 		db_printf("device not found\n");
13003 		return;
13004 	}
13005 	if (addr < 0) {
13006 		db_printf("invalid address\n");
13007 		return;
13008 	}
13009 	if (count <= 0) {
13010 		db_printf("invalid length\n");
13011 		return;
13012 	}
13013 
13014 	t4_dump_mem(device_get_softc(dev), addr, count);
13015 }
13016 #endif
13017 
13018 static eventhandler_tag vxlan_start_evtag;
13019 static eventhandler_tag vxlan_stop_evtag;
13020 
13021 struct vxlan_evargs {
13022 	if_t ifp;
13023 	uint16_t port;
13024 };
13025 
13026 static void
13027 enable_vxlan_rx(struct adapter *sc)
13028 {
13029 	int i, rc;
13030 	struct port_info *pi;
13031 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13032 
13033 	ASSERT_SYNCHRONIZED_OP(sc);
13034 
13035 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13036 	    F_VXLAN_EN);
13037 	for_each_port(sc, i) {
13038 		pi = sc->port[i];
13039 		if (pi->vxlan_tcam_entry == true)
13040 			continue;
13041 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13042 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13043 		    true);
13044 		if (rc < 0) {
13045 			rc = -rc;
13046 			CH_ERR(&pi->vi[0],
13047 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13048 		} else {
13049 			MPASS(rc == sc->rawf_base + pi->port_id);
13050 			pi->vxlan_tcam_entry = true;
13051 		}
13052 	}
13053 }
13054 
13055 static void
13056 t4_vxlan_start(struct adapter *sc, void *arg)
13057 {
13058 	struct vxlan_evargs *v = arg;
13059 
13060 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13061 		return;
13062 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13063 		return;
13064 
13065 	if (sc->vxlan_refcount == 0) {
13066 		sc->vxlan_port = v->port;
13067 		sc->vxlan_refcount = 1;
13068 		if (!hw_off_limits(sc))
13069 			enable_vxlan_rx(sc);
13070 	} else if (sc->vxlan_port == v->port) {
13071 		sc->vxlan_refcount++;
13072 	} else {
13073 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13074 		    "ignoring attempt to configure it on port %d\n",
13075 		    sc->vxlan_port, v->port);
13076 	}
13077 	end_synchronized_op(sc, 0);
13078 }
13079 
13080 static void
13081 t4_vxlan_stop(struct adapter *sc, void *arg)
13082 {
13083 	struct vxlan_evargs *v = arg;
13084 
13085 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13086 		return;
13087 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13088 		return;
13089 
13090 	/*
13091 	 * VXLANs may have been configured before the driver was loaded so we
13092 	 * may see more stops than starts.  This is not handled cleanly but at
13093 	 * least we keep the refcount sane.
13094 	 */
13095 	if (sc->vxlan_port != v->port)
13096 		goto done;
13097 	if (sc->vxlan_refcount == 0) {
13098 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13099 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13100 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13101 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13102 done:
13103 	end_synchronized_op(sc, 0);
13104 }
13105 
13106 static void
13107 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13108     sa_family_t family, u_int port)
13109 {
13110 	struct vxlan_evargs v;
13111 
13112 	MPASS(family == AF_INET || family == AF_INET6);
13113 	v.ifp = ifp;
13114 	v.port = port;
13115 
13116 	t4_iterate(t4_vxlan_start, &v);
13117 }
13118 
13119 static void
13120 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13121     u_int port)
13122 {
13123 	struct vxlan_evargs v;
13124 
13125 	MPASS(family == AF_INET || family == AF_INET6);
13126 	v.ifp = ifp;
13127 	v.port = port;
13128 
13129 	t4_iterate(t4_vxlan_stop, &v);
13130 }
13131 
13132 
13133 static struct sx mlu;	/* mod load unload */
13134 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13135 
13136 static int
13137 mod_event(module_t mod, int cmd, void *arg)
13138 {
13139 	int rc = 0;
13140 	static int loaded = 0;
13141 
13142 	switch (cmd) {
13143 	case MOD_LOAD:
13144 		sx_xlock(&mlu);
13145 		if (loaded++ == 0) {
13146 			t4_sge_modload();
13147 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13148 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13149 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13150 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13151 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13152 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13153 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13154 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13155 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13156 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13157 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13158 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13159 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13160 			    do_smt_write_rpl);
13161 			sx_init(&t4_list_lock, "T4/T5 adapters");
13162 			SLIST_INIT(&t4_list);
13163 			callout_init(&fatal_callout, 1);
13164 #ifdef TCP_OFFLOAD
13165 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13166 #endif
13167 #ifdef INET6
13168 			t4_clip_modload();
13169 #endif
13170 #ifdef KERN_TLS
13171 			t6_ktls_modload();
13172 #endif
13173 			t4_tracer_modload();
13174 			tweak_tunables();
13175 			vxlan_start_evtag =
13176 			    EVENTHANDLER_REGISTER(vxlan_start,
13177 				t4_vxlan_start_handler, NULL,
13178 				EVENTHANDLER_PRI_ANY);
13179 			vxlan_stop_evtag =
13180 			    EVENTHANDLER_REGISTER(vxlan_stop,
13181 				t4_vxlan_stop_handler, NULL,
13182 				EVENTHANDLER_PRI_ANY);
13183 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13184 			    taskqueue_thread_enqueue, &reset_tq);
13185 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13186 			    "t4_rst_thr");
13187 		}
13188 		sx_xunlock(&mlu);
13189 		break;
13190 
13191 	case MOD_UNLOAD:
13192 		sx_xlock(&mlu);
13193 		if (--loaded == 0) {
13194 #ifdef TCP_OFFLOAD
13195 			int i;
13196 #endif
13197 			int tries;
13198 
13199 			taskqueue_free(reset_tq);
13200 
13201 			tries = 0;
13202 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13203 				uprintf("%ju clusters with custom free routine "
13204 				    "still is use.\n", t4_sge_extfree_refs());
13205 				pause("t4unload", 2 * hz);
13206 			}
13207 
13208 			sx_slock(&t4_list_lock);
13209 			if (!SLIST_EMPTY(&t4_list)) {
13210 				rc = EBUSY;
13211 				sx_sunlock(&t4_list_lock);
13212 				goto done_unload;
13213 			}
13214 #ifdef TCP_OFFLOAD
13215 			sx_slock(&t4_uld_list_lock);
13216 			for (i = 0; i <= ULD_MAX; i++) {
13217 				if (t4_uld_list[i] != NULL) {
13218 					rc = EBUSY;
13219 					sx_sunlock(&t4_uld_list_lock);
13220 					sx_sunlock(&t4_list_lock);
13221 					goto done_unload;
13222 				}
13223 			}
13224 			sx_sunlock(&t4_uld_list_lock);
13225 #endif
13226 			sx_sunlock(&t4_list_lock);
13227 
13228 			if (t4_sge_extfree_refs() == 0) {
13229 				EVENTHANDLER_DEREGISTER(vxlan_start,
13230 				    vxlan_start_evtag);
13231 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13232 				    vxlan_stop_evtag);
13233 				t4_tracer_modunload();
13234 #ifdef KERN_TLS
13235 				t6_ktls_modunload();
13236 #endif
13237 #ifdef INET6
13238 				t4_clip_modunload();
13239 #endif
13240 #ifdef TCP_OFFLOAD
13241 				sx_destroy(&t4_uld_list_lock);
13242 #endif
13243 				sx_destroy(&t4_list_lock);
13244 				t4_sge_modunload();
13245 				loaded = 0;
13246 			} else {
13247 				rc = EBUSY;
13248 				loaded++;	/* undo earlier decrement */
13249 			}
13250 		}
13251 done_unload:
13252 		sx_xunlock(&mlu);
13253 		break;
13254 	}
13255 
13256 	return (rc);
13257 }
13258 
13259 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13260 MODULE_VERSION(t4nex, 1);
13261 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13262 #ifdef DEV_NETMAP
13263 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13264 #endif /* DEV_NETMAP */
13265 
13266 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13267 MODULE_VERSION(t5nex, 1);
13268 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13269 #ifdef DEV_NETMAP
13270 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13271 #endif /* DEV_NETMAP */
13272 
13273 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13274 MODULE_VERSION(t6nex, 1);
13275 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13276 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13277 #ifdef DEV_NETMAP
13278 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13279 #endif /* DEV_NETMAP */
13280 
13281 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13282 MODULE_VERSION(cxgbe, 1);
13283 
13284 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13285 MODULE_VERSION(cxl, 1);
13286 
13287 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13288 MODULE_VERSION(cc, 1);
13289 
13290 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13291 MODULE_VERSION(vcxgbe, 1);
13292 
13293 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13294 MODULE_VERSION(vcxl, 1);
13295 
13296 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13297 MODULE_VERSION(vcc, 1);
13298