xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 00460cc8c5ad02b628e81eec9e493a1df8393d36)
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 SLIST_HEAD(, uld_info) t4_uld_list;
267 #endif
268 
269 /*
270  * Tunables.  See tweak_tunables() too.
271  *
272  * Each tunable is set to a default value here if it's known at compile-time.
273  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274  * provide a reasonable default (upto n) when the driver is loaded.
275  *
276  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277  * T5 are under hw.cxl.
278  */
279 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280     "cxgbe(4) parameters");
281 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) T5+ parameters");
283 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) TOE parameters");
285 
286 /*
287  * Number of queues for tx and rx, NIC and offload.
288  */
289 #define NTXQ 16
290 int t4_ntxq = -NTXQ;
291 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292     "Number of TX queues per port");
293 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294 
295 #define NRXQ 8
296 int t4_nrxq = -NRXQ;
297 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298     "Number of RX queues per port");
299 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300 
301 #define NTXQ_VI 1
302 static int t4_ntxq_vi = -NTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304     "Number of TX queues per VI");
305 
306 #define NRXQ_VI 1
307 static int t4_nrxq_vi = -NRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309     "Number of RX queues per VI");
310 
311 static int t4_rsrv_noflowq = 0;
312 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313     0, "Reserve TX queue 0 of each VI for non-flowid packets");
314 
315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316 #define NOFLDTXQ 8
317 static int t4_nofldtxq = -NOFLDTXQ;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319     "Number of offload TX queues per port");
320 
321 #define NOFLDRXQ 2
322 static int t4_nofldrxq = -NOFLDRXQ;
323 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324     "Number of offload RX queues per port");
325 
326 #define NOFLDTXQ_VI 1
327 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329     "Number of offload TX queues per VI");
330 
331 #define NOFLDRXQ_VI 1
332 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334     "Number of offload RX queues per VI");
335 
336 #define TMR_IDX_OFLD 1
337 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340 
341 #define PKTC_IDX_OFLD (-1)
342 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345 
346 /* 0 means chip/fw default, non-zero number is value in microseconds */
347 static u_long t4_toe_keepalive_idle = 0;
348 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350 
351 /* 0 means chip/fw default, non-zero number is value in microseconds */
352 static u_long t4_toe_keepalive_interval = 0;
353 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355 
356 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357 static int t4_toe_keepalive_count = 0;
358 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360 
361 /* 0 means chip/fw default, non-zero number is value in microseconds */
362 static u_long t4_toe_rexmt_min = 0;
363 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365 
366 /* 0 means chip/fw default, non-zero number is value in microseconds */
367 static u_long t4_toe_rexmt_max = 0;
368 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370 
371 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372 static int t4_toe_rexmt_count = 0;
373 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375 
376 /* -1 means chip/fw default, other values are raw backoff values to use */
377 static int t4_toe_rexmt_backoff[16] = {
378 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379 };
380 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382     "cxgbe(4) TOE retransmit backoff values");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[0], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[1], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[2], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[3], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[4], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[5], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[6], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[7], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[8], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[9], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[10], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[11], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[12], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[13], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[14], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[15], 0, "");
415 
416 int t4_ddp_rcvbuf_len = 256 * 1024;
417 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
418     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
419 
420 unsigned int t4_ddp_rcvbuf_cache = 4;
421 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
422     &t4_ddp_rcvbuf_cache, 0,
423     "maximum number of free DDP RX buffers to cache per connection");
424 #endif
425 
426 #ifdef DEV_NETMAP
427 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
428 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
429 static int t4_native_netmap = NN_EXTRA_VI;
430 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
431     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
432 
433 #define NNMTXQ 8
434 static int t4_nnmtxq = -NNMTXQ;
435 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
436     "Number of netmap TX queues");
437 
438 #define NNMRXQ 8
439 static int t4_nnmrxq = -NNMRXQ;
440 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
441     "Number of netmap RX queues");
442 
443 #define NNMTXQ_VI 2
444 static int t4_nnmtxq_vi = -NNMTXQ_VI;
445 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
446     "Number of netmap TX queues per VI");
447 
448 #define NNMRXQ_VI 2
449 static int t4_nnmrxq_vi = -NNMRXQ_VI;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
451     "Number of netmap RX queues per VI");
452 #endif
453 
454 /*
455  * Holdoff parameters for ports.
456  */
457 #define TMR_IDX 1
458 int t4_tmr_idx = TMR_IDX;
459 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
460     0, "Holdoff timer index");
461 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
462 
463 #define PKTC_IDX (-1)
464 int t4_pktc_idx = PKTC_IDX;
465 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
466     0, "Holdoff packet counter index");
467 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
468 
469 /*
470  * Size (# of entries) of each tx and rx queue.
471  */
472 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
473 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
474     "Number of descriptors in each TX queue");
475 
476 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
477 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
478     "Number of descriptors in each RX queue");
479 
480 /*
481  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
482  */
483 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
485     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
486 
487 /*
488  * Configuration file.  All the _CF names here are special.
489  */
490 #define DEFAULT_CF	"default"
491 #define BUILTIN_CF	"built-in"
492 #define FLASH_CF	"flash"
493 #define UWIRE_CF	"uwire"
494 #define FPGA_CF		"fpga"
495 static char t4_cfg_file[32] = DEFAULT_CF;
496 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
497     sizeof(t4_cfg_file), "Firmware configuration file");
498 
499 /*
500  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
501  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
502  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
503  *            mark or when signalled to do so, 0 to never emit PAUSE.
504  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
505  *                 negotiated settings will override rx_pause/tx_pause.
506  *                 Otherwise rx_pause/tx_pause are applied forcibly.
507  */
508 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
509 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
510     &t4_pause_settings, 0,
511     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
512 
513 /*
514  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
515  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
516  *  0 to disable FEC.
517  */
518 static int t4_fec = -1;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
520     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
521 
522 /*
523  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
524  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
525  * driver runs as if this is set to 0.
526  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
527  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
528  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
529  *    the firmware anyway (may result in l1cfg errors with old firmwares).
530  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
531  *    means set all FEC bits that are valid for the speed.
532  */
533 static int t4_force_fec = -1;
534 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
535     "Controls the use of FORCE_FEC bit in L1 configuration.");
536 
537 /*
538  * Link autonegotiation.
539  * -1 to run with the firmware default.
540  *  0 to disable.
541  *  1 to enable.
542  */
543 static int t4_autoneg = -1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
545     "Link autonegotiation");
546 
547 /*
548  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
549  * encouraged respectively).  '-n' is the same as 'n' except the firmware
550  * version used in the checks is read from the firmware bundled with the driver.
551  */
552 static int t4_fw_install = 1;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
554     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
555 
556 /*
557  * ASIC features that will be used.  Disable the ones you don't want so that the
558  * chip resources aren't wasted on features that will not be used.
559  */
560 static int t4_nbmcaps_allowed = 0;
561 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
562     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
563 
564 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
565 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
566     &t4_linkcaps_allowed, 0, "Default link capabilities");
567 
568 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
569     FW_CAPS_CONFIG_SWITCH_EGRESS;
570 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
571     &t4_switchcaps_allowed, 0, "Default switch capabilities");
572 
573 #ifdef RATELIMIT
574 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
575 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
576 #else
577 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
578 	FW_CAPS_CONFIG_NIC_HASHFILTER;
579 #endif
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
581     &t4_niccaps_allowed, 0, "Default NIC capabilities");
582 
583 static int t4_toecaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
585     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
586 
587 static int t4_rdmacaps_allowed = -1;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
589     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
590 
591 static int t4_cryptocaps_allowed = -1;
592 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
593     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
594 
595 static int t4_iscsicaps_allowed = -1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
597     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
598 
599 static int t4_fcoecaps_allowed = 0;
600 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
601     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
602 
603 static int t5_write_combine = 0;
604 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
605     0, "Use WC instead of UC for BAR2");
606 
607 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
608 static int t4_doorbells_allowed = 0xf;
609 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
610 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
611 
612 static int t4_num_vis = 1;
613 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
614     "Number of VIs per port");
615 
616 /*
617  * PCIe Relaxed Ordering.
618  * -1: driver should figure out a good value.
619  * 0: disable RO.
620  * 1: enable RO.
621  * 2: leave RO alone.
622  */
623 static int pcie_relaxed_ordering = -1;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
625     &pcie_relaxed_ordering, 0,
626     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
627 
628 static int t4_panic_on_fatal_err = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
630     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
631 
632 static int t4_reset_on_fatal_err = 0;
633 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
634     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
635 
636 static int t4_clock_gate_on_suspend = 0;
637 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
638     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
639 
640 static int t4_tx_vm_wr = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
642     "Use VM work requests to transmit packets.");
643 
644 /*
645  * Set to non-zero to enable the attack filter.  A packet that matches any of
646  * these conditions will get dropped on ingress:
647  * 1) IP && source address == destination address.
648  * 2) TCP/IP && source address is not a unicast address.
649  * 3) TCP/IP && destination address is not a unicast address.
650  * 4) IP && source address is loopback (127.x.y.z).
651  * 5) IP && destination address is loopback (127.x.y.z).
652  * 6) IPv6 && source address == destination address.
653  * 7) IPv6 && source address is not a unicast address.
654  * 8) IPv6 && source address is loopback (::1/128).
655  * 9) IPv6 && destination address is loopback (::1/128).
656  * 10) IPv6 && source address is unspecified (::/128).
657  * 11) IPv6 && destination address is unspecified (::/128).
658  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
659  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
660  */
661 static int t4_attack_filter = 0;
662 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
663     &t4_attack_filter, 0, "Drop suspicious traffic");
664 
665 static int t4_drop_ip_fragments = 0;
666 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
667     &t4_drop_ip_fragments, 0, "Drop IP fragments");
668 
669 static int t4_drop_pkts_with_l2_errors = 1;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
671     &t4_drop_pkts_with_l2_errors, 0,
672     "Drop all frames with Layer 2 length or checksum errors");
673 
674 static int t4_drop_pkts_with_l3_errors = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l3_errors, 0,
677     "Drop all frames with IP version, length, or checksum errors");
678 
679 static int t4_drop_pkts_with_l4_errors = 0;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
681     &t4_drop_pkts_with_l4_errors, 0,
682     "Drop all frames with Layer 4 length, checksum, or other errors");
683 
684 #ifdef TCP_OFFLOAD
685 /*
686  * TOE tunables.
687  */
688 static int t4_cop_managed_offloading = 0;
689 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
690     &t4_cop_managed_offloading, 0,
691     "COP (Connection Offload Policy) controls all TOE offload");
692 #endif
693 
694 #ifdef KERN_TLS
695 /*
696  * This enables KERN_TLS for all adapters if set.
697  */
698 static int t4_kern_tls = 0;
699 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
700     "Enable KERN_TLS mode for T6 adapters");
701 
702 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
703     "cxgbe(4) KERN_TLS parameters");
704 
705 static int t4_tls_inline_keys = 0;
706 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
707     &t4_tls_inline_keys, 0,
708     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
709     "in card memory.");
710 
711 static int t4_tls_combo_wrs = 0;
712 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
713     0, "Attempt to combine TCB field updates with TLS record work requests.");
714 #endif
715 
716 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
717 static int vi_mac_funcs[] = {
718 	FW_VI_FUNC_ETH,
719 	FW_VI_FUNC_OFLD,
720 	FW_VI_FUNC_IWARP,
721 	FW_VI_FUNC_OPENISCSI,
722 	FW_VI_FUNC_OPENFCOE,
723 	FW_VI_FUNC_FOISCSI,
724 	FW_VI_FUNC_FOFCOE,
725 };
726 
727 struct intrs_and_queues {
728 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
729 	uint16_t num_vis;	/* number of VIs for each port */
730 	uint16_t nirq;		/* Total # of vectors */
731 	uint16_t ntxq;		/* # of NIC txq's for each port */
732 	uint16_t nrxq;		/* # of NIC rxq's for each port */
733 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
734 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
735 	uint16_t nnmtxq;	/* # of netmap txq's */
736 	uint16_t nnmrxq;	/* # of netmap rxq's */
737 
738 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
739 	uint16_t ntxq_vi;	/* # of NIC txq's */
740 	uint16_t nrxq_vi;	/* # of NIC rxq's */
741 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
742 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
743 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
744 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
745 };
746 
747 static void setup_memwin(struct adapter *);
748 static void position_memwin(struct adapter *, int, uint32_t);
749 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
750 static int fwmtype_to_hwmtype(int);
751 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
752     uint32_t *);
753 static int fixup_devlog_params(struct adapter *);
754 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
755 static int contact_firmware(struct adapter *);
756 static int partition_resources(struct adapter *);
757 static int get_params__pre_init(struct adapter *);
758 static int set_params__pre_init(struct adapter *);
759 static int get_params__post_init(struct adapter *);
760 static int set_params__post_init(struct adapter *);
761 static void t4_set_desc(struct adapter *);
762 static bool fixed_ifmedia(struct port_info *);
763 static void build_medialist(struct port_info *);
764 static void init_link_config(struct port_info *);
765 static int fixup_link_config(struct port_info *);
766 static int apply_link_config(struct port_info *);
767 static int cxgbe_init_synchronized(struct vi_info *);
768 static int cxgbe_uninit_synchronized(struct vi_info *);
769 static int adapter_full_init(struct adapter *);
770 static void adapter_full_uninit(struct adapter *);
771 static int vi_full_init(struct vi_info *);
772 static void vi_full_uninit(struct vi_info *);
773 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
774 static void quiesce_txq(struct sge_txq *);
775 static void quiesce_wrq(struct sge_wrq *);
776 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
777 static void quiesce_vi(struct vi_info *);
778 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
779     driver_intr_t *, void *, char *);
780 static int t4_free_irq(struct adapter *, struct irq *);
781 static void t4_init_atid_table(struct adapter *);
782 static void t4_free_atid_table(struct adapter *);
783 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
784 static void vi_refresh_stats(struct vi_info *);
785 static void cxgbe_refresh_stats(struct vi_info *);
786 static void cxgbe_tick(void *);
787 static void vi_tick(void *);
788 static void cxgbe_sysctls(struct port_info *);
789 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
790 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
791 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
792 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
793 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
794 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
795 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
796 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
797 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
798 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
799 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
800 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
801 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
802 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
803 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
804 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
805 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
806 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
807 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
808 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
809 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
810 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
811 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
812 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
813 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
814 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
817 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
820 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
822 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
824 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
825 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
826 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
827 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
828 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
829 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
830 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
831 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
837 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
838 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
839 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
840 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
841 #ifdef TCP_OFFLOAD
842 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
843 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
844 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
845 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
846 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
847 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
848 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
849 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
850 #endif
851 static int get_sge_context(struct adapter *, struct t4_sge_context *);
852 static int load_fw(struct adapter *, struct t4_data *);
853 static int load_cfg(struct adapter *, struct t4_data *);
854 static int load_boot(struct adapter *, struct t4_bootrom *);
855 static int load_bootcfg(struct adapter *, struct t4_data *);
856 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
857 static void free_offload_policy(struct t4_offload_policy *);
858 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
859 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
860 static int read_i2c(struct adapter *, struct t4_i2c_data *);
861 static int clear_stats(struct adapter *, u_int);
862 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
863 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
864 #ifdef TCP_OFFLOAD
865 static int toe_capability(struct vi_info *, bool);
866 static int t4_deactivate_all_uld(struct adapter *);
867 static void t4_async_event(struct adapter *);
868 #endif
869 #ifdef KERN_TLS
870 static int ktls_capability(struct adapter *, bool);
871 #endif
872 static int mod_event(module_t, int, void *);
873 static int notify_siblings(device_t, int);
874 static uint64_t vi_get_counter(if_t, ift_counter);
875 static uint64_t cxgbe_get_counter(if_t, ift_counter);
876 static void enable_vxlan_rx(struct adapter *);
877 static void reset_adapter_task(void *, int);
878 static void fatal_error_task(void *, int);
879 static void dump_devlog(struct adapter *);
880 static void dump_cim_regs(struct adapter *);
881 static void dump_cimla(struct adapter *);
882 
883 struct {
884 	uint16_t device;
885 	char *desc;
886 } t4_pciids[] = {
887 	{0xa000, "Chelsio Terminator 4 FPGA"},
888 	{0x4400, "Chelsio T440-dbg"},
889 	{0x4401, "Chelsio T420-CR"},
890 	{0x4402, "Chelsio T422-CR"},
891 	{0x4403, "Chelsio T440-CR"},
892 	{0x4404, "Chelsio T420-BCH"},
893 	{0x4405, "Chelsio T440-BCH"},
894 	{0x4406, "Chelsio T440-CH"},
895 	{0x4407, "Chelsio T420-SO"},
896 	{0x4408, "Chelsio T420-CX"},
897 	{0x4409, "Chelsio T420-BT"},
898 	{0x440a, "Chelsio T404-BT"},
899 	{0x440e, "Chelsio T440-LP-CR"},
900 }, t5_pciids[] = {
901 	{0xb000, "Chelsio Terminator 5 FPGA"},
902 	{0x5400, "Chelsio T580-dbg"},
903 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
904 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
905 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
906 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
907 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
908 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
909 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
910 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
911 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
912 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
913 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
914 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
915 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
916 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
917 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
918 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
919 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
920 
921 	/* Custom */
922 	{0x5483, "Custom T540-CR"},
923 	{0x5484, "Custom T540-BT"},
924 }, t6_pciids[] = {
925 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
926 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
927 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
928 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
929 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
930 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
931 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
932 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
933 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
934 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
935 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
936 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
937 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
938 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
939 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
940 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
941 
942 	/* Custom */
943 	{0x6480, "Custom T6225-CR"},
944 	{0x6481, "Custom T62100-CR"},
945 	{0x6482, "Custom T6225-CR"},
946 	{0x6483, "Custom T62100-CR"},
947 	{0x6484, "Custom T64100-CR"},
948 	{0x6485, "Custom T6240-SO"},
949 	{0x6486, "Custom T6225-SO-CR"},
950 	{0x6487, "Custom T6225-CR"},
951 };
952 
953 #ifdef TCP_OFFLOAD
954 /*
955  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
956  * be exactly the same for both rxq and ofld_rxq.
957  */
958 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
959 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
960 #endif
961 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
962 
963 static int
964 t4_probe(device_t dev)
965 {
966 	int i;
967 	uint16_t v = pci_get_vendor(dev);
968 	uint16_t d = pci_get_device(dev);
969 	uint8_t f = pci_get_function(dev);
970 
971 	if (v != PCI_VENDOR_ID_CHELSIO)
972 		return (ENXIO);
973 
974 	/* Attach only to PF0 of the FPGA */
975 	if (d == 0xa000 && f != 0)
976 		return (ENXIO);
977 
978 	for (i = 0; i < nitems(t4_pciids); i++) {
979 		if (d == t4_pciids[i].device) {
980 			device_set_desc(dev, t4_pciids[i].desc);
981 			return (BUS_PROBE_DEFAULT);
982 		}
983 	}
984 
985 	return (ENXIO);
986 }
987 
988 static int
989 t5_probe(device_t dev)
990 {
991 	int i;
992 	uint16_t v = pci_get_vendor(dev);
993 	uint16_t d = pci_get_device(dev);
994 	uint8_t f = pci_get_function(dev);
995 
996 	if (v != PCI_VENDOR_ID_CHELSIO)
997 		return (ENXIO);
998 
999 	/* Attach only to PF0 of the FPGA */
1000 	if (d == 0xb000 && f != 0)
1001 		return (ENXIO);
1002 
1003 	for (i = 0; i < nitems(t5_pciids); i++) {
1004 		if (d == t5_pciids[i].device) {
1005 			device_set_desc(dev, t5_pciids[i].desc);
1006 			return (BUS_PROBE_DEFAULT);
1007 		}
1008 	}
1009 
1010 	return (ENXIO);
1011 }
1012 
1013 static int
1014 t6_probe(device_t dev)
1015 {
1016 	int i;
1017 	uint16_t v = pci_get_vendor(dev);
1018 	uint16_t d = pci_get_device(dev);
1019 
1020 	if (v != PCI_VENDOR_ID_CHELSIO)
1021 		return (ENXIO);
1022 
1023 	for (i = 0; i < nitems(t6_pciids); i++) {
1024 		if (d == t6_pciids[i].device) {
1025 			device_set_desc(dev, t6_pciids[i].desc);
1026 			return (BUS_PROBE_DEFAULT);
1027 		}
1028 	}
1029 
1030 	return (ENXIO);
1031 }
1032 
1033 static void
1034 t5_attribute_workaround(device_t dev)
1035 {
1036 	device_t root_port;
1037 	uint32_t v;
1038 
1039 	/*
1040 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1041 	 * Ordering attributes when replying to a TLP from a Root
1042 	 * Port.  As a workaround, find the parent Root Port and
1043 	 * disable No Snoop and Relaxed Ordering.  Note that this
1044 	 * affects all devices under this root port.
1045 	 */
1046 	root_port = pci_find_pcie_root_port(dev);
1047 	if (root_port == NULL) {
1048 		device_printf(dev, "Unable to find parent root port\n");
1049 		return;
1050 	}
1051 
1052 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1053 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1054 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1055 	    0)
1056 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1057 		    device_get_nameunit(root_port));
1058 }
1059 
1060 static const struct devnames devnames[] = {
1061 	{
1062 		.nexus_name = "t4nex",
1063 		.ifnet_name = "cxgbe",
1064 		.vi_ifnet_name = "vcxgbe",
1065 		.pf03_drv_name = "t4iov",
1066 		.vf_nexus_name = "t4vf",
1067 		.vf_ifnet_name = "cxgbev"
1068 	}, {
1069 		.nexus_name = "t5nex",
1070 		.ifnet_name = "cxl",
1071 		.vi_ifnet_name = "vcxl",
1072 		.pf03_drv_name = "t5iov",
1073 		.vf_nexus_name = "t5vf",
1074 		.vf_ifnet_name = "cxlv"
1075 	}, {
1076 		.nexus_name = "t6nex",
1077 		.ifnet_name = "cc",
1078 		.vi_ifnet_name = "vcc",
1079 		.pf03_drv_name = "t6iov",
1080 		.vf_nexus_name = "t6vf",
1081 		.vf_ifnet_name = "ccv"
1082 	}
1083 };
1084 
1085 void
1086 t4_init_devnames(struct adapter *sc)
1087 {
1088 	int id;
1089 
1090 	id = chip_id(sc);
1091 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1092 		sc->names = &devnames[id - CHELSIO_T4];
1093 	else {
1094 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1095 		sc->names = NULL;
1096 	}
1097 }
1098 
1099 static int
1100 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1101 {
1102 	const char *parent, *name;
1103 	long value;
1104 	int line, unit;
1105 
1106 	line = 0;
1107 	parent = device_get_nameunit(sc->dev);
1108 	name = sc->names->ifnet_name;
1109 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1110 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1111 		    value == pi->port_id)
1112 			return (unit);
1113 	}
1114 	return (-1);
1115 }
1116 
1117 static void
1118 t4_calibration(void *arg)
1119 {
1120 	struct adapter *sc;
1121 	struct clock_sync *cur, *nex;
1122 	uint64_t hw;
1123 	sbintime_t sbt;
1124 	int next_up;
1125 
1126 	sc = (struct adapter *)arg;
1127 
1128 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1129 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1130 	sbt = sbinuptime();
1131 
1132 	cur = &sc->cal_info[sc->cal_current];
1133 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1134 	nex = &sc->cal_info[next_up];
1135 	if (__predict_false(sc->cal_count == 0)) {
1136 		/* First time in, just get the values in */
1137 		cur->hw_cur = hw;
1138 		cur->sbt_cur = sbt;
1139 		sc->cal_count++;
1140 		goto done;
1141 	}
1142 
1143 	if (cur->hw_cur == hw) {
1144 		/* The clock is not advancing? */
1145 		sc->cal_count = 0;
1146 		atomic_store_rel_int(&cur->gen, 0);
1147 		goto done;
1148 	}
1149 
1150 	seqc_write_begin(&nex->gen);
1151 	nex->hw_prev = cur->hw_cur;
1152 	nex->sbt_prev = cur->sbt_cur;
1153 	nex->hw_cur = hw;
1154 	nex->sbt_cur = sbt;
1155 	seqc_write_end(&nex->gen);
1156 	sc->cal_current = next_up;
1157 done:
1158 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1159 	    sc, C_DIRECT_EXEC);
1160 }
1161 
1162 static void
1163 t4_calibration_start(struct adapter *sc)
1164 {
1165 	/*
1166 	 * Here if we have not done a calibration
1167 	 * then do so otherwise start the appropriate
1168 	 * timer.
1169 	 */
1170 	int i;
1171 
1172 	for (i = 0; i < CNT_CAL_INFO; i++) {
1173 		sc->cal_info[i].gen = 0;
1174 	}
1175 	sc->cal_current = 0;
1176 	sc->cal_count = 0;
1177 	sc->cal_gen = 0;
1178 	t4_calibration(sc);
1179 }
1180 
1181 static int
1182 t4_attach(device_t dev)
1183 {
1184 	struct adapter *sc;
1185 	int rc = 0, i, j, rqidx, tqidx, nports;
1186 	struct make_dev_args mda;
1187 	struct intrs_and_queues iaq;
1188 	struct sge *s;
1189 	uint32_t *buf;
1190 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1191 	int ofld_tqidx;
1192 #endif
1193 #ifdef TCP_OFFLOAD
1194 	int ofld_rqidx;
1195 #endif
1196 #ifdef DEV_NETMAP
1197 	int nm_rqidx, nm_tqidx;
1198 #endif
1199 	int num_vis;
1200 
1201 	sc = device_get_softc(dev);
1202 	sc->dev = dev;
1203 	sysctl_ctx_init(&sc->ctx);
1204 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1205 
1206 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1207 		t5_attribute_workaround(dev);
1208 	pci_enable_busmaster(dev);
1209 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1210 		uint32_t v;
1211 
1212 		pci_set_max_read_req(dev, 4096);
1213 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1214 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1215 		if (pcie_relaxed_ordering == 0 &&
1216 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1217 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1218 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1219 		} else if (pcie_relaxed_ordering == 1 &&
1220 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1221 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1222 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1223 		}
1224 	}
1225 
1226 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1227 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1228 	sc->traceq = -1;
1229 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1230 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1231 	    device_get_nameunit(dev));
1232 
1233 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1234 	    device_get_nameunit(dev));
1235 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1236 	t4_add_adapter(sc);
1237 
1238 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1239 	TAILQ_INIT(&sc->sfl);
1240 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1241 
1242 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1243 
1244 	sc->policy = NULL;
1245 	rw_init(&sc->policy_lock, "connection offload policy");
1246 
1247 	callout_init(&sc->ktls_tick, 1);
1248 
1249 	callout_init(&sc->cal_callout, 1);
1250 
1251 	refcount_init(&sc->vxlan_refcount, 0);
1252 
1253 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1254 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1255 
1256 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1257 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1258 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1259 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1260 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1261 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1262 
1263 	rc = t4_map_bars_0_and_4(sc);
1264 	if (rc != 0)
1265 		goto done; /* error message displayed already */
1266 
1267 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1268 
1269 	/* Prepare the adapter for operation. */
1270 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1271 	rc = -t4_prep_adapter(sc, buf);
1272 	free(buf, M_CXGBE);
1273 	if (rc != 0) {
1274 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1275 		goto done;
1276 	}
1277 
1278 	/*
1279 	 * This is the real PF# to which we're attaching.  Works from within PCI
1280 	 * passthrough environments too, where pci_get_function() could return a
1281 	 * different PF# depending on the passthrough configuration.  We need to
1282 	 * use the real PF# in all our communication with the firmware.
1283 	 */
1284 	j = t4_read_reg(sc, A_PL_WHOAMI);
1285 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1286 	sc->mbox = sc->pf;
1287 
1288 	t4_init_devnames(sc);
1289 	if (sc->names == NULL) {
1290 		rc = ENOTSUP;
1291 		goto done; /* error message displayed already */
1292 	}
1293 
1294 	/*
1295 	 * Do this really early, with the memory windows set up even before the
1296 	 * character device.  The userland tool's register i/o and mem read
1297 	 * will work even in "recovery mode".
1298 	 */
1299 	setup_memwin(sc);
1300 	if (t4_init_devlog_params(sc, 0) == 0)
1301 		fixup_devlog_params(sc);
1302 	make_dev_args_init(&mda);
1303 	mda.mda_devsw = &t4_cdevsw;
1304 	mda.mda_uid = UID_ROOT;
1305 	mda.mda_gid = GID_WHEEL;
1306 	mda.mda_mode = 0600;
1307 	mda.mda_si_drv1 = sc;
1308 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1309 	if (rc != 0)
1310 		device_printf(dev, "failed to create nexus char device: %d.\n",
1311 		    rc);
1312 
1313 	/* Go no further if recovery mode has been requested. */
1314 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1315 		device_printf(dev, "recovery mode.\n");
1316 		goto done;
1317 	}
1318 
1319 #if defined(__i386__)
1320 	if ((cpu_feature & CPUID_CX8) == 0) {
1321 		device_printf(dev, "64 bit atomics not available.\n");
1322 		rc = ENOTSUP;
1323 		goto done;
1324 	}
1325 #endif
1326 
1327 	/* Contact the firmware and try to become the master driver. */
1328 	rc = contact_firmware(sc);
1329 	if (rc != 0)
1330 		goto done; /* error message displayed already */
1331 	MPASS(sc->flags & FW_OK);
1332 
1333 	rc = get_params__pre_init(sc);
1334 	if (rc != 0)
1335 		goto done; /* error message displayed already */
1336 
1337 	if (sc->flags & MASTER_PF) {
1338 		rc = partition_resources(sc);
1339 		if (rc != 0)
1340 			goto done; /* error message displayed already */
1341 	}
1342 
1343 	rc = get_params__post_init(sc);
1344 	if (rc != 0)
1345 		goto done; /* error message displayed already */
1346 
1347 	rc = set_params__post_init(sc);
1348 	if (rc != 0)
1349 		goto done; /* error message displayed already */
1350 
1351 	rc = t4_map_bar_2(sc);
1352 	if (rc != 0)
1353 		goto done; /* error message displayed already */
1354 
1355 	rc = t4_adj_doorbells(sc);
1356 	if (rc != 0)
1357 		goto done; /* error message displayed already */
1358 
1359 	rc = t4_create_dma_tag(sc);
1360 	if (rc != 0)
1361 		goto done; /* error message displayed already */
1362 
1363 	/*
1364 	 * First pass over all the ports - allocate VIs and initialize some
1365 	 * basic parameters like mac address, port type, etc.
1366 	 */
1367 	for_each_port(sc, i) {
1368 		struct port_info *pi;
1369 
1370 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1371 		sc->port[i] = pi;
1372 
1373 		/* These must be set before t4_port_init */
1374 		pi->adapter = sc;
1375 		pi->port_id = i;
1376 		/*
1377 		 * XXX: vi[0] is special so we can't delay this allocation until
1378 		 * pi->nvi's final value is known.
1379 		 */
1380 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1381 		    M_ZERO | M_WAITOK);
1382 
1383 		/*
1384 		 * Allocate the "main" VI and initialize parameters
1385 		 * like mac addr.
1386 		 */
1387 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1388 		if (rc != 0) {
1389 			device_printf(dev, "unable to initialize port %d: %d\n",
1390 			    i, rc);
1391 			free(pi->vi, M_CXGBE);
1392 			free(pi, M_CXGBE);
1393 			sc->port[i] = NULL;
1394 			goto done;
1395 		}
1396 
1397 		if (is_bt(pi->port_type))
1398 			setbit(&sc->bt_map, pi->tx_chan);
1399 		else
1400 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1401 
1402 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1403 		    device_get_nameunit(dev), i);
1404 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1405 		sc->chan_map[pi->tx_chan] = i;
1406 
1407 		/*
1408 		 * The MPS counter for FCS errors doesn't work correctly on the
1409 		 * T6 so we use the MAC counter here.  Which MAC is in use
1410 		 * depends on the link settings which will be known when the
1411 		 * link comes up.
1412 		 */
1413 		if (is_t6(sc))
1414 			pi->fcs_reg = -1;
1415 		else {
1416 			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1417 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1418 		}
1419 		pi->fcs_base = 0;
1420 
1421 		/* All VIs on this port share this media. */
1422 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1423 		    cxgbe_media_status);
1424 
1425 		PORT_LOCK(pi);
1426 		init_link_config(pi);
1427 		fixup_link_config(pi);
1428 		build_medialist(pi);
1429 		if (fixed_ifmedia(pi))
1430 			pi->flags |= FIXED_IFMEDIA;
1431 		PORT_UNLOCK(pi);
1432 
1433 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1434 		    t4_ifnet_unit(sc, pi));
1435 		if (pi->dev == NULL) {
1436 			device_printf(dev,
1437 			    "failed to add device for port %d.\n", i);
1438 			rc = ENXIO;
1439 			goto done;
1440 		}
1441 		pi->vi[0].dev = pi->dev;
1442 		device_set_softc(pi->dev, pi);
1443 	}
1444 
1445 	/*
1446 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1447 	 */
1448 	nports = sc->params.nports;
1449 	rc = cfg_itype_and_nqueues(sc, &iaq);
1450 	if (rc != 0)
1451 		goto done; /* error message displayed already */
1452 
1453 	num_vis = iaq.num_vis;
1454 	sc->intr_type = iaq.intr_type;
1455 	sc->intr_count = iaq.nirq;
1456 
1457 	s = &sc->sge;
1458 	s->nrxq = nports * iaq.nrxq;
1459 	s->ntxq = nports * iaq.ntxq;
1460 	if (num_vis > 1) {
1461 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1462 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1463 	}
1464 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1465 	s->neq += nports;		/* ctrl queues: 1 per port */
1466 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1467 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1468 	if (is_offload(sc) || is_ethoffload(sc)) {
1469 		s->nofldtxq = nports * iaq.nofldtxq;
1470 		if (num_vis > 1)
1471 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1472 		s->neq += s->nofldtxq;
1473 
1474 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1475 		    M_CXGBE, M_ZERO | M_WAITOK);
1476 	}
1477 #endif
1478 #ifdef TCP_OFFLOAD
1479 	if (is_offload(sc)) {
1480 		s->nofldrxq = nports * iaq.nofldrxq;
1481 		if (num_vis > 1)
1482 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1483 		s->neq += s->nofldrxq;	/* free list */
1484 		s->niq += s->nofldrxq;
1485 
1486 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1487 		    M_CXGBE, M_ZERO | M_WAITOK);
1488 	}
1489 #endif
1490 #ifdef DEV_NETMAP
1491 	s->nnmrxq = 0;
1492 	s->nnmtxq = 0;
1493 	if (t4_native_netmap & NN_MAIN_VI) {
1494 		s->nnmrxq += nports * iaq.nnmrxq;
1495 		s->nnmtxq += nports * iaq.nnmtxq;
1496 	}
1497 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1498 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1499 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1500 	}
1501 	s->neq += s->nnmtxq + s->nnmrxq;
1502 	s->niq += s->nnmrxq;
1503 
1504 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1505 	    M_CXGBE, M_ZERO | M_WAITOK);
1506 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1507 	    M_CXGBE, M_ZERO | M_WAITOK);
1508 #endif
1509 	MPASS(s->niq <= s->iqmap_sz);
1510 	MPASS(s->neq <= s->eqmap_sz);
1511 
1512 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1513 	    M_ZERO | M_WAITOK);
1514 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1515 	    M_ZERO | M_WAITOK);
1516 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1517 	    M_ZERO | M_WAITOK);
1518 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1519 	    M_ZERO | M_WAITOK);
1520 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1521 	    M_ZERO | M_WAITOK);
1522 
1523 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1524 	    M_ZERO | M_WAITOK);
1525 
1526 	t4_init_l2t(sc, M_WAITOK);
1527 	t4_init_smt(sc, M_WAITOK);
1528 	t4_init_tx_sched(sc);
1529 	t4_init_atid_table(sc);
1530 #ifdef RATELIMIT
1531 	t4_init_etid_table(sc);
1532 #endif
1533 #ifdef INET6
1534 	t4_init_clip_table(sc);
1535 #endif
1536 	if (sc->vres.key.size != 0)
1537 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1538 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1539 
1540 	/*
1541 	 * Second pass over the ports.  This time we know the number of rx and
1542 	 * tx queues that each port should get.
1543 	 */
1544 	rqidx = tqidx = 0;
1545 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1546 	ofld_tqidx = 0;
1547 #endif
1548 #ifdef TCP_OFFLOAD
1549 	ofld_rqidx = 0;
1550 #endif
1551 #ifdef DEV_NETMAP
1552 	nm_rqidx = nm_tqidx = 0;
1553 #endif
1554 	for_each_port(sc, i) {
1555 		struct port_info *pi = sc->port[i];
1556 		struct vi_info *vi;
1557 
1558 		if (pi == NULL)
1559 			continue;
1560 
1561 		pi->nvi = num_vis;
1562 		for_each_vi(pi, j, vi) {
1563 			vi->pi = pi;
1564 			vi->adapter = sc;
1565 			vi->first_intr = -1;
1566 			vi->qsize_rxq = t4_qsize_rxq;
1567 			vi->qsize_txq = t4_qsize_txq;
1568 
1569 			vi->first_rxq = rqidx;
1570 			vi->first_txq = tqidx;
1571 			vi->tmr_idx = t4_tmr_idx;
1572 			vi->pktc_idx = t4_pktc_idx;
1573 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1574 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1575 
1576 			rqidx += vi->nrxq;
1577 			tqidx += vi->ntxq;
1578 
1579 			if (j == 0 && vi->ntxq > 1)
1580 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1581 			else
1582 				vi->rsrv_noflowq = 0;
1583 
1584 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1585 			vi->first_ofld_txq = ofld_tqidx;
1586 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1587 			ofld_tqidx += vi->nofldtxq;
1588 #endif
1589 #ifdef TCP_OFFLOAD
1590 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1591 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1592 			vi->first_ofld_rxq = ofld_rqidx;
1593 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1594 
1595 			ofld_rqidx += vi->nofldrxq;
1596 #endif
1597 #ifdef DEV_NETMAP
1598 			vi->first_nm_rxq = nm_rqidx;
1599 			vi->first_nm_txq = nm_tqidx;
1600 			if (j == 0) {
1601 				vi->nnmrxq = iaq.nnmrxq;
1602 				vi->nnmtxq = iaq.nnmtxq;
1603 			} else {
1604 				vi->nnmrxq = iaq.nnmrxq_vi;
1605 				vi->nnmtxq = iaq.nnmtxq_vi;
1606 			}
1607 			nm_rqidx += vi->nnmrxq;
1608 			nm_tqidx += vi->nnmtxq;
1609 #endif
1610 		}
1611 	}
1612 
1613 	rc = t4_setup_intr_handlers(sc);
1614 	if (rc != 0) {
1615 		device_printf(dev,
1616 		    "failed to setup interrupt handlers: %d\n", rc);
1617 		goto done;
1618 	}
1619 
1620 	rc = bus_generic_probe(dev);
1621 	if (rc != 0) {
1622 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1623 		goto done;
1624 	}
1625 
1626 	/*
1627 	 * Ensure thread-safe mailbox access (in debug builds).
1628 	 *
1629 	 * So far this was the only thread accessing the mailbox but various
1630 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1631 	 * will access the mailbox from different threads.
1632 	 */
1633 	sc->flags |= CHK_MBOX_ACCESS;
1634 
1635 	rc = bus_generic_attach(dev);
1636 	if (rc != 0) {
1637 		device_printf(dev,
1638 		    "failed to attach all child ports: %d\n", rc);
1639 		goto done;
1640 	}
1641 	t4_calibration_start(sc);
1642 
1643 	device_printf(dev,
1644 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1645 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1646 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1647 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1648 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1649 
1650 	t4_set_desc(sc);
1651 
1652 	notify_siblings(dev, 0);
1653 
1654 done:
1655 	if (rc != 0 && sc->cdev) {
1656 		/* cdev was created and so cxgbetool works; recover that way. */
1657 		device_printf(dev,
1658 		    "error during attach, adapter is now in recovery mode.\n");
1659 		rc = 0;
1660 	}
1661 
1662 	if (rc != 0)
1663 		t4_detach_common(dev);
1664 	else
1665 		t4_sysctls(sc);
1666 
1667 	return (rc);
1668 }
1669 
1670 static int
1671 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1672 {
1673 	struct adapter *sc;
1674 	struct port_info *pi;
1675 	int i;
1676 
1677 	sc = device_get_softc(bus);
1678 	for_each_port(sc, i) {
1679 		pi = sc->port[i];
1680 		if (pi != NULL && pi->dev == dev) {
1681 			sbuf_printf(sb, "port=%d", pi->port_id);
1682 			break;
1683 		}
1684 	}
1685 	return (0);
1686 }
1687 
1688 static int
1689 t4_ready(device_t dev)
1690 {
1691 	struct adapter *sc;
1692 
1693 	sc = device_get_softc(dev);
1694 	if (sc->flags & FW_OK)
1695 		return (0);
1696 	return (ENXIO);
1697 }
1698 
1699 static int
1700 t4_read_port_device(device_t dev, int port, device_t *child)
1701 {
1702 	struct adapter *sc;
1703 	struct port_info *pi;
1704 
1705 	sc = device_get_softc(dev);
1706 	if (port < 0 || port >= MAX_NPORTS)
1707 		return (EINVAL);
1708 	pi = sc->port[port];
1709 	if (pi == NULL || pi->dev == NULL)
1710 		return (ENXIO);
1711 	*child = pi->dev;
1712 	return (0);
1713 }
1714 
1715 static int
1716 notify_siblings(device_t dev, int detaching)
1717 {
1718 	device_t sibling;
1719 	int error, i;
1720 
1721 	error = 0;
1722 	for (i = 0; i < PCI_FUNCMAX; i++) {
1723 		if (i == pci_get_function(dev))
1724 			continue;
1725 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1726 		    pci_get_slot(dev), i);
1727 		if (sibling == NULL || !device_is_attached(sibling))
1728 			continue;
1729 		if (detaching)
1730 			error = T4_DETACH_CHILD(sibling);
1731 		else
1732 			(void)T4_ATTACH_CHILD(sibling);
1733 		if (error)
1734 			break;
1735 	}
1736 	return (error);
1737 }
1738 
1739 /*
1740  * Idempotent
1741  */
1742 static int
1743 t4_detach(device_t dev)
1744 {
1745 	int rc;
1746 
1747 	rc = notify_siblings(dev, 1);
1748 	if (rc) {
1749 		device_printf(dev,
1750 		    "failed to detach sibling devices: %d\n", rc);
1751 		return (rc);
1752 	}
1753 
1754 	return (t4_detach_common(dev));
1755 }
1756 
1757 int
1758 t4_detach_common(device_t dev)
1759 {
1760 	struct adapter *sc;
1761 	struct port_info *pi;
1762 	int i, rc;
1763 
1764 	sc = device_get_softc(dev);
1765 
1766 #ifdef TCP_OFFLOAD
1767 	rc = t4_deactivate_all_uld(sc);
1768 	if (rc) {
1769 		device_printf(dev,
1770 		    "failed to detach upper layer drivers: %d\n", rc);
1771 		return (rc);
1772 	}
1773 #endif
1774 
1775 	if (sc->cdev) {
1776 		destroy_dev(sc->cdev);
1777 		sc->cdev = NULL;
1778 	}
1779 
1780 	sx_xlock(&t4_list_lock);
1781 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1782 	sx_xunlock(&t4_list_lock);
1783 
1784 	sc->flags &= ~CHK_MBOX_ACCESS;
1785 	if (sc->flags & FULL_INIT_DONE) {
1786 		if (!(sc->flags & IS_VF))
1787 			t4_intr_disable(sc);
1788 	}
1789 
1790 	if (device_is_attached(dev)) {
1791 		rc = bus_generic_detach(dev);
1792 		if (rc) {
1793 			device_printf(dev,
1794 			    "failed to detach child devices: %d\n", rc);
1795 			return (rc);
1796 		}
1797 	}
1798 
1799 	for (i = 0; i < sc->intr_count; i++)
1800 		t4_free_irq(sc, &sc->irq[i]);
1801 
1802 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1803 		t4_free_tx_sched(sc);
1804 
1805 	for (i = 0; i < MAX_NPORTS; i++) {
1806 		pi = sc->port[i];
1807 		if (pi) {
1808 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1809 			if (pi->dev)
1810 				device_delete_child(dev, pi->dev);
1811 
1812 			mtx_destroy(&pi->pi_lock);
1813 			free(pi->vi, M_CXGBE);
1814 			free(pi, M_CXGBE);
1815 		}
1816 	}
1817 	callout_stop(&sc->cal_callout);
1818 	callout_drain(&sc->cal_callout);
1819 	device_delete_children(dev);
1820 	sysctl_ctx_free(&sc->ctx);
1821 	adapter_full_uninit(sc);
1822 
1823 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1824 		t4_fw_bye(sc, sc->mbox);
1825 
1826 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1827 		pci_release_msi(dev);
1828 
1829 	if (sc->regs_res)
1830 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1831 		    sc->regs_res);
1832 
1833 	if (sc->udbs_res)
1834 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1835 		    sc->udbs_res);
1836 
1837 	if (sc->msix_res)
1838 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1839 		    sc->msix_res);
1840 
1841 	if (sc->l2t)
1842 		t4_free_l2t(sc->l2t);
1843 	if (sc->smt)
1844 		t4_free_smt(sc->smt);
1845 	t4_free_atid_table(sc);
1846 #ifdef RATELIMIT
1847 	t4_free_etid_table(sc);
1848 #endif
1849 	if (sc->key_map)
1850 		vmem_destroy(sc->key_map);
1851 #ifdef INET6
1852 	t4_destroy_clip_table(sc);
1853 #endif
1854 
1855 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1856 	free(sc->sge.ofld_txq, M_CXGBE);
1857 #endif
1858 #ifdef TCP_OFFLOAD
1859 	free(sc->sge.ofld_rxq, M_CXGBE);
1860 #endif
1861 #ifdef DEV_NETMAP
1862 	free(sc->sge.nm_rxq, M_CXGBE);
1863 	free(sc->sge.nm_txq, M_CXGBE);
1864 #endif
1865 	free(sc->irq, M_CXGBE);
1866 	free(sc->sge.rxq, M_CXGBE);
1867 	free(sc->sge.txq, M_CXGBE);
1868 	free(sc->sge.ctrlq, M_CXGBE);
1869 	free(sc->sge.iqmap, M_CXGBE);
1870 	free(sc->sge.eqmap, M_CXGBE);
1871 	free(sc->tids.ftid_tab, M_CXGBE);
1872 	free(sc->tids.hpftid_tab, M_CXGBE);
1873 	free_hftid_hash(&sc->tids);
1874 	free(sc->tids.tid_tab, M_CXGBE);
1875 	t4_destroy_dma_tag(sc);
1876 
1877 	callout_drain(&sc->ktls_tick);
1878 	callout_drain(&sc->sfl_callout);
1879 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1880 		mtx_destroy(&sc->tids.ftid_lock);
1881 		cv_destroy(&sc->tids.ftid_cv);
1882 	}
1883 	if (mtx_initialized(&sc->tids.atid_lock))
1884 		mtx_destroy(&sc->tids.atid_lock);
1885 	if (mtx_initialized(&sc->ifp_lock))
1886 		mtx_destroy(&sc->ifp_lock);
1887 
1888 	if (rw_initialized(&sc->policy_lock)) {
1889 		rw_destroy(&sc->policy_lock);
1890 #ifdef TCP_OFFLOAD
1891 		if (sc->policy != NULL)
1892 			free_offload_policy(sc->policy);
1893 #endif
1894 	}
1895 
1896 	for (i = 0; i < NUM_MEMWIN; i++) {
1897 		struct memwin *mw = &sc->memwin[i];
1898 
1899 		if (rw_initialized(&mw->mw_lock))
1900 			rw_destroy(&mw->mw_lock);
1901 	}
1902 
1903 	mtx_destroy(&sc->sfl_lock);
1904 	mtx_destroy(&sc->reg_lock);
1905 	mtx_destroy(&sc->sc_lock);
1906 
1907 	bzero(sc, sizeof(*sc));
1908 
1909 	return (0);
1910 }
1911 
1912 static inline bool
1913 ok_to_reset(struct adapter *sc)
1914 {
1915 	struct tid_info *t = &sc->tids;
1916 	struct port_info *pi;
1917 	struct vi_info *vi;
1918 	int i, j;
1919 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1920 
1921 	if (is_t6(sc))
1922 		caps |= IFCAP_TXTLS;
1923 
1924 	ASSERT_SYNCHRONIZED_OP(sc);
1925 	MPASS(!(sc->flags & IS_VF));
1926 
1927 	for_each_port(sc, i) {
1928 		pi = sc->port[i];
1929 		for_each_vi(pi, j, vi) {
1930 			if (if_getcapenable(vi->ifp) & caps)
1931 				return (false);
1932 		}
1933 	}
1934 
1935 	if (atomic_load_int(&t->tids_in_use) > 0)
1936 		return (false);
1937 	if (atomic_load_int(&t->stids_in_use) > 0)
1938 		return (false);
1939 	if (atomic_load_int(&t->atids_in_use) > 0)
1940 		return (false);
1941 	if (atomic_load_int(&t->ftids_in_use) > 0)
1942 		return (false);
1943 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1944 		return (false);
1945 	if (atomic_load_int(&t->etids_in_use) > 0)
1946 		return (false);
1947 
1948 	return (true);
1949 }
1950 
1951 static inline int
1952 stop_adapter(struct adapter *sc)
1953 {
1954 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1955 		return (1);		/* Already stopped. */
1956 	return (t4_shutdown_adapter(sc));
1957 }
1958 
1959 static int
1960 t4_suspend(device_t dev)
1961 {
1962 	struct adapter *sc = device_get_softc(dev);
1963 	struct port_info *pi;
1964 	struct vi_info *vi;
1965 	if_t ifp;
1966 	struct sge_rxq *rxq;
1967 	struct sge_txq *txq;
1968 	struct sge_wrq *wrq;
1969 #ifdef TCP_OFFLOAD
1970 	struct sge_ofld_rxq *ofld_rxq;
1971 #endif
1972 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1973 	struct sge_ofld_txq *ofld_txq;
1974 #endif
1975 	int rc, i, j, k;
1976 
1977 	CH_ALERT(sc, "suspend requested\n");
1978 
1979 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1980 	if (rc != 0)
1981 		return (ENXIO);
1982 
1983 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1984 	MPASS(!hw_off_limits(sc));
1985 
1986 	if (!ok_to_reset(sc)) {
1987 		/* XXX: should list what resource is preventing suspend. */
1988 		CH_ERR(sc, "not safe to suspend.\n");
1989 		rc = EBUSY;
1990 		goto done;
1991 	}
1992 
1993 	/* No more DMA or interrupts. */
1994 	stop_adapter(sc);
1995 
1996 	/* Quiesce all activity. */
1997 	for_each_port(sc, i) {
1998 		pi = sc->port[i];
1999 		pi->vxlan_tcam_entry = false;
2000 
2001 		PORT_LOCK(pi);
2002 		if (pi->up_vis > 0) {
2003 			/*
2004 			 * t4_shutdown_adapter has already shut down all the
2005 			 * PHYs but it also disables interrupts and DMA so there
2006 			 * won't be a link interrupt.  So we update the state
2007 			 * manually and inform the kernel.
2008 			 */
2009 			pi->link_cfg.link_ok = false;
2010 			t4_os_link_changed(pi);
2011 		}
2012 		PORT_UNLOCK(pi);
2013 
2014 		for_each_vi(pi, j, vi) {
2015 			vi->xact_addr_filt = -1;
2016 			mtx_lock(&vi->tick_mtx);
2017 			vi->flags |= VI_SKIP_STATS;
2018 			mtx_unlock(&vi->tick_mtx);
2019 			if (!(vi->flags & VI_INIT_DONE))
2020 				continue;
2021 
2022 			ifp = vi->ifp;
2023 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2024 				mtx_lock(&vi->tick_mtx);
2025 				callout_stop(&vi->tick);
2026 				mtx_unlock(&vi->tick_mtx);
2027 				callout_drain(&vi->tick);
2028 			}
2029 
2030 			/*
2031 			 * Note that the HW is not available.
2032 			 */
2033 			for_each_txq(vi, k, txq) {
2034 				TXQ_LOCK(txq);
2035 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2036 				TXQ_UNLOCK(txq);
2037 			}
2038 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2039 			for_each_ofld_txq(vi, k, ofld_txq) {
2040 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2041 			}
2042 #endif
2043 			for_each_rxq(vi, k, rxq) {
2044 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2045 			}
2046 #if defined(TCP_OFFLOAD)
2047 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2048 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2049 			}
2050 #endif
2051 
2052 			quiesce_vi(vi);
2053 		}
2054 
2055 		if (sc->flags & FULL_INIT_DONE) {
2056 			/* Control queue */
2057 			wrq = &sc->sge.ctrlq[i];
2058 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2059 			quiesce_wrq(wrq);
2060 		}
2061 	}
2062 	if (sc->flags & FULL_INIT_DONE) {
2063 		/* Firmware event queue */
2064 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2065 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2066 	}
2067 
2068 	/* Stop calibration */
2069 	callout_stop(&sc->cal_callout);
2070 	callout_drain(&sc->cal_callout);
2071 
2072 	/* Mark the adapter totally off limits. */
2073 	mtx_lock(&sc->reg_lock);
2074 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2075 	sc->flags &= ~(FW_OK | MASTER_PF);
2076 	sc->reset_thread = NULL;
2077 	mtx_unlock(&sc->reg_lock);
2078 
2079 	if (t4_clock_gate_on_suspend) {
2080 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2081 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2082 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2083 	}
2084 
2085 	CH_ALERT(sc, "suspend completed.\n");
2086 done:
2087 	end_synchronized_op(sc, 0);
2088 	return (rc);
2089 }
2090 
2091 struct adapter_pre_reset_state {
2092 	u_int flags;
2093 	uint16_t nbmcaps;
2094 	uint16_t linkcaps;
2095 	uint16_t switchcaps;
2096 	uint16_t niccaps;
2097 	uint16_t toecaps;
2098 	uint16_t rdmacaps;
2099 	uint16_t cryptocaps;
2100 	uint16_t iscsicaps;
2101 	uint16_t fcoecaps;
2102 
2103 	u_int cfcsum;
2104 	char cfg_file[32];
2105 
2106 	struct adapter_params params;
2107 	struct t4_virt_res vres;
2108 	struct tid_info tids;
2109 	struct sge sge;
2110 
2111 	int rawf_base;
2112 	int nrawf;
2113 
2114 };
2115 
2116 static void
2117 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2118 {
2119 
2120 	ASSERT_SYNCHRONIZED_OP(sc);
2121 
2122 	o->flags = sc->flags;
2123 
2124 	o->nbmcaps =  sc->nbmcaps;
2125 	o->linkcaps = sc->linkcaps;
2126 	o->switchcaps = sc->switchcaps;
2127 	o->niccaps = sc->niccaps;
2128 	o->toecaps = sc->toecaps;
2129 	o->rdmacaps = sc->rdmacaps;
2130 	o->cryptocaps = sc->cryptocaps;
2131 	o->iscsicaps = sc->iscsicaps;
2132 	o->fcoecaps = sc->fcoecaps;
2133 
2134 	o->cfcsum = sc->cfcsum;
2135 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2136 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2137 
2138 	o->params = sc->params;
2139 	o->vres = sc->vres;
2140 	o->tids = sc->tids;
2141 	o->sge = sc->sge;
2142 
2143 	o->rawf_base = sc->rawf_base;
2144 	o->nrawf = sc->nrawf;
2145 }
2146 
2147 static int
2148 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2149 {
2150 	int rc = 0;
2151 
2152 	ASSERT_SYNCHRONIZED_OP(sc);
2153 
2154 	/* Capabilities */
2155 #define COMPARE_CAPS(c) do { \
2156 	if (o->c##caps != sc->c##caps) { \
2157 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2158 		    sc->c##caps); \
2159 		rc = EINVAL; \
2160 	} \
2161 } while (0)
2162 	COMPARE_CAPS(nbm);
2163 	COMPARE_CAPS(link);
2164 	COMPARE_CAPS(switch);
2165 	COMPARE_CAPS(nic);
2166 	COMPARE_CAPS(toe);
2167 	COMPARE_CAPS(rdma);
2168 	COMPARE_CAPS(crypto);
2169 	COMPARE_CAPS(iscsi);
2170 	COMPARE_CAPS(fcoe);
2171 #undef COMPARE_CAPS
2172 
2173 	/* Firmware config file */
2174 	if (o->cfcsum != sc->cfcsum) {
2175 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2176 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2177 		rc = EINVAL;
2178 	}
2179 
2180 #define COMPARE_PARAM(p, name) do { \
2181 	if (o->p != sc->p) { \
2182 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2183 		rc = EINVAL; \
2184 	} \
2185 } while (0)
2186 	COMPARE_PARAM(sge.iq_start, iq_start);
2187 	COMPARE_PARAM(sge.eq_start, eq_start);
2188 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2189 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2190 	COMPARE_PARAM(tids.nftids, nftids);
2191 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2192 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2193 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2194 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2195 	COMPARE_PARAM(tids.tid_base, tid_base);
2196 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2197 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2198 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2199 	COMPARE_PARAM(rawf_base, rawf_base);
2200 	COMPARE_PARAM(nrawf, nrawf);
2201 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2202 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2203 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2204 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2205 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2206 	COMPARE_PARAM(tids.ntids, ntids);
2207 	COMPARE_PARAM(tids.etid_base, etid_base);
2208 	COMPARE_PARAM(tids.etid_end, etid_end);
2209 	COMPARE_PARAM(tids.netids, netids);
2210 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2211 	COMPARE_PARAM(params.ethoffload, ethoffload);
2212 	COMPARE_PARAM(tids.natids, natids);
2213 	COMPARE_PARAM(tids.stid_base, stid_base);
2214 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2215 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2216 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2217 	COMPARE_PARAM(vres.stag.start, stag_start);
2218 	COMPARE_PARAM(vres.stag.size, stag_size);
2219 	COMPARE_PARAM(vres.rq.start, rq_start);
2220 	COMPARE_PARAM(vres.rq.size, rq_size);
2221 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2222 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2223 	COMPARE_PARAM(vres.qp.start, qp_start);
2224 	COMPARE_PARAM(vres.qp.size, qp_size);
2225 	COMPARE_PARAM(vres.cq.start, cq_start);
2226 	COMPARE_PARAM(vres.cq.size, cq_size);
2227 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2228 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2229 	COMPARE_PARAM(vres.srq.start, srq_start);
2230 	COMPARE_PARAM(vres.srq.size, srq_size);
2231 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2232 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2233 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2234 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2235 	COMPARE_PARAM(vres.key.start, key_start);
2236 	COMPARE_PARAM(vres.key.size, key_size);
2237 #undef COMPARE_PARAM
2238 
2239 	return (rc);
2240 }
2241 
2242 static int
2243 t4_resume(device_t dev)
2244 {
2245 	struct adapter *sc = device_get_softc(dev);
2246 	struct adapter_pre_reset_state *old_state = NULL;
2247 	struct port_info *pi;
2248 	struct vi_info *vi;
2249 	if_t ifp;
2250 	struct sge_txq *txq;
2251 	int rc, i, j, k;
2252 
2253 	CH_ALERT(sc, "resume requested.\n");
2254 
2255 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2256 	if (rc != 0)
2257 		return (ENXIO);
2258 	MPASS(hw_off_limits(sc));
2259 	MPASS((sc->flags & FW_OK) == 0);
2260 	MPASS((sc->flags & MASTER_PF) == 0);
2261 	MPASS(sc->reset_thread == NULL);
2262 	sc->reset_thread = curthread;
2263 
2264 	/* Register access is expected to work by the time we're here. */
2265 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2266 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2267 		rc = ENXIO;
2268 		goto done;
2269 	}
2270 
2271 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2272 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2273 
2274 	/* Restore memory window. */
2275 	setup_memwin(sc);
2276 
2277 	/* Go no further if recovery mode has been requested. */
2278 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2279 		CH_ALERT(sc, "recovery mode on resume.\n");
2280 		rc = 0;
2281 		mtx_lock(&sc->reg_lock);
2282 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2283 		mtx_unlock(&sc->reg_lock);
2284 		goto done;
2285 	}
2286 
2287 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2288 	save_caps_and_params(sc, old_state);
2289 
2290 	/* Reestablish contact with firmware and become the primary PF. */
2291 	rc = contact_firmware(sc);
2292 	if (rc != 0)
2293 		goto done; /* error message displayed already */
2294 	MPASS(sc->flags & FW_OK);
2295 
2296 	if (sc->flags & MASTER_PF) {
2297 		rc = partition_resources(sc);
2298 		if (rc != 0)
2299 			goto done; /* error message displayed already */
2300 	}
2301 
2302 	rc = get_params__post_init(sc);
2303 	if (rc != 0)
2304 		goto done; /* error message displayed already */
2305 
2306 	rc = set_params__post_init(sc);
2307 	if (rc != 0)
2308 		goto done; /* error message displayed already */
2309 
2310 	rc = compare_caps_and_params(sc, old_state);
2311 	if (rc != 0)
2312 		goto done; /* error message displayed already */
2313 
2314 	for_each_port(sc, i) {
2315 		pi = sc->port[i];
2316 		MPASS(pi != NULL);
2317 		MPASS(pi->vi != NULL);
2318 		MPASS(pi->vi[0].dev == pi->dev);
2319 
2320 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2321 		if (rc != 0) {
2322 			CH_ERR(sc,
2323 			    "failed to re-initialize port %d: %d\n", i, rc);
2324 			goto done;
2325 		}
2326 		MPASS(sc->chan_map[pi->tx_chan] == i);
2327 
2328 		PORT_LOCK(pi);
2329 		fixup_link_config(pi);
2330 		build_medialist(pi);
2331 		PORT_UNLOCK(pi);
2332 		for_each_vi(pi, j, vi) {
2333 			if (IS_MAIN_VI(vi))
2334 				continue;
2335 			rc = alloc_extra_vi(sc, pi, vi);
2336 			if (rc != 0) {
2337 				CH_ERR(vi,
2338 				    "failed to re-allocate extra VI: %d\n", rc);
2339 				goto done;
2340 			}
2341 		}
2342 	}
2343 
2344 	/*
2345 	 * Interrupts and queues are about to be enabled and other threads will
2346 	 * want to access the hardware too.  It is safe to do so.  Note that
2347 	 * this thread is still in the middle of a synchronized_op.
2348 	 */
2349 	mtx_lock(&sc->reg_lock);
2350 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2351 	mtx_unlock(&sc->reg_lock);
2352 
2353 	if (sc->flags & FULL_INIT_DONE) {
2354 		rc = adapter_full_init(sc);
2355 		if (rc != 0) {
2356 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2357 			goto done;
2358 		}
2359 
2360 		if (sc->vxlan_refcount > 0)
2361 			enable_vxlan_rx(sc);
2362 
2363 		for_each_port(sc, i) {
2364 			pi = sc->port[i];
2365 			for_each_vi(pi, j, vi) {
2366 				mtx_lock(&vi->tick_mtx);
2367 				vi->flags &= ~VI_SKIP_STATS;
2368 				mtx_unlock(&vi->tick_mtx);
2369 				if (!(vi->flags & VI_INIT_DONE))
2370 					continue;
2371 				rc = vi_full_init(vi);
2372 				if (rc != 0) {
2373 					CH_ERR(vi, "failed to re-initialize "
2374 					    "interface: %d\n", rc);
2375 					goto done;
2376 				}
2377 
2378 				ifp = vi->ifp;
2379 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2380 					continue;
2381 				/*
2382 				 * Note that we do not setup multicast addresses
2383 				 * in the first pass.  This ensures that the
2384 				 * unicast DMACs for all VIs on all ports get an
2385 				 * MPS TCAM entry.
2386 				 */
2387 				rc = update_mac_settings(ifp, XGMAC_ALL &
2388 				    ~XGMAC_MCADDRS);
2389 				if (rc != 0) {
2390 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2391 					goto done;
2392 				}
2393 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2394 				    true);
2395 				if (rc != 0) {
2396 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2397 					goto done;
2398 				}
2399 				for_each_txq(vi, k, txq) {
2400 					TXQ_LOCK(txq);
2401 					txq->eq.flags |= EQ_ENABLED;
2402 					TXQ_UNLOCK(txq);
2403 				}
2404 				mtx_lock(&vi->tick_mtx);
2405 				callout_schedule(&vi->tick, hz);
2406 				mtx_unlock(&vi->tick_mtx);
2407 			}
2408 			PORT_LOCK(pi);
2409 			if (pi->up_vis > 0) {
2410 				t4_update_port_info(pi);
2411 				fixup_link_config(pi);
2412 				build_medialist(pi);
2413 				apply_link_config(pi);
2414 				if (pi->link_cfg.link_ok)
2415 					t4_os_link_changed(pi);
2416 			}
2417 			PORT_UNLOCK(pi);
2418 		}
2419 
2420 		/* Now reprogram the L2 multicast addresses. */
2421 		for_each_port(sc, i) {
2422 			pi = sc->port[i];
2423 			for_each_vi(pi, j, vi) {
2424 				if (!(vi->flags & VI_INIT_DONE))
2425 					continue;
2426 				ifp = vi->ifp;
2427 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2428 					continue;
2429 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2430 				if (rc != 0) {
2431 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2432 					rc = 0;	/* carry on */
2433 				}
2434 			}
2435 		}
2436 	}
2437 
2438 	/* Reset all calibration */
2439 	t4_calibration_start(sc);
2440 
2441 done:
2442 	if (rc == 0) {
2443 		sc->incarnation++;
2444 		CH_ALERT(sc, "resume completed.\n");
2445 	}
2446 	end_synchronized_op(sc, 0);
2447 	free(old_state, M_CXGBE);
2448 	return (rc);
2449 }
2450 
2451 static int
2452 t4_reset_prepare(device_t dev, device_t child)
2453 {
2454 	struct adapter *sc = device_get_softc(dev);
2455 
2456 	CH_ALERT(sc, "reset_prepare.\n");
2457 	return (0);
2458 }
2459 
2460 static int
2461 t4_reset_post(device_t dev, device_t child)
2462 {
2463 	struct adapter *sc = device_get_softc(dev);
2464 
2465 	CH_ALERT(sc, "reset_post.\n");
2466 	return (0);
2467 }
2468 
2469 static int
2470 reset_adapter(struct adapter *sc)
2471 {
2472 	int rc, oldinc, error_flags;
2473 
2474 	CH_ALERT(sc, "reset requested.\n");
2475 
2476 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2477 	if (rc != 0)
2478 		return (EBUSY);
2479 
2480 	if (hw_off_limits(sc)) {
2481 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2482 		rc = ENXIO;
2483 		goto done;
2484 	}
2485 
2486 	if (!ok_to_reset(sc)) {
2487 		/* XXX: should list what resource is preventing reset. */
2488 		CH_ERR(sc, "not safe to reset.\n");
2489 		rc = EBUSY;
2490 		goto done;
2491 	}
2492 
2493 done:
2494 	oldinc = sc->incarnation;
2495 	end_synchronized_op(sc, 0);
2496 	if (rc != 0)
2497 		return (rc);	/* Error logged already. */
2498 
2499 	atomic_add_int(&sc->num_resets, 1);
2500 	mtx_lock(&Giant);
2501 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2502 	mtx_unlock(&Giant);
2503 	if (rc != 0)
2504 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2505 	else {
2506 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2507 		if (rc != 0)
2508 			return (EBUSY);
2509 		error_flags = atomic_load_int(&sc->error_flags);
2510 		if (sc->incarnation > oldinc && error_flags == 0) {
2511 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2512 		} else {
2513 			CH_ERR(sc, "adapter did not reset properly, flags "
2514 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2515 			    error_flags);
2516 			rc = ENXIO;
2517 		}
2518 		end_synchronized_op(sc, 0);
2519 	}
2520 
2521 	return (rc);
2522 }
2523 
2524 static void
2525 reset_adapter_task(void *arg, int pending)
2526 {
2527 	/* XXX: t4_async_event here? */
2528 	reset_adapter(arg);
2529 }
2530 
2531 static int
2532 cxgbe_probe(device_t dev)
2533 {
2534 	struct port_info *pi = device_get_softc(dev);
2535 
2536 	device_set_descf(dev, "port %d", pi->port_id);
2537 
2538 	return (BUS_PROBE_DEFAULT);
2539 }
2540 
2541 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2542     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2543     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2544     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2545 #define T4_CAP_ENABLE (T4_CAP)
2546 
2547 static void
2548 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2549 {
2550 	if_t ifp;
2551 	struct sbuf *sb;
2552 	struct sysctl_ctx_list *ctx = &vi->ctx;
2553 	struct sysctl_oid_list *children;
2554 	struct pfil_head_args pa;
2555 	struct adapter *sc = vi->adapter;
2556 
2557 	sysctl_ctx_init(ctx);
2558 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2559 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2560 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2561 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2562 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2563 #ifdef DEV_NETMAP
2564 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2565 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2566 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2567 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2568 #endif
2569 #ifdef TCP_OFFLOAD
2570 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2571 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2572 #endif
2573 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2574 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2575 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2576 #endif
2577 
2578 	vi->xact_addr_filt = -1;
2579 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2580 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2581 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2582 		vi->flags |= TX_USES_VM_WR;
2583 
2584 	/* Allocate an ifnet and set it up */
2585 	ifp = if_alloc_dev(IFT_ETHER, dev);
2586 	vi->ifp = ifp;
2587 	if_setsoftc(ifp, vi);
2588 
2589 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2590 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2591 
2592 	if_setinitfn(ifp, cxgbe_init);
2593 	if_setioctlfn(ifp, cxgbe_ioctl);
2594 	if_settransmitfn(ifp, cxgbe_transmit);
2595 	if_setqflushfn(ifp, cxgbe_qflush);
2596 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2597 		if_setgetcounterfn(ifp, vi_get_counter);
2598 	else
2599 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2600 #if defined(KERN_TLS) || defined(RATELIMIT)
2601 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2602 #endif
2603 #ifdef RATELIMIT
2604 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2605 #endif
2606 
2607 	if_setcapabilities(ifp, T4_CAP);
2608 	if_setcapenable(ifp, T4_CAP_ENABLE);
2609 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2610 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2611 	if (chip_id(sc) >= CHELSIO_T6) {
2612 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2613 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2614 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2615 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2616 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2617 	}
2618 
2619 #ifdef TCP_OFFLOAD
2620 	if (vi->nofldrxq != 0)
2621 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2622 #endif
2623 #ifdef RATELIMIT
2624 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2625 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2626 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2627 	}
2628 #endif
2629 
2630 	if_sethwtsomax(ifp, IP_MAXPACKET);
2631 	if (vi->flags & TX_USES_VM_WR)
2632 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2633 	else
2634 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2635 #ifdef RATELIMIT
2636 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2637 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2638 #endif
2639 	if_sethwtsomaxsegsize(ifp, 65536);
2640 #ifdef KERN_TLS
2641 	if (is_ktls(sc)) {
2642 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2643 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2644 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2645 	}
2646 #endif
2647 
2648 	ether_ifattach(ifp, vi->hw_addr);
2649 #ifdef DEV_NETMAP
2650 	if (vi->nnmrxq != 0)
2651 		cxgbe_nm_attach(vi);
2652 #endif
2653 	sb = sbuf_new_auto();
2654 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2655 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2656 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2657 	case IFCAP_TOE:
2658 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2659 		break;
2660 	case IFCAP_TOE | IFCAP_TXRTLMT:
2661 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2662 		break;
2663 	case IFCAP_TXRTLMT:
2664 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2665 		break;
2666 	}
2667 #endif
2668 #ifdef TCP_OFFLOAD
2669 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2670 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2671 #endif
2672 #ifdef DEV_NETMAP
2673 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2674 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2675 		    vi->nnmtxq, vi->nnmrxq);
2676 #endif
2677 	sbuf_finish(sb);
2678 	device_printf(dev, "%s\n", sbuf_data(sb));
2679 	sbuf_delete(sb);
2680 
2681 	vi_sysctls(vi);
2682 
2683 	pa.pa_version = PFIL_VERSION;
2684 	pa.pa_flags = PFIL_IN;
2685 	pa.pa_type = PFIL_TYPE_ETHERNET;
2686 	pa.pa_headname = if_name(ifp);
2687 	vi->pfil = pfil_head_register(&pa);
2688 }
2689 
2690 static int
2691 cxgbe_attach(device_t dev)
2692 {
2693 	struct port_info *pi = device_get_softc(dev);
2694 	struct adapter *sc = pi->adapter;
2695 	struct vi_info *vi;
2696 	int i;
2697 
2698 	sysctl_ctx_init(&pi->ctx);
2699 
2700 	cxgbe_vi_attach(dev, &pi->vi[0]);
2701 
2702 	for_each_vi(pi, i, vi) {
2703 		if (i == 0)
2704 			continue;
2705 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2706 		if (vi->dev == NULL) {
2707 			device_printf(dev, "failed to add VI %d\n", i);
2708 			continue;
2709 		}
2710 		device_set_softc(vi->dev, vi);
2711 	}
2712 
2713 	cxgbe_sysctls(pi);
2714 
2715 	bus_generic_attach(dev);
2716 
2717 	return (0);
2718 }
2719 
2720 static void
2721 cxgbe_vi_detach(struct vi_info *vi)
2722 {
2723 	if_t ifp = vi->ifp;
2724 
2725 	if (vi->pfil != NULL) {
2726 		pfil_head_unregister(vi->pfil);
2727 		vi->pfil = NULL;
2728 	}
2729 
2730 	ether_ifdetach(ifp);
2731 
2732 	/* Let detach proceed even if these fail. */
2733 #ifdef DEV_NETMAP
2734 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2735 		cxgbe_nm_detach(vi);
2736 #endif
2737 	cxgbe_uninit_synchronized(vi);
2738 	callout_drain(&vi->tick);
2739 	mtx_destroy(&vi->tick_mtx);
2740 	sysctl_ctx_free(&vi->ctx);
2741 	vi_full_uninit(vi);
2742 
2743 	if_free(vi->ifp);
2744 	vi->ifp = NULL;
2745 }
2746 
2747 static int
2748 cxgbe_detach(device_t dev)
2749 {
2750 	struct port_info *pi = device_get_softc(dev);
2751 	struct adapter *sc = pi->adapter;
2752 	int rc;
2753 
2754 	/* Detach the extra VIs first. */
2755 	rc = bus_generic_detach(dev);
2756 	if (rc)
2757 		return (rc);
2758 	device_delete_children(dev);
2759 
2760 	sysctl_ctx_free(&pi->ctx);
2761 	begin_vi_detach(sc, &pi->vi[0]);
2762 	if (pi->flags & HAS_TRACEQ) {
2763 		sc->traceq = -1;	/* cloner should not create ifnet */
2764 		t4_tracer_port_detach(sc);
2765 	}
2766 	cxgbe_vi_detach(&pi->vi[0]);
2767 	ifmedia_removeall(&pi->media);
2768 	end_vi_detach(sc, &pi->vi[0]);
2769 
2770 	return (0);
2771 }
2772 
2773 static void
2774 cxgbe_init(void *arg)
2775 {
2776 	struct vi_info *vi = arg;
2777 	struct adapter *sc = vi->adapter;
2778 
2779 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2780 		return;
2781 	cxgbe_init_synchronized(vi);
2782 	end_synchronized_op(sc, 0);
2783 }
2784 
2785 static int
2786 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2787 {
2788 	int rc = 0, mtu, flags;
2789 	struct vi_info *vi = if_getsoftc(ifp);
2790 	struct port_info *pi = vi->pi;
2791 	struct adapter *sc = pi->adapter;
2792 	struct ifreq *ifr = (struct ifreq *)data;
2793 	uint32_t mask;
2794 
2795 	switch (cmd) {
2796 	case SIOCSIFMTU:
2797 		mtu = ifr->ifr_mtu;
2798 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2799 			return (EINVAL);
2800 
2801 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2802 		if (rc)
2803 			return (rc);
2804 		if_setmtu(ifp, mtu);
2805 		if (vi->flags & VI_INIT_DONE) {
2806 			t4_update_fl_bufsize(ifp);
2807 			if (!hw_off_limits(sc) &&
2808 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2809 				rc = update_mac_settings(ifp, XGMAC_MTU);
2810 		}
2811 		end_synchronized_op(sc, 0);
2812 		break;
2813 
2814 	case SIOCSIFFLAGS:
2815 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2816 		if (rc)
2817 			return (rc);
2818 
2819 		if (hw_off_limits(sc)) {
2820 			rc = ENXIO;
2821 			goto fail;
2822 		}
2823 
2824 		if (if_getflags(ifp) & IFF_UP) {
2825 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2826 				flags = vi->if_flags;
2827 				if ((if_getflags(ifp) ^ flags) &
2828 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2829 					rc = update_mac_settings(ifp,
2830 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2831 				}
2832 			} else {
2833 				rc = cxgbe_init_synchronized(vi);
2834 			}
2835 			vi->if_flags = if_getflags(ifp);
2836 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2837 			rc = cxgbe_uninit_synchronized(vi);
2838 		}
2839 		end_synchronized_op(sc, 0);
2840 		break;
2841 
2842 	case SIOCADDMULTI:
2843 	case SIOCDELMULTI:
2844 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2845 		if (rc)
2846 			return (rc);
2847 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2848 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2849 		end_synchronized_op(sc, 0);
2850 		break;
2851 
2852 	case SIOCSIFCAP:
2853 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2854 		if (rc)
2855 			return (rc);
2856 
2857 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2858 		if (mask & IFCAP_TXCSUM) {
2859 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2860 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2861 
2862 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2863 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2864 				mask &= ~IFCAP_TSO4;
2865 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2866 				if_printf(ifp,
2867 				    "tso4 disabled due to -txcsum.\n");
2868 			}
2869 		}
2870 		if (mask & IFCAP_TXCSUM_IPV6) {
2871 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2872 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2873 
2874 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2875 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2876 				mask &= ~IFCAP_TSO6;
2877 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2878 				if_printf(ifp,
2879 				    "tso6 disabled due to -txcsum6.\n");
2880 			}
2881 		}
2882 		if (mask & IFCAP_RXCSUM)
2883 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2884 		if (mask & IFCAP_RXCSUM_IPV6)
2885 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2886 
2887 		/*
2888 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2889 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2890 		 * sending a TSO request our way, so it's sufficient to toggle
2891 		 * IFCAP_TSOx only.
2892 		 */
2893 		if (mask & IFCAP_TSO4) {
2894 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2895 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2896 				if_printf(ifp, "enable txcsum first.\n");
2897 				rc = EAGAIN;
2898 				goto fail;
2899 			}
2900 			if_togglecapenable(ifp, IFCAP_TSO4);
2901 		}
2902 		if (mask & IFCAP_TSO6) {
2903 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2904 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2905 				if_printf(ifp, "enable txcsum6 first.\n");
2906 				rc = EAGAIN;
2907 				goto fail;
2908 			}
2909 			if_togglecapenable(ifp, IFCAP_TSO6);
2910 		}
2911 		if (mask & IFCAP_LRO) {
2912 #if defined(INET) || defined(INET6)
2913 			int i;
2914 			struct sge_rxq *rxq;
2915 
2916 			if_togglecapenable(ifp, IFCAP_LRO);
2917 			for_each_rxq(vi, i, rxq) {
2918 				if (if_getcapenable(ifp) & IFCAP_LRO)
2919 					rxq->iq.flags |= IQ_LRO_ENABLED;
2920 				else
2921 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2922 			}
2923 #endif
2924 		}
2925 #ifdef TCP_OFFLOAD
2926 		if (mask & IFCAP_TOE) {
2927 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2928 
2929 			rc = toe_capability(vi, enable);
2930 			if (rc != 0)
2931 				goto fail;
2932 
2933 			if_togglecapenable(ifp, mask);
2934 		}
2935 #endif
2936 		if (mask & IFCAP_VLAN_HWTAGGING) {
2937 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2938 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2939 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2940 		}
2941 		if (mask & IFCAP_VLAN_MTU) {
2942 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2943 
2944 			/* Need to find out how to disable auto-mtu-inflation */
2945 		}
2946 		if (mask & IFCAP_VLAN_HWTSO)
2947 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2948 		if (mask & IFCAP_VLAN_HWCSUM)
2949 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2950 #ifdef RATELIMIT
2951 		if (mask & IFCAP_TXRTLMT)
2952 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2953 #endif
2954 		if (mask & IFCAP_HWRXTSTMP) {
2955 			int i;
2956 			struct sge_rxq *rxq;
2957 
2958 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2959 			for_each_rxq(vi, i, rxq) {
2960 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2961 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2962 				else
2963 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2964 			}
2965 		}
2966 		if (mask & IFCAP_MEXTPG)
2967 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2968 
2969 #ifdef KERN_TLS
2970 		if (mask & IFCAP_TXTLS) {
2971 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2972 
2973 			rc = ktls_capability(sc, enable);
2974 			if (rc != 0)
2975 				goto fail;
2976 
2977 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2978 		}
2979 #endif
2980 		if (mask & IFCAP_VXLAN_HWCSUM) {
2981 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2982 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2983 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2984 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2985 		}
2986 		if (mask & IFCAP_VXLAN_HWTSO) {
2987 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2988 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2989 			    CSUM_INNER_IP_TSO);
2990 		}
2991 
2992 #ifdef VLAN_CAPABILITIES
2993 		VLAN_CAPABILITIES(ifp);
2994 #endif
2995 fail:
2996 		end_synchronized_op(sc, 0);
2997 		break;
2998 
2999 	case SIOCSIFMEDIA:
3000 	case SIOCGIFMEDIA:
3001 	case SIOCGIFXMEDIA:
3002 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3003 		break;
3004 
3005 	case SIOCGI2C: {
3006 		struct ifi2creq i2c;
3007 
3008 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3009 		if (rc != 0)
3010 			break;
3011 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3012 			rc = EPERM;
3013 			break;
3014 		}
3015 		if (i2c.len > sizeof(i2c.data)) {
3016 			rc = EINVAL;
3017 			break;
3018 		}
3019 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3020 		if (rc)
3021 			return (rc);
3022 		if (hw_off_limits(sc))
3023 			rc = ENXIO;
3024 		else
3025 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3026 			    i2c.offset, i2c.len, &i2c.data[0]);
3027 		end_synchronized_op(sc, 0);
3028 		if (rc == 0)
3029 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3030 		break;
3031 	}
3032 
3033 	default:
3034 		rc = ether_ioctl(ifp, cmd, data);
3035 	}
3036 
3037 	return (rc);
3038 }
3039 
3040 static int
3041 cxgbe_transmit(if_t ifp, struct mbuf *m)
3042 {
3043 	struct vi_info *vi = if_getsoftc(ifp);
3044 	struct port_info *pi = vi->pi;
3045 	struct adapter *sc;
3046 	struct sge_txq *txq;
3047 	void *items[1];
3048 	int rc;
3049 
3050 	M_ASSERTPKTHDR(m);
3051 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3052 #if defined(KERN_TLS) || defined(RATELIMIT)
3053 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3054 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3055 #endif
3056 
3057 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3058 		m_freem(m);
3059 		return (ENETDOWN);
3060 	}
3061 
3062 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3063 	if (__predict_false(rc != 0)) {
3064 		if (__predict_true(rc == EINPROGRESS)) {
3065 			/* queued by parse_pkt */
3066 			MPASS(m != NULL);
3067 			return (0);
3068 		}
3069 
3070 		MPASS(m == NULL);			/* was freed already */
3071 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3072 		return (rc);
3073 	}
3074 
3075 	/* Select a txq. */
3076 	sc = vi->adapter;
3077 	txq = &sc->sge.txq[vi->first_txq];
3078 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3079 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3080 		    vi->rsrv_noflowq);
3081 
3082 	items[0] = m;
3083 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3084 	if (__predict_false(rc != 0))
3085 		m_freem(m);
3086 
3087 	return (rc);
3088 }
3089 
3090 static void
3091 cxgbe_qflush(if_t ifp)
3092 {
3093 	struct vi_info *vi = if_getsoftc(ifp);
3094 	struct sge_txq *txq;
3095 	int i;
3096 
3097 	/* queues do not exist if !VI_INIT_DONE. */
3098 	if (vi->flags & VI_INIT_DONE) {
3099 		for_each_txq(vi, i, txq) {
3100 			TXQ_LOCK(txq);
3101 			txq->eq.flags |= EQ_QFLUSH;
3102 			TXQ_UNLOCK(txq);
3103 			while (!mp_ring_is_idle(txq->r)) {
3104 				mp_ring_check_drainage(txq->r, 4096);
3105 				pause("qflush", 1);
3106 			}
3107 			TXQ_LOCK(txq);
3108 			txq->eq.flags &= ~EQ_QFLUSH;
3109 			TXQ_UNLOCK(txq);
3110 		}
3111 	}
3112 	if_qflush(ifp);
3113 }
3114 
3115 static uint64_t
3116 vi_get_counter(if_t ifp, ift_counter c)
3117 {
3118 	struct vi_info *vi = if_getsoftc(ifp);
3119 	struct fw_vi_stats_vf *s = &vi->stats;
3120 
3121 	mtx_lock(&vi->tick_mtx);
3122 	vi_refresh_stats(vi);
3123 	mtx_unlock(&vi->tick_mtx);
3124 
3125 	switch (c) {
3126 	case IFCOUNTER_IPACKETS:
3127 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3128 		    s->rx_ucast_frames);
3129 	case IFCOUNTER_IERRORS:
3130 		return (s->rx_err_frames);
3131 	case IFCOUNTER_OPACKETS:
3132 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3133 		    s->tx_ucast_frames + s->tx_offload_frames);
3134 	case IFCOUNTER_OERRORS:
3135 		return (s->tx_drop_frames);
3136 	case IFCOUNTER_IBYTES:
3137 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3138 		    s->rx_ucast_bytes);
3139 	case IFCOUNTER_OBYTES:
3140 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3141 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3142 	case IFCOUNTER_IMCASTS:
3143 		return (s->rx_mcast_frames);
3144 	case IFCOUNTER_OMCASTS:
3145 		return (s->tx_mcast_frames);
3146 	case IFCOUNTER_OQDROPS: {
3147 		uint64_t drops;
3148 
3149 		drops = 0;
3150 		if (vi->flags & VI_INIT_DONE) {
3151 			int i;
3152 			struct sge_txq *txq;
3153 
3154 			for_each_txq(vi, i, txq)
3155 				drops += counter_u64_fetch(txq->r->dropped);
3156 		}
3157 
3158 		return (drops);
3159 
3160 	}
3161 
3162 	default:
3163 		return (if_get_counter_default(ifp, c));
3164 	}
3165 }
3166 
3167 static uint64_t
3168 cxgbe_get_counter(if_t ifp, ift_counter c)
3169 {
3170 	struct vi_info *vi = if_getsoftc(ifp);
3171 	struct port_info *pi = vi->pi;
3172 	struct port_stats *s = &pi->stats;
3173 
3174 	mtx_lock(&vi->tick_mtx);
3175 	cxgbe_refresh_stats(vi);
3176 	mtx_unlock(&vi->tick_mtx);
3177 
3178 	switch (c) {
3179 	case IFCOUNTER_IPACKETS:
3180 		return (s->rx_frames);
3181 
3182 	case IFCOUNTER_IERRORS:
3183 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3184 		    s->rx_fcs_err + s->rx_len_err);
3185 
3186 	case IFCOUNTER_OPACKETS:
3187 		return (s->tx_frames);
3188 
3189 	case IFCOUNTER_OERRORS:
3190 		return (s->tx_error_frames);
3191 
3192 	case IFCOUNTER_IBYTES:
3193 		return (s->rx_octets);
3194 
3195 	case IFCOUNTER_OBYTES:
3196 		return (s->tx_octets);
3197 
3198 	case IFCOUNTER_IMCASTS:
3199 		return (s->rx_mcast_frames);
3200 
3201 	case IFCOUNTER_OMCASTS:
3202 		return (s->tx_mcast_frames);
3203 
3204 	case IFCOUNTER_IQDROPS:
3205 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3206 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3207 		    s->rx_trunc3 + pi->tnl_cong_drops);
3208 
3209 	case IFCOUNTER_OQDROPS: {
3210 		uint64_t drops;
3211 
3212 		drops = s->tx_drop;
3213 		if (vi->flags & VI_INIT_DONE) {
3214 			int i;
3215 			struct sge_txq *txq;
3216 
3217 			for_each_txq(vi, i, txq)
3218 				drops += counter_u64_fetch(txq->r->dropped);
3219 		}
3220 
3221 		return (drops);
3222 
3223 	}
3224 
3225 	default:
3226 		return (if_get_counter_default(ifp, c));
3227 	}
3228 }
3229 
3230 #if defined(KERN_TLS) || defined(RATELIMIT)
3231 static int
3232 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3233     struct m_snd_tag **pt)
3234 {
3235 	int error;
3236 
3237 	switch (params->hdr.type) {
3238 #ifdef RATELIMIT
3239 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3240 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3241 		break;
3242 #endif
3243 #ifdef KERN_TLS
3244 	case IF_SND_TAG_TYPE_TLS:
3245 	{
3246 		struct vi_info *vi = if_getsoftc(ifp);
3247 
3248 		if (is_t6(vi->pi->adapter))
3249 			error = t6_tls_tag_alloc(ifp, params, pt);
3250 		else
3251 			error = EOPNOTSUPP;
3252 		break;
3253 	}
3254 #endif
3255 	default:
3256 		error = EOPNOTSUPP;
3257 	}
3258 	return (error);
3259 }
3260 #endif
3261 
3262 /*
3263  * The kernel picks a media from the list we had provided but we still validate
3264  * the requeste.
3265  */
3266 int
3267 cxgbe_media_change(if_t ifp)
3268 {
3269 	struct vi_info *vi = if_getsoftc(ifp);
3270 	struct port_info *pi = vi->pi;
3271 	struct ifmedia *ifm = &pi->media;
3272 	struct link_config *lc = &pi->link_cfg;
3273 	struct adapter *sc = pi->adapter;
3274 	int rc;
3275 
3276 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3277 	if (rc != 0)
3278 		return (rc);
3279 	PORT_LOCK(pi);
3280 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3281 		/* ifconfig .. media autoselect */
3282 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3283 			rc = ENOTSUP; /* AN not supported by transceiver */
3284 			goto done;
3285 		}
3286 		lc->requested_aneg = AUTONEG_ENABLE;
3287 		lc->requested_speed = 0;
3288 		lc->requested_fc |= PAUSE_AUTONEG;
3289 	} else {
3290 		lc->requested_aneg = AUTONEG_DISABLE;
3291 		lc->requested_speed =
3292 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3293 		lc->requested_fc = 0;
3294 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3295 			lc->requested_fc |= PAUSE_RX;
3296 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3297 			lc->requested_fc |= PAUSE_TX;
3298 	}
3299 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3300 		fixup_link_config(pi);
3301 		rc = apply_link_config(pi);
3302 	}
3303 done:
3304 	PORT_UNLOCK(pi);
3305 	end_synchronized_op(sc, 0);
3306 	return (rc);
3307 }
3308 
3309 /*
3310  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3311  * given speed.
3312  */
3313 static int
3314 port_mword(struct port_info *pi, uint32_t speed)
3315 {
3316 
3317 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3318 	MPASS(powerof2(speed));
3319 
3320 	switch(pi->port_type) {
3321 	case FW_PORT_TYPE_BT_SGMII:
3322 	case FW_PORT_TYPE_BT_XFI:
3323 	case FW_PORT_TYPE_BT_XAUI:
3324 		/* BaseT */
3325 		switch (speed) {
3326 		case FW_PORT_CAP32_SPEED_100M:
3327 			return (IFM_100_T);
3328 		case FW_PORT_CAP32_SPEED_1G:
3329 			return (IFM_1000_T);
3330 		case FW_PORT_CAP32_SPEED_10G:
3331 			return (IFM_10G_T);
3332 		}
3333 		break;
3334 	case FW_PORT_TYPE_KX4:
3335 		if (speed == FW_PORT_CAP32_SPEED_10G)
3336 			return (IFM_10G_KX4);
3337 		break;
3338 	case FW_PORT_TYPE_CX4:
3339 		if (speed == FW_PORT_CAP32_SPEED_10G)
3340 			return (IFM_10G_CX4);
3341 		break;
3342 	case FW_PORT_TYPE_KX:
3343 		if (speed == FW_PORT_CAP32_SPEED_1G)
3344 			return (IFM_1000_KX);
3345 		break;
3346 	case FW_PORT_TYPE_KR:
3347 	case FW_PORT_TYPE_BP_AP:
3348 	case FW_PORT_TYPE_BP4_AP:
3349 	case FW_PORT_TYPE_BP40_BA:
3350 	case FW_PORT_TYPE_KR4_100G:
3351 	case FW_PORT_TYPE_KR_SFP28:
3352 	case FW_PORT_TYPE_KR_XLAUI:
3353 		switch (speed) {
3354 		case FW_PORT_CAP32_SPEED_1G:
3355 			return (IFM_1000_KX);
3356 		case FW_PORT_CAP32_SPEED_10G:
3357 			return (IFM_10G_KR);
3358 		case FW_PORT_CAP32_SPEED_25G:
3359 			return (IFM_25G_KR);
3360 		case FW_PORT_CAP32_SPEED_40G:
3361 			return (IFM_40G_KR4);
3362 		case FW_PORT_CAP32_SPEED_50G:
3363 			return (IFM_50G_KR2);
3364 		case FW_PORT_CAP32_SPEED_100G:
3365 			return (IFM_100G_KR4);
3366 		}
3367 		break;
3368 	case FW_PORT_TYPE_FIBER_XFI:
3369 	case FW_PORT_TYPE_FIBER_XAUI:
3370 	case FW_PORT_TYPE_SFP:
3371 	case FW_PORT_TYPE_QSFP_10G:
3372 	case FW_PORT_TYPE_QSA:
3373 	case FW_PORT_TYPE_QSFP:
3374 	case FW_PORT_TYPE_CR4_QSFP:
3375 	case FW_PORT_TYPE_CR_QSFP:
3376 	case FW_PORT_TYPE_CR2_QSFP:
3377 	case FW_PORT_TYPE_SFP28:
3378 		/* Pluggable transceiver */
3379 		switch (pi->mod_type) {
3380 		case FW_PORT_MOD_TYPE_LR:
3381 			switch (speed) {
3382 			case FW_PORT_CAP32_SPEED_1G:
3383 				return (IFM_1000_LX);
3384 			case FW_PORT_CAP32_SPEED_10G:
3385 				return (IFM_10G_LR);
3386 			case FW_PORT_CAP32_SPEED_25G:
3387 				return (IFM_25G_LR);
3388 			case FW_PORT_CAP32_SPEED_40G:
3389 				return (IFM_40G_LR4);
3390 			case FW_PORT_CAP32_SPEED_50G:
3391 				return (IFM_50G_LR2);
3392 			case FW_PORT_CAP32_SPEED_100G:
3393 				return (IFM_100G_LR4);
3394 			}
3395 			break;
3396 		case FW_PORT_MOD_TYPE_SR:
3397 			switch (speed) {
3398 			case FW_PORT_CAP32_SPEED_1G:
3399 				return (IFM_1000_SX);
3400 			case FW_PORT_CAP32_SPEED_10G:
3401 				return (IFM_10G_SR);
3402 			case FW_PORT_CAP32_SPEED_25G:
3403 				return (IFM_25G_SR);
3404 			case FW_PORT_CAP32_SPEED_40G:
3405 				return (IFM_40G_SR4);
3406 			case FW_PORT_CAP32_SPEED_50G:
3407 				return (IFM_50G_SR2);
3408 			case FW_PORT_CAP32_SPEED_100G:
3409 				return (IFM_100G_SR4);
3410 			}
3411 			break;
3412 		case FW_PORT_MOD_TYPE_ER:
3413 			if (speed == FW_PORT_CAP32_SPEED_10G)
3414 				return (IFM_10G_ER);
3415 			break;
3416 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3417 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3418 			switch (speed) {
3419 			case FW_PORT_CAP32_SPEED_1G:
3420 				return (IFM_1000_CX);
3421 			case FW_PORT_CAP32_SPEED_10G:
3422 				return (IFM_10G_TWINAX);
3423 			case FW_PORT_CAP32_SPEED_25G:
3424 				return (IFM_25G_CR);
3425 			case FW_PORT_CAP32_SPEED_40G:
3426 				return (IFM_40G_CR4);
3427 			case FW_PORT_CAP32_SPEED_50G:
3428 				return (IFM_50G_CR2);
3429 			case FW_PORT_CAP32_SPEED_100G:
3430 				return (IFM_100G_CR4);
3431 			}
3432 			break;
3433 		case FW_PORT_MOD_TYPE_LRM:
3434 			if (speed == FW_PORT_CAP32_SPEED_10G)
3435 				return (IFM_10G_LRM);
3436 			break;
3437 		case FW_PORT_MOD_TYPE_NA:
3438 			MPASS(0);	/* Not pluggable? */
3439 			/* fall throough */
3440 		case FW_PORT_MOD_TYPE_ERROR:
3441 		case FW_PORT_MOD_TYPE_UNKNOWN:
3442 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3443 			break;
3444 		case FW_PORT_MOD_TYPE_NONE:
3445 			return (IFM_NONE);
3446 		}
3447 		break;
3448 	case FW_PORT_TYPE_NONE:
3449 		return (IFM_NONE);
3450 	}
3451 
3452 	return (IFM_UNKNOWN);
3453 }
3454 
3455 void
3456 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3457 {
3458 	struct vi_info *vi = if_getsoftc(ifp);
3459 	struct port_info *pi = vi->pi;
3460 	struct adapter *sc = pi->adapter;
3461 	struct link_config *lc = &pi->link_cfg;
3462 
3463 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3464 		return;
3465 	PORT_LOCK(pi);
3466 
3467 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3468 		/*
3469 		 * If all the interfaces are administratively down the firmware
3470 		 * does not report transceiver changes.  Refresh port info here
3471 		 * so that ifconfig displays accurate ifmedia at all times.
3472 		 * This is the only reason we have a synchronized op in this
3473 		 * function.  Just PORT_LOCK would have been enough otherwise.
3474 		 */
3475 		t4_update_port_info(pi);
3476 		build_medialist(pi);
3477 	}
3478 
3479 	/* ifm_status */
3480 	ifmr->ifm_status = IFM_AVALID;
3481 	if (lc->link_ok == false)
3482 		goto done;
3483 	ifmr->ifm_status |= IFM_ACTIVE;
3484 
3485 	/* ifm_active */
3486 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3487 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3488 	if (lc->fc & PAUSE_RX)
3489 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3490 	if (lc->fc & PAUSE_TX)
3491 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3492 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3493 done:
3494 	PORT_UNLOCK(pi);
3495 	end_synchronized_op(sc, 0);
3496 }
3497 
3498 static int
3499 vcxgbe_probe(device_t dev)
3500 {
3501 	struct vi_info *vi = device_get_softc(dev);
3502 
3503 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3504 	    vi - vi->pi->vi);
3505 
3506 	return (BUS_PROBE_DEFAULT);
3507 }
3508 
3509 static int
3510 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3511 {
3512 	int func, index, rc;
3513 	uint32_t param, val;
3514 
3515 	ASSERT_SYNCHRONIZED_OP(sc);
3516 
3517 	index = vi - pi->vi;
3518 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3519 	KASSERT(index < nitems(vi_mac_funcs),
3520 	    ("%s: VI %s doesn't have a MAC func", __func__,
3521 	    device_get_nameunit(vi->dev)));
3522 	func = vi_mac_funcs[index];
3523 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3524 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3525 	if (rc < 0) {
3526 		CH_ERR(vi, "failed to allocate virtual interface %d"
3527 		    "for port %d: %d\n", index, pi->port_id, -rc);
3528 		return (-rc);
3529 	}
3530 	vi->viid = rc;
3531 
3532 	if (vi->rss_size == 1) {
3533 		/*
3534 		 * This VI didn't get a slice of the RSS table.  Reduce the
3535 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3536 		 * configuration file (nvi, rssnvi for this PF) if this is a
3537 		 * problem.
3538 		 */
3539 		device_printf(vi->dev, "RSS table not available.\n");
3540 		vi->rss_base = 0xffff;
3541 
3542 		return (0);
3543 	}
3544 
3545 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3546 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3547 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3548 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3549 	if (rc)
3550 		vi->rss_base = 0xffff;
3551 	else {
3552 		MPASS((val >> 16) == vi->rss_size);
3553 		vi->rss_base = val & 0xffff;
3554 	}
3555 
3556 	return (0);
3557 }
3558 
3559 static int
3560 vcxgbe_attach(device_t dev)
3561 {
3562 	struct vi_info *vi;
3563 	struct port_info *pi;
3564 	struct adapter *sc;
3565 	int rc;
3566 
3567 	vi = device_get_softc(dev);
3568 	pi = vi->pi;
3569 	sc = pi->adapter;
3570 
3571 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3572 	if (rc)
3573 		return (rc);
3574 	rc = alloc_extra_vi(sc, pi, vi);
3575 	end_synchronized_op(sc, 0);
3576 	if (rc)
3577 		return (rc);
3578 
3579 	cxgbe_vi_attach(dev, vi);
3580 
3581 	return (0);
3582 }
3583 
3584 static int
3585 vcxgbe_detach(device_t dev)
3586 {
3587 	struct vi_info *vi;
3588 	struct adapter *sc;
3589 
3590 	vi = device_get_softc(dev);
3591 	sc = vi->adapter;
3592 
3593 	begin_vi_detach(sc, vi);
3594 	cxgbe_vi_detach(vi);
3595 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3596 	end_vi_detach(sc, vi);
3597 
3598 	return (0);
3599 }
3600 
3601 static struct callout fatal_callout;
3602 static struct taskqueue *reset_tq;
3603 
3604 static void
3605 delayed_panic(void *arg)
3606 {
3607 	struct adapter *sc = arg;
3608 
3609 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3610 }
3611 
3612 static void
3613 fatal_error_task(void *arg, int pending)
3614 {
3615 	struct adapter *sc = arg;
3616 	int rc;
3617 
3618 #ifdef TCP_OFFLOAD
3619 	t4_async_event(sc);
3620 #endif
3621 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3622 		dump_cim_regs(sc);
3623 		dump_cimla(sc);
3624 		dump_devlog(sc);
3625 	}
3626 
3627 	if (t4_reset_on_fatal_err) {
3628 		CH_ALERT(sc, "resetting on fatal error.\n");
3629 		rc = reset_adapter(sc);
3630 		if (rc == 0 && t4_panic_on_fatal_err) {
3631 			CH_ALERT(sc, "reset was successful, "
3632 			    "system will NOT panic.\n");
3633 			return;
3634 		}
3635 	}
3636 
3637 	if (t4_panic_on_fatal_err) {
3638 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3639 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3640 	}
3641 }
3642 
3643 void
3644 t4_fatal_err(struct adapter *sc, bool fw_error)
3645 {
3646 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3647 
3648 	stop_adapter(sc);
3649 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3650 		return;
3651 	if (fw_error) {
3652 		/*
3653 		 * We are here because of a firmware error/timeout and not
3654 		 * because of a hardware interrupt.  It is possible (although
3655 		 * not very likely) that an error interrupt was also raised but
3656 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3657 		 * main INT_CAUSE registers here to make sure we haven't missed
3658 		 * anything interesting.
3659 		 */
3660 		t4_slow_intr_handler(sc, verbose);
3661 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3662 	}
3663 	t4_report_fw_error(sc);
3664 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3665 	    device_get_nameunit(sc->dev), fw_error);
3666 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3667 }
3668 
3669 void
3670 t4_add_adapter(struct adapter *sc)
3671 {
3672 	sx_xlock(&t4_list_lock);
3673 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3674 	sx_xunlock(&t4_list_lock);
3675 }
3676 
3677 int
3678 t4_map_bars_0_and_4(struct adapter *sc)
3679 {
3680 	sc->regs_rid = PCIR_BAR(0);
3681 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3682 	    &sc->regs_rid, RF_ACTIVE);
3683 	if (sc->regs_res == NULL) {
3684 		device_printf(sc->dev, "cannot map registers.\n");
3685 		return (ENXIO);
3686 	}
3687 	sc->bt = rman_get_bustag(sc->regs_res);
3688 	sc->bh = rman_get_bushandle(sc->regs_res);
3689 	sc->mmio_len = rman_get_size(sc->regs_res);
3690 	setbit(&sc->doorbells, DOORBELL_KDB);
3691 
3692 	sc->msix_rid = PCIR_BAR(4);
3693 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3694 	    &sc->msix_rid, RF_ACTIVE);
3695 	if (sc->msix_res == NULL) {
3696 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3697 		return (ENXIO);
3698 	}
3699 
3700 	return (0);
3701 }
3702 
3703 int
3704 t4_map_bar_2(struct adapter *sc)
3705 {
3706 
3707 	/*
3708 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3709 	 * to map it if RDMA is disabled.
3710 	 */
3711 	if (is_t4(sc) && sc->rdmacaps == 0)
3712 		return (0);
3713 
3714 	sc->udbs_rid = PCIR_BAR(2);
3715 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3716 	    &sc->udbs_rid, RF_ACTIVE);
3717 	if (sc->udbs_res == NULL) {
3718 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3719 		return (ENXIO);
3720 	}
3721 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3722 
3723 	if (chip_id(sc) >= CHELSIO_T5) {
3724 		setbit(&sc->doorbells, DOORBELL_UDB);
3725 #if defined(__i386__) || defined(__amd64__)
3726 		if (t5_write_combine) {
3727 			int rc, mode;
3728 
3729 			/*
3730 			 * Enable write combining on BAR2.  This is the
3731 			 * userspace doorbell BAR and is split into 128B
3732 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3733 			 * with an egress queue.  The first 64B has the doorbell
3734 			 * and the second 64B can be used to submit a tx work
3735 			 * request with an implicit doorbell.
3736 			 */
3737 
3738 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3739 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3740 			if (rc == 0) {
3741 				clrbit(&sc->doorbells, DOORBELL_UDB);
3742 				setbit(&sc->doorbells, DOORBELL_WCWR);
3743 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3744 			} else {
3745 				device_printf(sc->dev,
3746 				    "couldn't enable write combining: %d\n",
3747 				    rc);
3748 			}
3749 
3750 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3751 			t4_write_reg(sc, A_SGE_STAT_CFG,
3752 			    V_STATSOURCE_T5(7) | mode);
3753 		}
3754 #endif
3755 	}
3756 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3757 
3758 	return (0);
3759 }
3760 
3761 int
3762 t4_adj_doorbells(struct adapter *sc)
3763 {
3764 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3765 		sc->doorbells &= t4_doorbells_allowed;
3766 		return (0);
3767 	}
3768 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3769 	       sc->doorbells, t4_doorbells_allowed);
3770 	return (EINVAL);
3771 }
3772 
3773 struct memwin_init {
3774 	uint32_t base;
3775 	uint32_t aperture;
3776 };
3777 
3778 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3779 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3780 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3781 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3782 };
3783 
3784 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3785 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3786 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3787 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3788 };
3789 
3790 static void
3791 setup_memwin(struct adapter *sc)
3792 {
3793 	const struct memwin_init *mw_init;
3794 	struct memwin *mw;
3795 	int i;
3796 	uint32_t bar0;
3797 
3798 	if (is_t4(sc)) {
3799 		/*
3800 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3801 		 * mechanism.  Works from within PCI passthrough environments
3802 		 * too, where rman_get_start() can return a different value.  We
3803 		 * need to program the T4 memory window decoders with the actual
3804 		 * addresses that will be coming across the PCIe link.
3805 		 */
3806 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3807 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3808 
3809 		mw_init = &t4_memwin[0];
3810 	} else {
3811 		/* T5+ use the relative offset inside the PCIe BAR */
3812 		bar0 = 0;
3813 
3814 		mw_init = &t5_memwin[0];
3815 	}
3816 
3817 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3818 		if (!rw_initialized(&mw->mw_lock)) {
3819 			rw_init(&mw->mw_lock, "memory window access");
3820 			mw->mw_base = mw_init->base;
3821 			mw->mw_aperture = mw_init->aperture;
3822 			mw->mw_curpos = 0;
3823 		}
3824 		t4_write_reg(sc,
3825 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3826 		    (mw->mw_base + bar0) | V_BIR(0) |
3827 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3828 		rw_wlock(&mw->mw_lock);
3829 		position_memwin(sc, i, mw->mw_curpos);
3830 		rw_wunlock(&mw->mw_lock);
3831 	}
3832 
3833 	/* flush */
3834 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3835 }
3836 
3837 /*
3838  * Positions the memory window at the given address in the card's address space.
3839  * There are some alignment requirements and the actual position may be at an
3840  * address prior to the requested address.  mw->mw_curpos always has the actual
3841  * position of the window.
3842  */
3843 static void
3844 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3845 {
3846 	struct memwin *mw;
3847 	uint32_t pf;
3848 	uint32_t reg;
3849 
3850 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3851 	mw = &sc->memwin[idx];
3852 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3853 
3854 	if (is_t4(sc)) {
3855 		pf = 0;
3856 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3857 	} else {
3858 		pf = V_PFNUM(sc->pf);
3859 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3860 	}
3861 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3862 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3863 	t4_read_reg(sc, reg);	/* flush */
3864 }
3865 
3866 int
3867 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3868     int len, int rw)
3869 {
3870 	struct memwin *mw;
3871 	uint32_t mw_end, v;
3872 
3873 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3874 
3875 	/* Memory can only be accessed in naturally aligned 4 byte units */
3876 	if (addr & 3 || len & 3 || len <= 0)
3877 		return (EINVAL);
3878 
3879 	mw = &sc->memwin[idx];
3880 	while (len > 0) {
3881 		rw_rlock(&mw->mw_lock);
3882 		mw_end = mw->mw_curpos + mw->mw_aperture;
3883 		if (addr >= mw_end || addr < mw->mw_curpos) {
3884 			/* Will need to reposition the window */
3885 			if (!rw_try_upgrade(&mw->mw_lock)) {
3886 				rw_runlock(&mw->mw_lock);
3887 				rw_wlock(&mw->mw_lock);
3888 			}
3889 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3890 			position_memwin(sc, idx, addr);
3891 			rw_downgrade(&mw->mw_lock);
3892 			mw_end = mw->mw_curpos + mw->mw_aperture;
3893 		}
3894 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3895 		while (addr < mw_end && len > 0) {
3896 			if (rw == 0) {
3897 				v = t4_read_reg(sc, mw->mw_base + addr -
3898 				    mw->mw_curpos);
3899 				*val++ = le32toh(v);
3900 			} else {
3901 				v = *val++;
3902 				t4_write_reg(sc, mw->mw_base + addr -
3903 				    mw->mw_curpos, htole32(v));
3904 			}
3905 			addr += 4;
3906 			len -= 4;
3907 		}
3908 		rw_runlock(&mw->mw_lock);
3909 	}
3910 
3911 	return (0);
3912 }
3913 
3914 CTASSERT(M_TID_COOKIE == M_COOKIE);
3915 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3916 
3917 static void
3918 t4_init_atid_table(struct adapter *sc)
3919 {
3920 	struct tid_info *t;
3921 	int i;
3922 
3923 	t = &sc->tids;
3924 	if (t->natids == 0)
3925 		return;
3926 
3927 	MPASS(t->atid_tab == NULL);
3928 
3929 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3930 	    M_ZERO | M_WAITOK);
3931 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3932 	t->afree = t->atid_tab;
3933 	t->atids_in_use = 0;
3934 	for (i = 1; i < t->natids; i++)
3935 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3936 	t->atid_tab[t->natids - 1].next = NULL;
3937 }
3938 
3939 static void
3940 t4_free_atid_table(struct adapter *sc)
3941 {
3942 	struct tid_info *t;
3943 
3944 	t = &sc->tids;
3945 
3946 	KASSERT(t->atids_in_use == 0,
3947 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3948 
3949 	if (mtx_initialized(&t->atid_lock))
3950 		mtx_destroy(&t->atid_lock);
3951 	free(t->atid_tab, M_CXGBE);
3952 	t->atid_tab = NULL;
3953 }
3954 
3955 int
3956 alloc_atid(struct adapter *sc, void *ctx)
3957 {
3958 	struct tid_info *t = &sc->tids;
3959 	int atid = -1;
3960 
3961 	mtx_lock(&t->atid_lock);
3962 	if (t->afree) {
3963 		union aopen_entry *p = t->afree;
3964 
3965 		atid = p - t->atid_tab;
3966 		MPASS(atid <= M_TID_TID);
3967 		t->afree = p->next;
3968 		p->data = ctx;
3969 		t->atids_in_use++;
3970 	}
3971 	mtx_unlock(&t->atid_lock);
3972 	return (atid);
3973 }
3974 
3975 void *
3976 lookup_atid(struct adapter *sc, int atid)
3977 {
3978 	struct tid_info *t = &sc->tids;
3979 
3980 	return (t->atid_tab[atid].data);
3981 }
3982 
3983 void
3984 free_atid(struct adapter *sc, int atid)
3985 {
3986 	struct tid_info *t = &sc->tids;
3987 	union aopen_entry *p = &t->atid_tab[atid];
3988 
3989 	mtx_lock(&t->atid_lock);
3990 	p->next = t->afree;
3991 	t->afree = p;
3992 	t->atids_in_use--;
3993 	mtx_unlock(&t->atid_lock);
3994 }
3995 
3996 static void
3997 queue_tid_release(struct adapter *sc, int tid)
3998 {
3999 
4000 	CXGBE_UNIMPLEMENTED("deferred tid release");
4001 }
4002 
4003 void
4004 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4005 {
4006 	struct wrqe *wr;
4007 	struct cpl_tid_release *req;
4008 
4009 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4010 	if (wr == NULL) {
4011 		queue_tid_release(sc, tid);	/* defer */
4012 		return;
4013 	}
4014 	req = wrtod(wr);
4015 
4016 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4017 
4018 	t4_wrq_tx(sc, wr);
4019 }
4020 
4021 static int
4022 t4_range_cmp(const void *a, const void *b)
4023 {
4024 	return ((const struct t4_range *)a)->start -
4025 	       ((const struct t4_range *)b)->start;
4026 }
4027 
4028 /*
4029  * Verify that the memory range specified by the addr/len pair is valid within
4030  * the card's address space.
4031  */
4032 static int
4033 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4034 {
4035 	struct t4_range mem_ranges[4], *r, *next;
4036 	uint32_t em, addr_len;
4037 	int i, n, remaining;
4038 
4039 	/* Memory can only be accessed in naturally aligned 4 byte units */
4040 	if (addr & 3 || len & 3 || len == 0)
4041 		return (EINVAL);
4042 
4043 	/* Enabled memories */
4044 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4045 
4046 	r = &mem_ranges[0];
4047 	n = 0;
4048 	bzero(r, sizeof(mem_ranges));
4049 	if (em & F_EDRAM0_ENABLE) {
4050 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4051 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4052 		if (r->size > 0) {
4053 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4054 			if (addr >= r->start &&
4055 			    addr + len <= r->start + r->size)
4056 				return (0);
4057 			r++;
4058 			n++;
4059 		}
4060 	}
4061 	if (em & F_EDRAM1_ENABLE) {
4062 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4063 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4064 		if (r->size > 0) {
4065 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4066 			if (addr >= r->start &&
4067 			    addr + len <= r->start + r->size)
4068 				return (0);
4069 			r++;
4070 			n++;
4071 		}
4072 	}
4073 	if (em & F_EXT_MEM_ENABLE) {
4074 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4075 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4076 		if (r->size > 0) {
4077 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4078 			if (addr >= r->start &&
4079 			    addr + len <= r->start + r->size)
4080 				return (0);
4081 			r++;
4082 			n++;
4083 		}
4084 	}
4085 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4086 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4087 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4088 		if (r->size > 0) {
4089 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4090 			if (addr >= r->start &&
4091 			    addr + len <= r->start + r->size)
4092 				return (0);
4093 			r++;
4094 			n++;
4095 		}
4096 	}
4097 	MPASS(n <= nitems(mem_ranges));
4098 
4099 	if (n > 1) {
4100 		/* Sort and merge the ranges. */
4101 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4102 
4103 		/* Start from index 0 and examine the next n - 1 entries. */
4104 		r = &mem_ranges[0];
4105 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4106 
4107 			MPASS(r->size > 0);	/* r is a valid entry. */
4108 			next = r + 1;
4109 			MPASS(next->size > 0);	/* and so is the next one. */
4110 
4111 			while (r->start + r->size >= next->start) {
4112 				/* Merge the next one into the current entry. */
4113 				r->size = max(r->start + r->size,
4114 				    next->start + next->size) - r->start;
4115 				n--;	/* One fewer entry in total. */
4116 				if (--remaining == 0)
4117 					goto done;	/* short circuit */
4118 				next++;
4119 			}
4120 			if (next != r + 1) {
4121 				/*
4122 				 * Some entries were merged into r and next
4123 				 * points to the first valid entry that couldn't
4124 				 * be merged.
4125 				 */
4126 				MPASS(next->size > 0);	/* must be valid */
4127 				memcpy(r + 1, next, remaining * sizeof(*r));
4128 #ifdef INVARIANTS
4129 				/*
4130 				 * This so that the foo->size assertion in the
4131 				 * next iteration of the loop do the right
4132 				 * thing for entries that were pulled up and are
4133 				 * no longer valid.
4134 				 */
4135 				MPASS(n < nitems(mem_ranges));
4136 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4137 				    sizeof(struct t4_range));
4138 #endif
4139 			}
4140 		}
4141 done:
4142 		/* Done merging the ranges. */
4143 		MPASS(n > 0);
4144 		r = &mem_ranges[0];
4145 		for (i = 0; i < n; i++, r++) {
4146 			if (addr >= r->start &&
4147 			    addr + len <= r->start + r->size)
4148 				return (0);
4149 		}
4150 	}
4151 
4152 	return (EFAULT);
4153 }
4154 
4155 static int
4156 fwmtype_to_hwmtype(int mtype)
4157 {
4158 
4159 	switch (mtype) {
4160 	case FW_MEMTYPE_EDC0:
4161 		return (MEM_EDC0);
4162 	case FW_MEMTYPE_EDC1:
4163 		return (MEM_EDC1);
4164 	case FW_MEMTYPE_EXTMEM:
4165 		return (MEM_MC0);
4166 	case FW_MEMTYPE_EXTMEM1:
4167 		return (MEM_MC1);
4168 	default:
4169 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4170 	}
4171 }
4172 
4173 /*
4174  * Verify that the memory range specified by the memtype/offset/len pair is
4175  * valid and lies entirely within the memtype specified.  The global address of
4176  * the start of the range is returned in addr.
4177  */
4178 static int
4179 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4180     uint32_t *addr)
4181 {
4182 	uint32_t em, addr_len, maddr;
4183 
4184 	/* Memory can only be accessed in naturally aligned 4 byte units */
4185 	if (off & 3 || len & 3 || len == 0)
4186 		return (EINVAL);
4187 
4188 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4189 	switch (fwmtype_to_hwmtype(mtype)) {
4190 	case MEM_EDC0:
4191 		if (!(em & F_EDRAM0_ENABLE))
4192 			return (EINVAL);
4193 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4194 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4195 		break;
4196 	case MEM_EDC1:
4197 		if (!(em & F_EDRAM1_ENABLE))
4198 			return (EINVAL);
4199 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4200 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4201 		break;
4202 	case MEM_MC:
4203 		if (!(em & F_EXT_MEM_ENABLE))
4204 			return (EINVAL);
4205 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4206 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4207 		break;
4208 	case MEM_MC1:
4209 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4210 			return (EINVAL);
4211 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4212 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4213 		break;
4214 	default:
4215 		return (EINVAL);
4216 	}
4217 
4218 	*addr = maddr + off;	/* global address */
4219 	return (validate_mem_range(sc, *addr, len));
4220 }
4221 
4222 static int
4223 fixup_devlog_params(struct adapter *sc)
4224 {
4225 	struct devlog_params *dparams = &sc->params.devlog;
4226 	int rc;
4227 
4228 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4229 	    dparams->size, &dparams->addr);
4230 
4231 	return (rc);
4232 }
4233 
4234 static void
4235 update_nirq(struct intrs_and_queues *iaq, int nports)
4236 {
4237 
4238 	iaq->nirq = T4_EXTRA_INTR;
4239 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4240 	iaq->nirq += nports * iaq->nofldrxq;
4241 	iaq->nirq += nports * (iaq->num_vis - 1) *
4242 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4243 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4244 }
4245 
4246 /*
4247  * Adjust requirements to fit the number of interrupts available.
4248  */
4249 static void
4250 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4251     int navail)
4252 {
4253 	int old_nirq;
4254 	const int nports = sc->params.nports;
4255 
4256 	MPASS(nports > 0);
4257 	MPASS(navail > 0);
4258 
4259 	bzero(iaq, sizeof(*iaq));
4260 	iaq->intr_type = itype;
4261 	iaq->num_vis = t4_num_vis;
4262 	iaq->ntxq = t4_ntxq;
4263 	iaq->ntxq_vi = t4_ntxq_vi;
4264 	iaq->nrxq = t4_nrxq;
4265 	iaq->nrxq_vi = t4_nrxq_vi;
4266 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4267 	if (is_offload(sc) || is_ethoffload(sc)) {
4268 		iaq->nofldtxq = t4_nofldtxq;
4269 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4270 	}
4271 #endif
4272 #ifdef TCP_OFFLOAD
4273 	if (is_offload(sc)) {
4274 		iaq->nofldrxq = t4_nofldrxq;
4275 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4276 	}
4277 #endif
4278 #ifdef DEV_NETMAP
4279 	if (t4_native_netmap & NN_MAIN_VI) {
4280 		iaq->nnmtxq = t4_nnmtxq;
4281 		iaq->nnmrxq = t4_nnmrxq;
4282 	}
4283 	if (t4_native_netmap & NN_EXTRA_VI) {
4284 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4285 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4286 	}
4287 #endif
4288 
4289 	update_nirq(iaq, nports);
4290 	if (iaq->nirq <= navail &&
4291 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4292 		/*
4293 		 * This is the normal case -- there are enough interrupts for
4294 		 * everything.
4295 		 */
4296 		goto done;
4297 	}
4298 
4299 	/*
4300 	 * If extra VIs have been configured try reducing their count and see if
4301 	 * that works.
4302 	 */
4303 	while (iaq->num_vis > 1) {
4304 		iaq->num_vis--;
4305 		update_nirq(iaq, nports);
4306 		if (iaq->nirq <= navail &&
4307 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4308 			device_printf(sc->dev, "virtual interfaces per port "
4309 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4310 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4311 			    "itype %d, navail %u, nirq %d.\n",
4312 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4313 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4314 			    itype, navail, iaq->nirq);
4315 			goto done;
4316 		}
4317 	}
4318 
4319 	/*
4320 	 * Extra VIs will not be created.  Log a message if they were requested.
4321 	 */
4322 	MPASS(iaq->num_vis == 1);
4323 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4324 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4325 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4326 	if (iaq->num_vis != t4_num_vis) {
4327 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4328 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4329 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4330 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4331 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4332 	}
4333 
4334 	/*
4335 	 * Keep reducing the number of NIC rx queues to the next lower power of
4336 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4337 	 * if that works.
4338 	 */
4339 	do {
4340 		if (iaq->nrxq > 1) {
4341 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4342 			if (iaq->nnmrxq > iaq->nrxq)
4343 				iaq->nnmrxq = iaq->nrxq;
4344 		}
4345 		if (iaq->nofldrxq > 1)
4346 			iaq->nofldrxq >>= 1;
4347 
4348 		old_nirq = iaq->nirq;
4349 		update_nirq(iaq, nports);
4350 		if (iaq->nirq <= navail &&
4351 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4352 			device_printf(sc->dev, "running with reduced number of "
4353 			    "rx queues because of shortage of interrupts.  "
4354 			    "nrxq=%u, nofldrxq=%u.  "
4355 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4356 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4357 			goto done;
4358 		}
4359 	} while (old_nirq != iaq->nirq);
4360 
4361 	/* One interrupt for everything.  Ugh. */
4362 	device_printf(sc->dev, "running with minimal number of queues.  "
4363 	    "itype %d, navail %u.\n", itype, navail);
4364 	iaq->nirq = 1;
4365 	iaq->nrxq = 1;
4366 	iaq->ntxq = 1;
4367 	if (iaq->nofldrxq > 0) {
4368 		iaq->nofldrxq = 1;
4369 		iaq->nofldtxq = 1;
4370 	}
4371 	iaq->nnmtxq = 0;
4372 	iaq->nnmrxq = 0;
4373 done:
4374 	MPASS(iaq->num_vis > 0);
4375 	if (iaq->num_vis > 1) {
4376 		MPASS(iaq->nrxq_vi > 0);
4377 		MPASS(iaq->ntxq_vi > 0);
4378 	}
4379 	MPASS(iaq->nirq > 0);
4380 	MPASS(iaq->nrxq > 0);
4381 	MPASS(iaq->ntxq > 0);
4382 	if (itype == INTR_MSI) {
4383 		MPASS(powerof2(iaq->nirq));
4384 	}
4385 }
4386 
4387 static int
4388 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4389 {
4390 	int rc, itype, navail, nalloc;
4391 
4392 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4393 
4394 		if ((itype & t4_intr_types) == 0)
4395 			continue;	/* not allowed */
4396 
4397 		if (itype == INTR_MSIX)
4398 			navail = pci_msix_count(sc->dev);
4399 		else if (itype == INTR_MSI)
4400 			navail = pci_msi_count(sc->dev);
4401 		else
4402 			navail = 1;
4403 restart:
4404 		if (navail == 0)
4405 			continue;
4406 
4407 		calculate_iaq(sc, iaq, itype, navail);
4408 		nalloc = iaq->nirq;
4409 		rc = 0;
4410 		if (itype == INTR_MSIX)
4411 			rc = pci_alloc_msix(sc->dev, &nalloc);
4412 		else if (itype == INTR_MSI)
4413 			rc = pci_alloc_msi(sc->dev, &nalloc);
4414 
4415 		if (rc == 0 && nalloc > 0) {
4416 			if (nalloc == iaq->nirq)
4417 				return (0);
4418 
4419 			/*
4420 			 * Didn't get the number requested.  Use whatever number
4421 			 * the kernel is willing to allocate.
4422 			 */
4423 			device_printf(sc->dev, "fewer vectors than requested, "
4424 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4425 			    itype, iaq->nirq, nalloc);
4426 			pci_release_msi(sc->dev);
4427 			navail = nalloc;
4428 			goto restart;
4429 		}
4430 
4431 		device_printf(sc->dev,
4432 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4433 		    itype, rc, iaq->nirq, nalloc);
4434 	}
4435 
4436 	device_printf(sc->dev,
4437 	    "failed to find a usable interrupt type.  "
4438 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4439 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4440 
4441 	return (ENXIO);
4442 }
4443 
4444 #define FW_VERSION(chip) ( \
4445     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4446     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4447     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4448     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4449 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4450 
4451 /* Just enough of fw_hdr to cover all version info. */
4452 struct fw_h {
4453 	__u8	ver;
4454 	__u8	chip;
4455 	__be16	len512;
4456 	__be32	fw_ver;
4457 	__be32	tp_microcode_ver;
4458 	__u8	intfver_nic;
4459 	__u8	intfver_vnic;
4460 	__u8	intfver_ofld;
4461 	__u8	intfver_ri;
4462 	__u8	intfver_iscsipdu;
4463 	__u8	intfver_iscsi;
4464 	__u8	intfver_fcoepdu;
4465 	__u8	intfver_fcoe;
4466 };
4467 /* Spot check a couple of fields. */
4468 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4469 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4470 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4471 
4472 struct fw_info {
4473 	uint8_t chip;
4474 	char *kld_name;
4475 	char *fw_mod_name;
4476 	struct fw_h fw_h;
4477 } fw_info[] = {
4478 	{
4479 		.chip = CHELSIO_T4,
4480 		.kld_name = "t4fw_cfg",
4481 		.fw_mod_name = "t4fw",
4482 		.fw_h = {
4483 			.chip = FW_HDR_CHIP_T4,
4484 			.fw_ver = htobe32(FW_VERSION(T4)),
4485 			.intfver_nic = FW_INTFVER(T4, NIC),
4486 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4487 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4488 			.intfver_ri = FW_INTFVER(T4, RI),
4489 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4490 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4491 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4492 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4493 		},
4494 	}, {
4495 		.chip = CHELSIO_T5,
4496 		.kld_name = "t5fw_cfg",
4497 		.fw_mod_name = "t5fw",
4498 		.fw_h = {
4499 			.chip = FW_HDR_CHIP_T5,
4500 			.fw_ver = htobe32(FW_VERSION(T5)),
4501 			.intfver_nic = FW_INTFVER(T5, NIC),
4502 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4503 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4504 			.intfver_ri = FW_INTFVER(T5, RI),
4505 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4506 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4507 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4508 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4509 		},
4510 	}, {
4511 		.chip = CHELSIO_T6,
4512 		.kld_name = "t6fw_cfg",
4513 		.fw_mod_name = "t6fw",
4514 		.fw_h = {
4515 			.chip = FW_HDR_CHIP_T6,
4516 			.fw_ver = htobe32(FW_VERSION(T6)),
4517 			.intfver_nic = FW_INTFVER(T6, NIC),
4518 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4519 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4520 			.intfver_ri = FW_INTFVER(T6, RI),
4521 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4522 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4523 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4524 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4525 		},
4526 	}
4527 };
4528 
4529 static struct fw_info *
4530 find_fw_info(int chip)
4531 {
4532 	int i;
4533 
4534 	for (i = 0; i < nitems(fw_info); i++) {
4535 		if (fw_info[i].chip == chip)
4536 			return (&fw_info[i]);
4537 	}
4538 	return (NULL);
4539 }
4540 
4541 /*
4542  * Is the given firmware API compatible with the one the driver was compiled
4543  * with?
4544  */
4545 static int
4546 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4547 {
4548 
4549 	/* short circuit if it's the exact same firmware version */
4550 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4551 		return (1);
4552 
4553 	/*
4554 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4555 	 * features that are supported in the driver.
4556 	 */
4557 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4558 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4559 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4560 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4561 		return (1);
4562 #undef SAME_INTF
4563 
4564 	return (0);
4565 }
4566 
4567 static int
4568 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4569     const struct firmware **fw)
4570 {
4571 	struct fw_info *fw_info;
4572 
4573 	*dcfg = NULL;
4574 	if (fw != NULL)
4575 		*fw = NULL;
4576 
4577 	fw_info = find_fw_info(chip_id(sc));
4578 	if (fw_info == NULL) {
4579 		device_printf(sc->dev,
4580 		    "unable to look up firmware information for chip %d.\n",
4581 		    chip_id(sc));
4582 		return (EINVAL);
4583 	}
4584 
4585 	*dcfg = firmware_get(fw_info->kld_name);
4586 	if (*dcfg != NULL) {
4587 		if (fw != NULL)
4588 			*fw = firmware_get(fw_info->fw_mod_name);
4589 		return (0);
4590 	}
4591 
4592 	return (ENOENT);
4593 }
4594 
4595 static void
4596 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4597     const struct firmware *fw)
4598 {
4599 
4600 	if (fw != NULL)
4601 		firmware_put(fw, FIRMWARE_UNLOAD);
4602 	if (dcfg != NULL)
4603 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4604 }
4605 
4606 /*
4607  * Return values:
4608  * 0 means no firmware install attempted.
4609  * ERESTART means a firmware install was attempted and was successful.
4610  * +ve errno means a firmware install was attempted but failed.
4611  */
4612 static int
4613 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4614     const struct fw_h *drv_fw, const char *reason, int *already)
4615 {
4616 	const struct firmware *cfg, *fw;
4617 	const uint32_t c = be32toh(card_fw->fw_ver);
4618 	uint32_t d, k;
4619 	int rc, fw_install;
4620 	struct fw_h bundled_fw;
4621 	bool load_attempted;
4622 
4623 	cfg = fw = NULL;
4624 	load_attempted = false;
4625 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4626 
4627 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4628 	if (t4_fw_install < 0) {
4629 		rc = load_fw_module(sc, &cfg, &fw);
4630 		if (rc != 0 || fw == NULL) {
4631 			device_printf(sc->dev,
4632 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4633 			    " will use compiled-in firmware version for"
4634 			    "hw.cxgbe.fw_install checks.\n",
4635 			    rc, cfg, fw);
4636 		} else {
4637 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4638 		}
4639 		load_attempted = true;
4640 	}
4641 	d = be32toh(bundled_fw.fw_ver);
4642 
4643 	if (reason != NULL)
4644 		goto install;
4645 
4646 	if ((sc->flags & FW_OK) == 0) {
4647 
4648 		if (c == 0xffffffff) {
4649 			reason = "missing";
4650 			goto install;
4651 		}
4652 
4653 		rc = 0;
4654 		goto done;
4655 	}
4656 
4657 	if (!fw_compatible(card_fw, &bundled_fw)) {
4658 		reason = "incompatible or unusable";
4659 		goto install;
4660 	}
4661 
4662 	if (d > c) {
4663 		reason = "older than the version bundled with this driver";
4664 		goto install;
4665 	}
4666 
4667 	if (fw_install == 2 && d != c) {
4668 		reason = "different than the version bundled with this driver";
4669 		goto install;
4670 	}
4671 
4672 	/* No reason to do anything to the firmware already on the card. */
4673 	rc = 0;
4674 	goto done;
4675 
4676 install:
4677 	rc = 0;
4678 	if ((*already)++)
4679 		goto done;
4680 
4681 	if (fw_install == 0) {
4682 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4683 		    "but the driver is prohibited from installing a firmware "
4684 		    "on the card.\n",
4685 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4686 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4687 
4688 		goto done;
4689 	}
4690 
4691 	/*
4692 	 * We'll attempt to install a firmware.  Load the module first (if it
4693 	 * hasn't been loaded already).
4694 	 */
4695 	if (!load_attempted) {
4696 		rc = load_fw_module(sc, &cfg, &fw);
4697 		if (rc != 0 || fw == NULL) {
4698 			device_printf(sc->dev,
4699 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4700 			    rc, cfg, fw);
4701 			/* carry on */
4702 		}
4703 	}
4704 	if (fw == NULL) {
4705 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4706 		    "but the driver cannot take corrective action because it "
4707 		    "is unable to load the firmware module.\n",
4708 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4709 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4710 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4711 		goto done;
4712 	}
4713 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4714 	if (k != d) {
4715 		MPASS(t4_fw_install > 0);
4716 		device_printf(sc->dev,
4717 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4718 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4719 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4720 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4721 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4722 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4723 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4724 		goto done;
4725 	}
4726 
4727 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4728 	    "installing firmware %u.%u.%u.%u on card.\n",
4729 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4730 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4731 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4732 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4733 
4734 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4735 	if (rc != 0) {
4736 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4737 	} else {
4738 		/* Installed successfully, update the cached header too. */
4739 		rc = ERESTART;
4740 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4741 	}
4742 done:
4743 	unload_fw_module(sc, cfg, fw);
4744 
4745 	return (rc);
4746 }
4747 
4748 /*
4749  * Establish contact with the firmware and attempt to become the master driver.
4750  *
4751  * A firmware will be installed to the card if needed (if the driver is allowed
4752  * to do so).
4753  */
4754 static int
4755 contact_firmware(struct adapter *sc)
4756 {
4757 	int rc, already = 0;
4758 	enum dev_state state;
4759 	struct fw_info *fw_info;
4760 	struct fw_hdr *card_fw;		/* fw on the card */
4761 	const struct fw_h *drv_fw;
4762 
4763 	fw_info = find_fw_info(chip_id(sc));
4764 	if (fw_info == NULL) {
4765 		device_printf(sc->dev,
4766 		    "unable to look up firmware information for chip %d.\n",
4767 		    chip_id(sc));
4768 		return (EINVAL);
4769 	}
4770 	drv_fw = &fw_info->fw_h;
4771 
4772 	/* Read the header of the firmware on the card */
4773 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4774 restart:
4775 	rc = -t4_get_fw_hdr(sc, card_fw);
4776 	if (rc != 0) {
4777 		device_printf(sc->dev,
4778 		    "unable to read firmware header from card's flash: %d\n",
4779 		    rc);
4780 		goto done;
4781 	}
4782 
4783 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4784 	    &already);
4785 	if (rc == ERESTART)
4786 		goto restart;
4787 	if (rc != 0)
4788 		goto done;
4789 
4790 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4791 	if (rc < 0 || state == DEV_STATE_ERR) {
4792 		rc = -rc;
4793 		device_printf(sc->dev,
4794 		    "failed to connect to the firmware: %d, %d.  "
4795 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4796 #if 0
4797 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4798 		    "not responding properly to HELLO", &already) == ERESTART)
4799 			goto restart;
4800 #endif
4801 		goto done;
4802 	}
4803 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4804 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4805 
4806 	if (rc == sc->pf) {
4807 		sc->flags |= MASTER_PF;
4808 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4809 		    NULL, &already);
4810 		if (rc == ERESTART)
4811 			rc = 0;
4812 		else if (rc != 0)
4813 			goto done;
4814 	} else if (state == DEV_STATE_UNINIT) {
4815 		/*
4816 		 * We didn't get to be the master so we definitely won't be
4817 		 * configuring the chip.  It's a bug if someone else hasn't
4818 		 * configured it already.
4819 		 */
4820 		device_printf(sc->dev, "couldn't be master(%d), "
4821 		    "device not already initialized either(%d).  "
4822 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4823 		rc = EPROTO;
4824 		goto done;
4825 	} else {
4826 		/*
4827 		 * Some other PF is the master and has configured the chip.
4828 		 * This is allowed but untested.
4829 		 */
4830 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4831 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4832 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4833 		sc->cfcsum = 0;
4834 		rc = 0;
4835 	}
4836 done:
4837 	if (rc != 0 && sc->flags & FW_OK) {
4838 		t4_fw_bye(sc, sc->mbox);
4839 		sc->flags &= ~FW_OK;
4840 	}
4841 	free(card_fw, M_CXGBE);
4842 	return (rc);
4843 }
4844 
4845 static int
4846 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4847     uint32_t mtype, uint32_t moff)
4848 {
4849 	struct fw_info *fw_info;
4850 	const struct firmware *dcfg, *rcfg = NULL;
4851 	const uint32_t *cfdata;
4852 	uint32_t cflen, addr;
4853 	int rc;
4854 
4855 	load_fw_module(sc, &dcfg, NULL);
4856 
4857 	/* Card specific interpretation of "default". */
4858 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4859 		if (pci_get_device(sc->dev) == 0x440a)
4860 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4861 		if (is_fpga(sc))
4862 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4863 	}
4864 
4865 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4866 		if (dcfg == NULL) {
4867 			device_printf(sc->dev,
4868 			    "KLD with default config is not available.\n");
4869 			rc = ENOENT;
4870 			goto done;
4871 		}
4872 		cfdata = dcfg->data;
4873 		cflen = dcfg->datasize & ~3;
4874 	} else {
4875 		char s[32];
4876 
4877 		fw_info = find_fw_info(chip_id(sc));
4878 		if (fw_info == NULL) {
4879 			device_printf(sc->dev,
4880 			    "unable to look up firmware information for chip %d.\n",
4881 			    chip_id(sc));
4882 			rc = EINVAL;
4883 			goto done;
4884 		}
4885 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4886 
4887 		rcfg = firmware_get(s);
4888 		if (rcfg == NULL) {
4889 			device_printf(sc->dev,
4890 			    "unable to load module \"%s\" for configuration "
4891 			    "profile \"%s\".\n", s, cfg_file);
4892 			rc = ENOENT;
4893 			goto done;
4894 		}
4895 		cfdata = rcfg->data;
4896 		cflen = rcfg->datasize & ~3;
4897 	}
4898 
4899 	if (cflen > FLASH_CFG_MAX_SIZE) {
4900 		device_printf(sc->dev,
4901 		    "config file too long (%d, max allowed is %d).\n",
4902 		    cflen, FLASH_CFG_MAX_SIZE);
4903 		rc = EINVAL;
4904 		goto done;
4905 	}
4906 
4907 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4908 	if (rc != 0) {
4909 		device_printf(sc->dev,
4910 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4911 		    __func__, mtype, moff, cflen, rc);
4912 		rc = EINVAL;
4913 		goto done;
4914 	}
4915 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4916 done:
4917 	if (rcfg != NULL)
4918 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4919 	unload_fw_module(sc, dcfg, NULL);
4920 	return (rc);
4921 }
4922 
4923 struct caps_allowed {
4924 	uint16_t nbmcaps;
4925 	uint16_t linkcaps;
4926 	uint16_t switchcaps;
4927 	uint16_t niccaps;
4928 	uint16_t toecaps;
4929 	uint16_t rdmacaps;
4930 	uint16_t cryptocaps;
4931 	uint16_t iscsicaps;
4932 	uint16_t fcoecaps;
4933 };
4934 
4935 #define FW_PARAM_DEV(param) \
4936 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4937 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4938 #define FW_PARAM_PFVF(param) \
4939 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4940 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4941 
4942 /*
4943  * Provide a configuration profile to the firmware and have it initialize the
4944  * chip accordingly.  This may involve uploading a configuration file to the
4945  * card.
4946  */
4947 static int
4948 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4949     const struct caps_allowed *caps_allowed)
4950 {
4951 	int rc;
4952 	struct fw_caps_config_cmd caps;
4953 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4954 
4955 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4956 	if (rc != 0) {
4957 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4958 		return (rc);
4959 	}
4960 
4961 	bzero(&caps, sizeof(caps));
4962 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4963 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4964 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4965 		mtype = 0;
4966 		moff = 0;
4967 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4968 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4969 		mtype = FW_MEMTYPE_FLASH;
4970 		moff = t4_flash_cfg_addr(sc);
4971 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4972 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4973 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4974 		    FW_LEN16(caps));
4975 	} else {
4976 		/*
4977 		 * Ask the firmware where it wants us to upload the config file.
4978 		 */
4979 		param = FW_PARAM_DEV(CF);
4980 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4981 		if (rc != 0) {
4982 			/* No support for config file?  Shouldn't happen. */
4983 			device_printf(sc->dev,
4984 			    "failed to query config file location: %d.\n", rc);
4985 			goto done;
4986 		}
4987 		mtype = G_FW_PARAMS_PARAM_Y(val);
4988 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4989 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4990 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4991 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4992 		    FW_LEN16(caps));
4993 
4994 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4995 		if (rc != 0) {
4996 			device_printf(sc->dev,
4997 			    "failed to upload config file to card: %d.\n", rc);
4998 			goto done;
4999 		}
5000 	}
5001 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5002 	if (rc != 0) {
5003 		device_printf(sc->dev, "failed to pre-process config file: %d "
5004 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5005 		goto done;
5006 	}
5007 
5008 	finicsum = be32toh(caps.finicsum);
5009 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5010 	if (finicsum != cfcsum) {
5011 		device_printf(sc->dev,
5012 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5013 		    finicsum, cfcsum);
5014 	}
5015 	sc->cfcsum = cfcsum;
5016 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5017 
5018 	/*
5019 	 * Let the firmware know what features will (not) be used so it can tune
5020 	 * things accordingly.
5021 	 */
5022 #define LIMIT_CAPS(x) do { \
5023 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5024 } while (0)
5025 	LIMIT_CAPS(nbm);
5026 	LIMIT_CAPS(link);
5027 	LIMIT_CAPS(switch);
5028 	LIMIT_CAPS(nic);
5029 	LIMIT_CAPS(toe);
5030 	LIMIT_CAPS(rdma);
5031 	LIMIT_CAPS(crypto);
5032 	LIMIT_CAPS(iscsi);
5033 	LIMIT_CAPS(fcoe);
5034 #undef LIMIT_CAPS
5035 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5036 		/*
5037 		 * TOE and hashfilters are mutually exclusive.  It is a config
5038 		 * file or firmware bug if both are reported as available.  Try
5039 		 * to cope with the situation in non-debug builds by disabling
5040 		 * TOE.
5041 		 */
5042 		MPASS(caps.toecaps == 0);
5043 
5044 		caps.toecaps = 0;
5045 		caps.rdmacaps = 0;
5046 		caps.iscsicaps = 0;
5047 	}
5048 
5049 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5050 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5051 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5052 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5053 	if (rc != 0) {
5054 		device_printf(sc->dev,
5055 		    "failed to process config file: %d.\n", rc);
5056 		goto done;
5057 	}
5058 
5059 	t4_tweak_chip_settings(sc);
5060 	set_params__pre_init(sc);
5061 
5062 	/* get basic stuff going */
5063 	rc = -t4_fw_initialize(sc, sc->mbox);
5064 	if (rc != 0) {
5065 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5066 		goto done;
5067 	}
5068 done:
5069 	return (rc);
5070 }
5071 
5072 /*
5073  * Partition chip resources for use between various PFs, VFs, etc.
5074  */
5075 static int
5076 partition_resources(struct adapter *sc)
5077 {
5078 	char cfg_file[sizeof(t4_cfg_file)];
5079 	struct caps_allowed caps_allowed;
5080 	int rc;
5081 	bool fallback;
5082 
5083 	/* Only the master driver gets to configure the chip resources. */
5084 	MPASS(sc->flags & MASTER_PF);
5085 
5086 #define COPY_CAPS(x) do { \
5087 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5088 } while (0)
5089 	bzero(&caps_allowed, sizeof(caps_allowed));
5090 	COPY_CAPS(nbm);
5091 	COPY_CAPS(link);
5092 	COPY_CAPS(switch);
5093 	COPY_CAPS(nic);
5094 	COPY_CAPS(toe);
5095 	COPY_CAPS(rdma);
5096 	COPY_CAPS(crypto);
5097 	COPY_CAPS(iscsi);
5098 	COPY_CAPS(fcoe);
5099 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5100 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5101 retry:
5102 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5103 	if (rc != 0 && fallback) {
5104 		dump_devlog(sc);
5105 		device_printf(sc->dev,
5106 		    "failed (%d) to configure card with \"%s\" profile, "
5107 		    "will fall back to a basic configuration and retry.\n",
5108 		    rc, cfg_file);
5109 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5110 		bzero(&caps_allowed, sizeof(caps_allowed));
5111 		COPY_CAPS(switch);
5112 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5113 		fallback = false;
5114 		goto retry;
5115 	}
5116 #undef COPY_CAPS
5117 	return (rc);
5118 }
5119 
5120 /*
5121  * Retrieve parameters that are needed (or nice to have) very early.
5122  */
5123 static int
5124 get_params__pre_init(struct adapter *sc)
5125 {
5126 	int rc;
5127 	uint32_t param[2], val[2];
5128 
5129 	t4_get_version_info(sc);
5130 
5131 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5132 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5133 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5134 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5135 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5136 
5137 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5138 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5139 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5140 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5141 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5142 
5143 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5144 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5145 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5146 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5147 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5148 
5149 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5150 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5151 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5152 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5153 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5154 
5155 	param[0] = FW_PARAM_DEV(PORTVEC);
5156 	param[1] = FW_PARAM_DEV(CCLK);
5157 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5158 	if (rc != 0) {
5159 		device_printf(sc->dev,
5160 		    "failed to query parameters (pre_init): %d.\n", rc);
5161 		return (rc);
5162 	}
5163 
5164 	sc->params.portvec = val[0];
5165 	sc->params.nports = bitcount32(val[0]);
5166 	sc->params.vpd.cclk = val[1];
5167 
5168 	/* Read device log parameters. */
5169 	rc = -t4_init_devlog_params(sc, 1);
5170 	if (rc == 0)
5171 		fixup_devlog_params(sc);
5172 	else {
5173 		device_printf(sc->dev,
5174 		    "failed to get devlog parameters: %d.\n", rc);
5175 		rc = 0;	/* devlog isn't critical for device operation */
5176 	}
5177 
5178 	return (rc);
5179 }
5180 
5181 /*
5182  * Any params that need to be set before FW_INITIALIZE.
5183  */
5184 static int
5185 set_params__pre_init(struct adapter *sc)
5186 {
5187 	int rc = 0;
5188 	uint32_t param, val;
5189 
5190 	if (chip_id(sc) >= CHELSIO_T6) {
5191 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5192 		val = 1;
5193 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5194 		/* firmwares < 1.20.1.0 do not have this param. */
5195 		if (rc == FW_EINVAL &&
5196 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5197 			rc = 0;
5198 		}
5199 		if (rc != 0) {
5200 			device_printf(sc->dev,
5201 			    "failed to enable high priority filters :%d.\n",
5202 			    rc);
5203 		}
5204 
5205 		param = FW_PARAM_DEV(PPOD_EDRAM);
5206 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5207 		if (rc == 0 && val == 1) {
5208 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5209 			    &val);
5210 			if (rc != 0) {
5211 				device_printf(sc->dev,
5212 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5213 			}
5214 		}
5215 	}
5216 
5217 	/* Enable opaque VIIDs with firmwares that support it. */
5218 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5219 	val = 1;
5220 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5221 	if (rc == 0 && val == 1)
5222 		sc->params.viid_smt_extn_support = true;
5223 	else
5224 		sc->params.viid_smt_extn_support = false;
5225 
5226 	return (rc);
5227 }
5228 
5229 /*
5230  * Retrieve various parameters that are of interest to the driver.  The device
5231  * has been initialized by the firmware at this point.
5232  */
5233 static int
5234 get_params__post_init(struct adapter *sc)
5235 {
5236 	int rc;
5237 	uint32_t param[7], val[7];
5238 	struct fw_caps_config_cmd caps;
5239 
5240 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5241 	param[1] = FW_PARAM_PFVF(EQ_START);
5242 	param[2] = FW_PARAM_PFVF(FILTER_START);
5243 	param[3] = FW_PARAM_PFVF(FILTER_END);
5244 	param[4] = FW_PARAM_PFVF(L2T_START);
5245 	param[5] = FW_PARAM_PFVF(L2T_END);
5246 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5247 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5248 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5249 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5250 	if (rc != 0) {
5251 		device_printf(sc->dev,
5252 		    "failed to query parameters (post_init): %d.\n", rc);
5253 		return (rc);
5254 	}
5255 
5256 	sc->sge.iq_start = val[0];
5257 	sc->sge.eq_start = val[1];
5258 	if ((int)val[3] > (int)val[2]) {
5259 		sc->tids.ftid_base = val[2];
5260 		sc->tids.ftid_end = val[3];
5261 		sc->tids.nftids = val[3] - val[2] + 1;
5262 	}
5263 	sc->vres.l2t.start = val[4];
5264 	sc->vres.l2t.size = val[5] - val[4] + 1;
5265 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5266 	    ("%s: L2 table size (%u) larger than expected (%u)",
5267 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5268 	sc->params.core_vdd = val[6];
5269 
5270 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5271 	param[1] = FW_PARAM_PFVF(EQ_END);
5272 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5273 	if (rc != 0) {
5274 		device_printf(sc->dev,
5275 		    "failed to query parameters (post_init2): %d.\n", rc);
5276 		return (rc);
5277 	}
5278 	MPASS((int)val[0] >= sc->sge.iq_start);
5279 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5280 	MPASS((int)val[1] >= sc->sge.eq_start);
5281 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5282 
5283 	if (chip_id(sc) >= CHELSIO_T6) {
5284 
5285 		sc->tids.tid_base = t4_read_reg(sc,
5286 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5287 
5288 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5289 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5290 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5291 		if (rc != 0) {
5292 			device_printf(sc->dev,
5293 			   "failed to query hpfilter parameters: %d.\n", rc);
5294 			return (rc);
5295 		}
5296 		if ((int)val[1] > (int)val[0]) {
5297 			sc->tids.hpftid_base = val[0];
5298 			sc->tids.hpftid_end = val[1];
5299 			sc->tids.nhpftids = val[1] - val[0] + 1;
5300 
5301 			/*
5302 			 * These should go off if the layout changes and the
5303 			 * driver needs to catch up.
5304 			 */
5305 			MPASS(sc->tids.hpftid_base == 0);
5306 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5307 		}
5308 
5309 		param[0] = FW_PARAM_PFVF(RAWF_START);
5310 		param[1] = FW_PARAM_PFVF(RAWF_END);
5311 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5312 		if (rc != 0) {
5313 			device_printf(sc->dev,
5314 			   "failed to query rawf parameters: %d.\n", rc);
5315 			return (rc);
5316 		}
5317 		if ((int)val[1] > (int)val[0]) {
5318 			sc->rawf_base = val[0];
5319 			sc->nrawf = val[1] - val[0] + 1;
5320 		}
5321 	}
5322 
5323 	/*
5324 	 * The parameters that follow may not be available on all firmwares.  We
5325 	 * query them individually rather than in a compound query because old
5326 	 * firmwares fail the entire query if an unknown parameter is queried.
5327 	 */
5328 
5329 	/*
5330 	 * MPS buffer group configuration.
5331 	 */
5332 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5333 	val[0] = 0;
5334 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5335 	if (rc == 0)
5336 		sc->params.mps_bg_map = val[0];
5337 	else
5338 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5339 
5340 	param[0] = FW_PARAM_DEV(TPCHMAP);
5341 	val[0] = 0;
5342 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5343 	if (rc == 0)
5344 		sc->params.tp_ch_map = val[0];
5345 	else
5346 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5347 
5348 	/*
5349 	 * Determine whether the firmware supports the filter2 work request.
5350 	 */
5351 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5352 	val[0] = 0;
5353 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5354 	if (rc == 0)
5355 		sc->params.filter2_wr_support = val[0] != 0;
5356 	else
5357 		sc->params.filter2_wr_support = 0;
5358 
5359 	/*
5360 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5361 	 */
5362 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5363 	val[0] = 0;
5364 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5365 	if (rc == 0)
5366 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5367 	else
5368 		sc->params.ulptx_memwrite_dsgl = false;
5369 
5370 	/* FW_RI_FR_NSMR_TPTE_WR support */
5371 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5372 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5373 	if (rc == 0)
5374 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5375 	else
5376 		sc->params.fr_nsmr_tpte_wr_support = false;
5377 
5378 	/* Support for 512 SGL entries per FR MR. */
5379 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5380 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5381 	if (rc == 0)
5382 		sc->params.dev_512sgl_mr = val[0] != 0;
5383 	else
5384 		sc->params.dev_512sgl_mr = false;
5385 
5386 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5387 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5388 	if (rc == 0)
5389 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5390 	else
5391 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5392 
5393 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5394 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5395 	if (rc == 0) {
5396 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5397 		sc->params.nsched_cls = val[0];
5398 	} else
5399 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5400 
5401 	/* get capabilites */
5402 	bzero(&caps, sizeof(caps));
5403 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5404 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5405 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5406 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5407 	if (rc != 0) {
5408 		device_printf(sc->dev,
5409 		    "failed to get card capabilities: %d.\n", rc);
5410 		return (rc);
5411 	}
5412 
5413 #define READ_CAPS(x) do { \
5414 	sc->x = htobe16(caps.x); \
5415 } while (0)
5416 	READ_CAPS(nbmcaps);
5417 	READ_CAPS(linkcaps);
5418 	READ_CAPS(switchcaps);
5419 	READ_CAPS(niccaps);
5420 	READ_CAPS(toecaps);
5421 	READ_CAPS(rdmacaps);
5422 	READ_CAPS(cryptocaps);
5423 	READ_CAPS(iscsicaps);
5424 	READ_CAPS(fcoecaps);
5425 
5426 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5427 		MPASS(chip_id(sc) > CHELSIO_T4);
5428 		MPASS(sc->toecaps == 0);
5429 		sc->toecaps = 0;
5430 
5431 		param[0] = FW_PARAM_DEV(NTID);
5432 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5433 		if (rc != 0) {
5434 			device_printf(sc->dev,
5435 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5436 			return (rc);
5437 		}
5438 		sc->tids.ntids = val[0];
5439 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5440 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5441 			sc->tids.ntids -= sc->tids.nhpftids;
5442 		}
5443 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5444 		sc->params.hash_filter = 1;
5445 	}
5446 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5447 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5448 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5449 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5450 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5451 		if (rc != 0) {
5452 			device_printf(sc->dev,
5453 			    "failed to query NIC parameters: %d.\n", rc);
5454 			return (rc);
5455 		}
5456 		if ((int)val[1] > (int)val[0]) {
5457 			sc->tids.etid_base = val[0];
5458 			sc->tids.etid_end = val[1];
5459 			sc->tids.netids = val[1] - val[0] + 1;
5460 			sc->params.eo_wr_cred = val[2];
5461 			sc->params.ethoffload = 1;
5462 		}
5463 	}
5464 	if (sc->toecaps) {
5465 		/* query offload-related parameters */
5466 		param[0] = FW_PARAM_DEV(NTID);
5467 		param[1] = FW_PARAM_PFVF(SERVER_START);
5468 		param[2] = FW_PARAM_PFVF(SERVER_END);
5469 		param[3] = FW_PARAM_PFVF(TDDP_START);
5470 		param[4] = FW_PARAM_PFVF(TDDP_END);
5471 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5472 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5473 		if (rc != 0) {
5474 			device_printf(sc->dev,
5475 			    "failed to query TOE parameters: %d.\n", rc);
5476 			return (rc);
5477 		}
5478 		sc->tids.ntids = val[0];
5479 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5480 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5481 			sc->tids.ntids -= sc->tids.nhpftids;
5482 		}
5483 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5484 		if ((int)val[2] > (int)val[1]) {
5485 			sc->tids.stid_base = val[1];
5486 			sc->tids.nstids = val[2] - val[1] + 1;
5487 		}
5488 		sc->vres.ddp.start = val[3];
5489 		sc->vres.ddp.size = val[4] - val[3] + 1;
5490 		sc->params.ofldq_wr_cred = val[5];
5491 		sc->params.offload = 1;
5492 	} else {
5493 		/*
5494 		 * The firmware attempts memfree TOE configuration for -SO cards
5495 		 * and will report toecaps=0 if it runs out of resources (this
5496 		 * depends on the config file).  It may not report 0 for other
5497 		 * capabilities dependent on the TOE in this case.  Set them to
5498 		 * 0 here so that the driver doesn't bother tracking resources
5499 		 * that will never be used.
5500 		 */
5501 		sc->iscsicaps = 0;
5502 		sc->rdmacaps = 0;
5503 	}
5504 	if (sc->rdmacaps) {
5505 		param[0] = FW_PARAM_PFVF(STAG_START);
5506 		param[1] = FW_PARAM_PFVF(STAG_END);
5507 		param[2] = FW_PARAM_PFVF(RQ_START);
5508 		param[3] = FW_PARAM_PFVF(RQ_END);
5509 		param[4] = FW_PARAM_PFVF(PBL_START);
5510 		param[5] = FW_PARAM_PFVF(PBL_END);
5511 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5512 		if (rc != 0) {
5513 			device_printf(sc->dev,
5514 			    "failed to query RDMA parameters(1): %d.\n", rc);
5515 			return (rc);
5516 		}
5517 		sc->vres.stag.start = val[0];
5518 		sc->vres.stag.size = val[1] - val[0] + 1;
5519 		sc->vres.rq.start = val[2];
5520 		sc->vres.rq.size = val[3] - val[2] + 1;
5521 		sc->vres.pbl.start = val[4];
5522 		sc->vres.pbl.size = val[5] - val[4] + 1;
5523 
5524 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5525 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5526 		param[2] = FW_PARAM_PFVF(CQ_START);
5527 		param[3] = FW_PARAM_PFVF(CQ_END);
5528 		param[4] = FW_PARAM_PFVF(OCQ_START);
5529 		param[5] = FW_PARAM_PFVF(OCQ_END);
5530 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5531 		if (rc != 0) {
5532 			device_printf(sc->dev,
5533 			    "failed to query RDMA parameters(2): %d.\n", rc);
5534 			return (rc);
5535 		}
5536 		sc->vres.qp.start = val[0];
5537 		sc->vres.qp.size = val[1] - val[0] + 1;
5538 		sc->vres.cq.start = val[2];
5539 		sc->vres.cq.size = val[3] - val[2] + 1;
5540 		sc->vres.ocq.start = val[4];
5541 		sc->vres.ocq.size = val[5] - val[4] + 1;
5542 
5543 		param[0] = FW_PARAM_PFVF(SRQ_START);
5544 		param[1] = FW_PARAM_PFVF(SRQ_END);
5545 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5546 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5547 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5548 		if (rc != 0) {
5549 			device_printf(sc->dev,
5550 			    "failed to query RDMA parameters(3): %d.\n", rc);
5551 			return (rc);
5552 		}
5553 		sc->vres.srq.start = val[0];
5554 		sc->vres.srq.size = val[1] - val[0] + 1;
5555 		sc->params.max_ordird_qp = val[2];
5556 		sc->params.max_ird_adapter = val[3];
5557 	}
5558 	if (sc->iscsicaps) {
5559 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5560 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5561 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5562 		if (rc != 0) {
5563 			device_printf(sc->dev,
5564 			    "failed to query iSCSI parameters: %d.\n", rc);
5565 			return (rc);
5566 		}
5567 		sc->vres.iscsi.start = val[0];
5568 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5569 	}
5570 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5571 		param[0] = FW_PARAM_PFVF(TLS_START);
5572 		param[1] = FW_PARAM_PFVF(TLS_END);
5573 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5574 		if (rc != 0) {
5575 			device_printf(sc->dev,
5576 			    "failed to query TLS parameters: %d.\n", rc);
5577 			return (rc);
5578 		}
5579 		sc->vres.key.start = val[0];
5580 		sc->vres.key.size = val[1] - val[0] + 1;
5581 	}
5582 
5583 	/*
5584 	 * We've got the params we wanted to query directly from the firmware.
5585 	 * Grab some others via other means.
5586 	 */
5587 	t4_init_sge_params(sc);
5588 	t4_init_tp_params(sc);
5589 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5590 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5591 
5592 	rc = t4_verify_chip_settings(sc);
5593 	if (rc != 0)
5594 		return (rc);
5595 	t4_init_rx_buf_info(sc);
5596 
5597 	return (rc);
5598 }
5599 
5600 #ifdef KERN_TLS
5601 static void
5602 ktls_tick(void *arg)
5603 {
5604 	struct adapter *sc;
5605 	uint32_t tstamp;
5606 
5607 	sc = arg;
5608 	tstamp = tcp_ts_getticks();
5609 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5610 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5611 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5612 }
5613 
5614 static int
5615 t6_config_kern_tls(struct adapter *sc, bool enable)
5616 {
5617 	int rc;
5618 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5619 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5620 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5621 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5622 
5623 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5624 	if (rc != 0) {
5625 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5626 		    enable ?  "enable" : "disable", rc);
5627 		return (rc);
5628 	}
5629 
5630 	if (enable) {
5631 		sc->flags |= KERN_TLS_ON;
5632 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5633 		    C_HARDCLOCK);
5634 	} else {
5635 		sc->flags &= ~KERN_TLS_ON;
5636 		callout_stop(&sc->ktls_tick);
5637 	}
5638 
5639 	return (rc);
5640 }
5641 #endif
5642 
5643 static int
5644 set_params__post_init(struct adapter *sc)
5645 {
5646 	uint32_t mask, param, val;
5647 #ifdef TCP_OFFLOAD
5648 	int i, v, shift;
5649 #endif
5650 
5651 	/* ask for encapsulated CPLs */
5652 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5653 	val = 1;
5654 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5655 
5656 	/* Enable 32b port caps if the firmware supports it. */
5657 	param = FW_PARAM_PFVF(PORT_CAPS32);
5658 	val = 1;
5659 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5660 		sc->params.port_caps32 = 1;
5661 
5662 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5663 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5664 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5665 	    V_MASKFILTER(val - 1));
5666 
5667 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5668 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5669 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5670 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5671 	val = 0;
5672 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5673 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5674 		    F_ATTACKFILTERENABLE);
5675 		val |= F_DROPERRORATTACK;
5676 	}
5677 	if (t4_drop_ip_fragments != 0) {
5678 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5679 		    F_FRAGMENTDROP);
5680 		val |= F_DROPERRORFRAG;
5681 	}
5682 	if (t4_drop_pkts_with_l2_errors != 0)
5683 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5684 	if (t4_drop_pkts_with_l3_errors != 0) {
5685 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5686 		    F_DROPERRORCSUMIP;
5687 	}
5688 	if (t4_drop_pkts_with_l4_errors != 0) {
5689 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5690 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5691 	}
5692 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5693 
5694 #ifdef TCP_OFFLOAD
5695 	/*
5696 	 * Override the TOE timers with user provided tunables.  This is not the
5697 	 * recommended way to change the timers (the firmware config file is) so
5698 	 * these tunables are not documented.
5699 	 *
5700 	 * All the timer tunables are in microseconds.
5701 	 */
5702 	if (t4_toe_keepalive_idle != 0) {
5703 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5704 		v &= M_KEEPALIVEIDLE;
5705 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5706 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5707 	}
5708 	if (t4_toe_keepalive_interval != 0) {
5709 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5710 		v &= M_KEEPALIVEINTVL;
5711 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5712 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5713 	}
5714 	if (t4_toe_keepalive_count != 0) {
5715 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5716 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5717 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5718 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5719 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5720 	}
5721 	if (t4_toe_rexmt_min != 0) {
5722 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5723 		v &= M_RXTMIN;
5724 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5725 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5726 	}
5727 	if (t4_toe_rexmt_max != 0) {
5728 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5729 		v &= M_RXTMAX;
5730 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5731 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5732 	}
5733 	if (t4_toe_rexmt_count != 0) {
5734 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5735 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5736 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5737 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5738 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5739 	}
5740 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5741 		if (t4_toe_rexmt_backoff[i] != -1) {
5742 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5743 			shift = (i & 3) << 3;
5744 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5745 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5746 		}
5747 	}
5748 #endif
5749 
5750 	/*
5751 	 * Limit TOE connections to 2 reassembly "islands".  This is
5752 	 * required to permit migrating TOE connections to either
5753 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5754 	 */
5755 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5756 	    V_PASSMODE(2));
5757 
5758 #ifdef KERN_TLS
5759 	if (is_ktls(sc)) {
5760 		sc->tlst.inline_keys = t4_tls_inline_keys;
5761 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5762 		if (t4_kern_tls != 0 && is_t6(sc))
5763 			t6_config_kern_tls(sc, true);
5764 	}
5765 #endif
5766 	return (0);
5767 }
5768 
5769 #undef FW_PARAM_PFVF
5770 #undef FW_PARAM_DEV
5771 
5772 static void
5773 t4_set_desc(struct adapter *sc)
5774 {
5775 	struct adapter_params *p = &sc->params;
5776 
5777 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5778 }
5779 
5780 static inline void
5781 ifmedia_add4(struct ifmedia *ifm, int m)
5782 {
5783 
5784 	ifmedia_add(ifm, m, 0, NULL);
5785 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5786 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5787 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5788 }
5789 
5790 /*
5791  * This is the selected media, which is not quite the same as the active media.
5792  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5793  * and active are not the same, and "media: Ethernet selected" otherwise.
5794  */
5795 static void
5796 set_current_media(struct port_info *pi)
5797 {
5798 	struct link_config *lc;
5799 	struct ifmedia *ifm;
5800 	int mword;
5801 	u_int speed;
5802 
5803 	PORT_LOCK_ASSERT_OWNED(pi);
5804 
5805 	/* Leave current media alone if it's already set to IFM_NONE. */
5806 	ifm = &pi->media;
5807 	if (ifm->ifm_cur != NULL &&
5808 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5809 		return;
5810 
5811 	lc = &pi->link_cfg;
5812 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5813 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5814 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5815 		return;
5816 	}
5817 	mword = IFM_ETHER | IFM_FDX;
5818 	if (lc->requested_fc & PAUSE_TX)
5819 		mword |= IFM_ETH_TXPAUSE;
5820 	if (lc->requested_fc & PAUSE_RX)
5821 		mword |= IFM_ETH_RXPAUSE;
5822 	if (lc->requested_speed == 0)
5823 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5824 	else
5825 		speed = lc->requested_speed;
5826 	mword |= port_mword(pi, speed_to_fwcap(speed));
5827 	ifmedia_set(ifm, mword);
5828 }
5829 
5830 /*
5831  * Returns true if the ifmedia list for the port cannot change.
5832  */
5833 static bool
5834 fixed_ifmedia(struct port_info *pi)
5835 {
5836 
5837 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5838 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5839 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5840 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5841 	    pi->port_type == FW_PORT_TYPE_KX ||
5842 	    pi->port_type == FW_PORT_TYPE_KR ||
5843 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5844 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5845 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5846 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5847 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5848 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5849 }
5850 
5851 static void
5852 build_medialist(struct port_info *pi)
5853 {
5854 	uint32_t ss, speed;
5855 	int unknown, mword, bit;
5856 	struct link_config *lc;
5857 	struct ifmedia *ifm;
5858 
5859 	PORT_LOCK_ASSERT_OWNED(pi);
5860 
5861 	if (pi->flags & FIXED_IFMEDIA)
5862 		return;
5863 
5864 	/*
5865 	 * Rebuild the ifmedia list.
5866 	 */
5867 	ifm = &pi->media;
5868 	ifmedia_removeall(ifm);
5869 	lc = &pi->link_cfg;
5870 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5871 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5872 		MPASS(ss != 0);
5873 no_media:
5874 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5875 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5876 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5877 		return;
5878 	}
5879 
5880 	unknown = 0;
5881 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5882 		speed = 1 << bit;
5883 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5884 		if (ss & speed) {
5885 			mword = port_mword(pi, speed);
5886 			if (mword == IFM_NONE) {
5887 				goto no_media;
5888 			} else if (mword == IFM_UNKNOWN)
5889 				unknown++;
5890 			else
5891 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5892 		}
5893 	}
5894 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5895 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5896 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5897 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5898 
5899 	set_current_media(pi);
5900 }
5901 
5902 /*
5903  * Initialize the requested fields in the link config based on driver tunables.
5904  */
5905 static void
5906 init_link_config(struct port_info *pi)
5907 {
5908 	struct link_config *lc = &pi->link_cfg;
5909 
5910 	PORT_LOCK_ASSERT_OWNED(pi);
5911 
5912 	lc->requested_caps = 0;
5913 	lc->requested_speed = 0;
5914 
5915 	if (t4_autoneg == 0)
5916 		lc->requested_aneg = AUTONEG_DISABLE;
5917 	else if (t4_autoneg == 1)
5918 		lc->requested_aneg = AUTONEG_ENABLE;
5919 	else
5920 		lc->requested_aneg = AUTONEG_AUTO;
5921 
5922 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5923 	    PAUSE_AUTONEG);
5924 
5925 	if (t4_fec & FEC_AUTO)
5926 		lc->requested_fec = FEC_AUTO;
5927 	else if (t4_fec == 0)
5928 		lc->requested_fec = FEC_NONE;
5929 	else {
5930 		/* -1 is handled by the FEC_AUTO block above and not here. */
5931 		lc->requested_fec = t4_fec &
5932 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5933 		if (lc->requested_fec == 0)
5934 			lc->requested_fec = FEC_AUTO;
5935 	}
5936 	if (t4_force_fec < 0)
5937 		lc->force_fec = -1;
5938 	else if (t4_force_fec > 0)
5939 		lc->force_fec = 1;
5940 	else
5941 		lc->force_fec = 0;
5942 }
5943 
5944 /*
5945  * Makes sure that all requested settings comply with what's supported by the
5946  * port.  Returns the number of settings that were invalid and had to be fixed.
5947  */
5948 static int
5949 fixup_link_config(struct port_info *pi)
5950 {
5951 	int n = 0;
5952 	struct link_config *lc = &pi->link_cfg;
5953 	uint32_t fwspeed;
5954 
5955 	PORT_LOCK_ASSERT_OWNED(pi);
5956 
5957 	/* Speed (when not autonegotiating) */
5958 	if (lc->requested_speed != 0) {
5959 		fwspeed = speed_to_fwcap(lc->requested_speed);
5960 		if ((fwspeed & lc->pcaps) == 0) {
5961 			n++;
5962 			lc->requested_speed = 0;
5963 		}
5964 	}
5965 
5966 	/* Link autonegotiation */
5967 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5968 	    lc->requested_aneg == AUTONEG_DISABLE ||
5969 	    lc->requested_aneg == AUTONEG_AUTO);
5970 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5971 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5972 		n++;
5973 		lc->requested_aneg = AUTONEG_AUTO;
5974 	}
5975 
5976 	/* Flow control */
5977 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5978 	if (lc->requested_fc & PAUSE_TX &&
5979 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5980 		n++;
5981 		lc->requested_fc &= ~PAUSE_TX;
5982 	}
5983 	if (lc->requested_fc & PAUSE_RX &&
5984 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5985 		n++;
5986 		lc->requested_fc &= ~PAUSE_RX;
5987 	}
5988 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5989 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5990 		n++;
5991 		lc->requested_fc |= PAUSE_AUTONEG;
5992 	}
5993 
5994 	/* FEC */
5995 	if ((lc->requested_fec & FEC_RS &&
5996 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5997 	    (lc->requested_fec & FEC_BASER_RS &&
5998 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5999 		n++;
6000 		lc->requested_fec = FEC_AUTO;
6001 	}
6002 
6003 	return (n);
6004 }
6005 
6006 /*
6007  * Apply the requested L1 settings, which are expected to be valid, to the
6008  * hardware.
6009  */
6010 static int
6011 apply_link_config(struct port_info *pi)
6012 {
6013 	struct adapter *sc = pi->adapter;
6014 	struct link_config *lc = &pi->link_cfg;
6015 	int rc;
6016 
6017 #ifdef INVARIANTS
6018 	ASSERT_SYNCHRONIZED_OP(sc);
6019 	PORT_LOCK_ASSERT_OWNED(pi);
6020 
6021 	if (lc->requested_aneg == AUTONEG_ENABLE)
6022 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6023 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6024 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6025 	if (lc->requested_fc & PAUSE_TX)
6026 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6027 	if (lc->requested_fc & PAUSE_RX)
6028 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6029 	if (lc->requested_fec & FEC_RS)
6030 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6031 	if (lc->requested_fec & FEC_BASER_RS)
6032 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6033 #endif
6034 	if (!(sc->flags & IS_VF)) {
6035 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6036 		if (rc != 0) {
6037 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6038 			return (rc);
6039 		}
6040 	}
6041 
6042 	/*
6043 	 * An L1_CFG will almost always result in a link-change event if the
6044 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6045 	 * the notification is processed.  If the link is down then the actual
6046 	 * settings are meaningless.
6047 	 *
6048 	 * This takes care of the case where a change in the L1 settings may not
6049 	 * result in a notification.
6050 	 */
6051 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6052 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6053 
6054 	return (0);
6055 }
6056 
6057 #define FW_MAC_EXACT_CHUNK	7
6058 struct mcaddr_ctx {
6059 	if_t ifp;
6060 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6061 	uint64_t hash;
6062 	int i;
6063 	int del;
6064 	int rc;
6065 };
6066 
6067 static u_int
6068 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6069 {
6070 	struct mcaddr_ctx *ctx = arg;
6071 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6072 	struct port_info *pi = vi->pi;
6073 	struct adapter *sc = pi->adapter;
6074 
6075 	if (ctx->rc < 0)
6076 		return (0);
6077 
6078 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6079 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6080 	ctx->i++;
6081 
6082 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6083 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6084 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6085 		if (ctx->rc < 0) {
6086 			int j;
6087 
6088 			for (j = 0; j < ctx->i; j++) {
6089 				if_printf(ctx->ifp,
6090 				    "failed to add mc address"
6091 				    " %02x:%02x:%02x:"
6092 				    "%02x:%02x:%02x rc=%d\n",
6093 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6094 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6095 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6096 				    -ctx->rc);
6097 			}
6098 			return (0);
6099 		}
6100 		ctx->del = 0;
6101 		ctx->i = 0;
6102 	}
6103 
6104 	return (1);
6105 }
6106 
6107 /*
6108  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6109  * indicates which parameters should be programmed (the rest are left alone).
6110  */
6111 int
6112 update_mac_settings(if_t ifp, int flags)
6113 {
6114 	int rc = 0;
6115 	struct vi_info *vi = if_getsoftc(ifp);
6116 	struct port_info *pi = vi->pi;
6117 	struct adapter *sc = pi->adapter;
6118 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6119 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6120 
6121 	ASSERT_SYNCHRONIZED_OP(sc);
6122 	KASSERT(flags, ("%s: not told what to update.", __func__));
6123 
6124 	if (flags & XGMAC_MTU)
6125 		mtu = if_getmtu(ifp);
6126 
6127 	if (flags & XGMAC_PROMISC)
6128 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6129 
6130 	if (flags & XGMAC_ALLMULTI)
6131 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6132 
6133 	if (flags & XGMAC_VLANEX)
6134 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6135 
6136 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6137 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6138 		    allmulti, 1, vlanex, false);
6139 		if (rc) {
6140 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6141 			    rc);
6142 			return (rc);
6143 		}
6144 	}
6145 
6146 	if (flags & XGMAC_UCADDR) {
6147 		uint8_t ucaddr[ETHER_ADDR_LEN];
6148 
6149 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6150 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6151 		    ucaddr, true, &vi->smt_idx);
6152 		if (rc < 0) {
6153 			rc = -rc;
6154 			if_printf(ifp, "change_mac failed: %d\n", rc);
6155 			return (rc);
6156 		} else {
6157 			vi->xact_addr_filt = rc;
6158 			rc = 0;
6159 		}
6160 	}
6161 
6162 	if (flags & XGMAC_MCADDRS) {
6163 		struct epoch_tracker et;
6164 		struct mcaddr_ctx ctx;
6165 		int j;
6166 
6167 		ctx.ifp = ifp;
6168 		ctx.hash = 0;
6169 		ctx.i = 0;
6170 		ctx.del = 1;
6171 		ctx.rc = 0;
6172 		/*
6173 		 * Unlike other drivers, we accumulate list of pointers into
6174 		 * interface address lists and we need to keep it safe even
6175 		 * after if_foreach_llmaddr() returns, thus we must enter the
6176 		 * network epoch.
6177 		 */
6178 		NET_EPOCH_ENTER(et);
6179 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6180 		if (ctx.rc < 0) {
6181 			NET_EPOCH_EXIT(et);
6182 			rc = -ctx.rc;
6183 			return (rc);
6184 		}
6185 		if (ctx.i > 0) {
6186 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6187 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6188 			NET_EPOCH_EXIT(et);
6189 			if (rc < 0) {
6190 				rc = -rc;
6191 				for (j = 0; j < ctx.i; j++) {
6192 					if_printf(ifp,
6193 					    "failed to add mcast address"
6194 					    " %02x:%02x:%02x:"
6195 					    "%02x:%02x:%02x rc=%d\n",
6196 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6197 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6198 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6199 					    rc);
6200 				}
6201 				return (rc);
6202 			}
6203 			ctx.del = 0;
6204 		} else
6205 			NET_EPOCH_EXIT(et);
6206 
6207 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6208 		if (rc != 0)
6209 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6210 			    rc);
6211 		if (ctx.del == 0) {
6212 			/* We clobbered the VXLAN entry if there was one. */
6213 			pi->vxlan_tcam_entry = false;
6214 		}
6215 	}
6216 
6217 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6218 	    pi->vxlan_tcam_entry == false) {
6219 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6220 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6221 		    true);
6222 		if (rc < 0) {
6223 			rc = -rc;
6224 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6225 			    rc);
6226 		} else {
6227 			MPASS(rc == sc->rawf_base + pi->port_id);
6228 			rc = 0;
6229 			pi->vxlan_tcam_entry = true;
6230 		}
6231 	}
6232 
6233 	return (rc);
6234 }
6235 
6236 /*
6237  * {begin|end}_synchronized_op must be called from the same thread.
6238  */
6239 int
6240 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6241     char *wmesg)
6242 {
6243 	int rc, pri;
6244 
6245 #ifdef WITNESS
6246 	/* the caller thinks it's ok to sleep, but is it really? */
6247 	if (flags & SLEEP_OK)
6248 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6249 		    "begin_synchronized_op");
6250 #endif
6251 
6252 	if (INTR_OK)
6253 		pri = PCATCH;
6254 	else
6255 		pri = 0;
6256 
6257 	ADAPTER_LOCK(sc);
6258 	for (;;) {
6259 
6260 		if (vi && IS_DETACHING(vi)) {
6261 			rc = ENXIO;
6262 			goto done;
6263 		}
6264 
6265 		if (!IS_BUSY(sc)) {
6266 			rc = 0;
6267 			break;
6268 		}
6269 
6270 		if (!(flags & SLEEP_OK)) {
6271 			rc = EBUSY;
6272 			goto done;
6273 		}
6274 
6275 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6276 			rc = EINTR;
6277 			goto done;
6278 		}
6279 	}
6280 
6281 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6282 	SET_BUSY(sc);
6283 #ifdef INVARIANTS
6284 	sc->last_op = wmesg;
6285 	sc->last_op_thr = curthread;
6286 	sc->last_op_flags = flags;
6287 #endif
6288 
6289 done:
6290 	if (!(flags & HOLD_LOCK) || rc)
6291 		ADAPTER_UNLOCK(sc);
6292 
6293 	return (rc);
6294 }
6295 
6296 /*
6297  * Tell if_ioctl and if_init that the VI is going away.  This is
6298  * special variant of begin_synchronized_op and must be paired with a
6299  * call to end_vi_detach.
6300  */
6301 void
6302 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6303 {
6304 	ADAPTER_LOCK(sc);
6305 	SET_DETACHING(vi);
6306 	wakeup(&sc->flags);
6307 	while (IS_BUSY(sc))
6308 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6309 	SET_BUSY(sc);
6310 #ifdef INVARIANTS
6311 	sc->last_op = "t4detach";
6312 	sc->last_op_thr = curthread;
6313 	sc->last_op_flags = 0;
6314 #endif
6315 	ADAPTER_UNLOCK(sc);
6316 }
6317 
6318 void
6319 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6320 {
6321 	ADAPTER_LOCK(sc);
6322 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6323 	CLR_BUSY(sc);
6324 	CLR_DETACHING(vi);
6325 	wakeup(&sc->flags);
6326 	ADAPTER_UNLOCK(sc);
6327 }
6328 
6329 /*
6330  * {begin|end}_synchronized_op must be called from the same thread.
6331  */
6332 void
6333 end_synchronized_op(struct adapter *sc, int flags)
6334 {
6335 
6336 	if (flags & LOCK_HELD)
6337 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6338 	else
6339 		ADAPTER_LOCK(sc);
6340 
6341 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6342 	CLR_BUSY(sc);
6343 	wakeup(&sc->flags);
6344 	ADAPTER_UNLOCK(sc);
6345 }
6346 
6347 static int
6348 cxgbe_init_synchronized(struct vi_info *vi)
6349 {
6350 	struct port_info *pi = vi->pi;
6351 	struct adapter *sc = pi->adapter;
6352 	if_t ifp = vi->ifp;
6353 	int rc = 0, i;
6354 	struct sge_txq *txq;
6355 
6356 	ASSERT_SYNCHRONIZED_OP(sc);
6357 
6358 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6359 		return (0);	/* already running */
6360 
6361 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6362 		return (rc);	/* error message displayed already */
6363 
6364 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6365 		return (rc); /* error message displayed already */
6366 
6367 	rc = update_mac_settings(ifp, XGMAC_ALL);
6368 	if (rc)
6369 		goto done;	/* error message displayed already */
6370 
6371 	PORT_LOCK(pi);
6372 	if (pi->up_vis == 0) {
6373 		t4_update_port_info(pi);
6374 		fixup_link_config(pi);
6375 		build_medialist(pi);
6376 		apply_link_config(pi);
6377 	}
6378 
6379 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6380 	if (rc != 0) {
6381 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6382 		PORT_UNLOCK(pi);
6383 		goto done;
6384 	}
6385 
6386 	/*
6387 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6388 	 * if this changes.
6389 	 */
6390 
6391 	for_each_txq(vi, i, txq) {
6392 		TXQ_LOCK(txq);
6393 		txq->eq.flags |= EQ_ENABLED;
6394 		TXQ_UNLOCK(txq);
6395 	}
6396 
6397 	/*
6398 	 * The first iq of the first port to come up is used for tracing.
6399 	 */
6400 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6401 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6402 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6403 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6404 		    V_QUEUENUMBER(sc->traceq));
6405 		pi->flags |= HAS_TRACEQ;
6406 	}
6407 
6408 	/* all ok */
6409 	pi->up_vis++;
6410 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6411 	if (pi->link_cfg.link_ok)
6412 		t4_os_link_changed(pi);
6413 	PORT_UNLOCK(pi);
6414 
6415 	mtx_lock(&vi->tick_mtx);
6416 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6417 		callout_reset(&vi->tick, hz, vi_tick, vi);
6418 	else
6419 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6420 	mtx_unlock(&vi->tick_mtx);
6421 done:
6422 	if (rc != 0)
6423 		cxgbe_uninit_synchronized(vi);
6424 
6425 	return (rc);
6426 }
6427 
6428 /*
6429  * Idempotent.
6430  */
6431 static int
6432 cxgbe_uninit_synchronized(struct vi_info *vi)
6433 {
6434 	struct port_info *pi = vi->pi;
6435 	struct adapter *sc = pi->adapter;
6436 	if_t ifp = vi->ifp;
6437 	int rc, i;
6438 	struct sge_txq *txq;
6439 
6440 	ASSERT_SYNCHRONIZED_OP(sc);
6441 
6442 	if (!(vi->flags & VI_INIT_DONE)) {
6443 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6444 			KASSERT(0, ("uninited VI is running"));
6445 			if_printf(ifp, "uninited VI with running ifnet.  "
6446 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6447 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6448 			    if_getdrvflags(ifp));
6449 		}
6450 		return (0);
6451 	}
6452 
6453 	/*
6454 	 * Disable the VI so that all its data in either direction is discarded
6455 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6456 	 * tick) intact as the TP can deliver negative advice or data that it's
6457 	 * holding in its RAM (for an offloaded connection) even after the VI is
6458 	 * disabled.
6459 	 */
6460 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6461 	if (rc) {
6462 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6463 		return (rc);
6464 	}
6465 
6466 	for_each_txq(vi, i, txq) {
6467 		TXQ_LOCK(txq);
6468 		txq->eq.flags &= ~EQ_ENABLED;
6469 		TXQ_UNLOCK(txq);
6470 	}
6471 
6472 	mtx_lock(&vi->tick_mtx);
6473 	callout_stop(&vi->tick);
6474 	mtx_unlock(&vi->tick_mtx);
6475 
6476 	PORT_LOCK(pi);
6477 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6478 		PORT_UNLOCK(pi);
6479 		return (0);
6480 	}
6481 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6482 	pi->up_vis--;
6483 	if (pi->up_vis > 0) {
6484 		PORT_UNLOCK(pi);
6485 		return (0);
6486 	}
6487 
6488 	pi->link_cfg.link_ok = false;
6489 	pi->link_cfg.speed = 0;
6490 	pi->link_cfg.link_down_rc = 255;
6491 	t4_os_link_changed(pi);
6492 	PORT_UNLOCK(pi);
6493 
6494 	return (0);
6495 }
6496 
6497 /*
6498  * It is ok for this function to fail midway and return right away.  t4_detach
6499  * will walk the entire sc->irq list and clean up whatever is valid.
6500  */
6501 int
6502 t4_setup_intr_handlers(struct adapter *sc)
6503 {
6504 	int rc, rid, p, q, v;
6505 	char s[8];
6506 	struct irq *irq;
6507 	struct port_info *pi;
6508 	struct vi_info *vi;
6509 	struct sge *sge = &sc->sge;
6510 	struct sge_rxq *rxq;
6511 #ifdef TCP_OFFLOAD
6512 	struct sge_ofld_rxq *ofld_rxq;
6513 #endif
6514 #ifdef DEV_NETMAP
6515 	struct sge_nm_rxq *nm_rxq;
6516 #endif
6517 #ifdef RSS
6518 	int nbuckets = rss_getnumbuckets();
6519 #endif
6520 
6521 	/*
6522 	 * Setup interrupts.
6523 	 */
6524 	irq = &sc->irq[0];
6525 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6526 	if (forwarding_intr_to_fwq(sc))
6527 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6528 
6529 	/* Multiple interrupts. */
6530 	if (sc->flags & IS_VF)
6531 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6532 		    ("%s: too few intr.", __func__));
6533 	else
6534 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6535 		    ("%s: too few intr.", __func__));
6536 
6537 	/* The first one is always error intr on PFs */
6538 	if (!(sc->flags & IS_VF)) {
6539 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6540 		if (rc != 0)
6541 			return (rc);
6542 		irq++;
6543 		rid++;
6544 	}
6545 
6546 	/* The second one is always the firmware event queue (first on VFs) */
6547 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6548 	if (rc != 0)
6549 		return (rc);
6550 	irq++;
6551 	rid++;
6552 
6553 	for_each_port(sc, p) {
6554 		pi = sc->port[p];
6555 		for_each_vi(pi, v, vi) {
6556 			vi->first_intr = rid - 1;
6557 
6558 			if (vi->nnmrxq > 0) {
6559 				int n = max(vi->nrxq, vi->nnmrxq);
6560 
6561 				rxq = &sge->rxq[vi->first_rxq];
6562 #ifdef DEV_NETMAP
6563 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6564 #endif
6565 				for (q = 0; q < n; q++) {
6566 					snprintf(s, sizeof(s), "%x%c%x", p,
6567 					    'a' + v, q);
6568 					if (q < vi->nrxq)
6569 						irq->rxq = rxq++;
6570 #ifdef DEV_NETMAP
6571 					if (q < vi->nnmrxq)
6572 						irq->nm_rxq = nm_rxq++;
6573 
6574 					if (irq->nm_rxq != NULL &&
6575 					    irq->rxq == NULL) {
6576 						/* Netmap rx only */
6577 						rc = t4_alloc_irq(sc, irq, rid,
6578 						    t4_nm_intr, irq->nm_rxq, s);
6579 					}
6580 					if (irq->nm_rxq != NULL &&
6581 					    irq->rxq != NULL) {
6582 						/* NIC and Netmap rx */
6583 						rc = t4_alloc_irq(sc, irq, rid,
6584 						    t4_vi_intr, irq, s);
6585 					}
6586 #endif
6587 					if (irq->rxq != NULL &&
6588 					    irq->nm_rxq == NULL) {
6589 						/* NIC rx only */
6590 						rc = t4_alloc_irq(sc, irq, rid,
6591 						    t4_intr, irq->rxq, s);
6592 					}
6593 					if (rc != 0)
6594 						return (rc);
6595 #ifdef RSS
6596 					if (q < vi->nrxq) {
6597 						bus_bind_intr(sc->dev, irq->res,
6598 						    rss_getcpu(q % nbuckets));
6599 					}
6600 #endif
6601 					irq++;
6602 					rid++;
6603 					vi->nintr++;
6604 				}
6605 			} else {
6606 				for_each_rxq(vi, q, rxq) {
6607 					snprintf(s, sizeof(s), "%x%c%x", p,
6608 					    'a' + v, q);
6609 					rc = t4_alloc_irq(sc, irq, rid,
6610 					    t4_intr, rxq, s);
6611 					if (rc != 0)
6612 						return (rc);
6613 #ifdef RSS
6614 					bus_bind_intr(sc->dev, irq->res,
6615 					    rss_getcpu(q % nbuckets));
6616 #endif
6617 					irq++;
6618 					rid++;
6619 					vi->nintr++;
6620 				}
6621 			}
6622 #ifdef TCP_OFFLOAD
6623 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6624 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6625 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6626 				    ofld_rxq, s);
6627 				if (rc != 0)
6628 					return (rc);
6629 				irq++;
6630 				rid++;
6631 				vi->nintr++;
6632 			}
6633 #endif
6634 		}
6635 	}
6636 	MPASS(irq == &sc->irq[sc->intr_count]);
6637 
6638 	return (0);
6639 }
6640 
6641 static void
6642 write_global_rss_key(struct adapter *sc)
6643 {
6644 #ifdef RSS
6645 	int i;
6646 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6647 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6648 
6649 	CTASSERT(RSS_KEYSIZE == 40);
6650 
6651 	rss_getkey((void *)&raw_rss_key[0]);
6652 	for (i = 0; i < nitems(rss_key); i++) {
6653 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6654 	}
6655 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6656 #endif
6657 }
6658 
6659 /*
6660  * Idempotent.
6661  */
6662 static int
6663 adapter_full_init(struct adapter *sc)
6664 {
6665 	int rc, i;
6666 
6667 	ASSERT_SYNCHRONIZED_OP(sc);
6668 
6669 	/*
6670 	 * queues that belong to the adapter (not any particular port).
6671 	 */
6672 	rc = t4_setup_adapter_queues(sc);
6673 	if (rc != 0)
6674 		return (rc);
6675 
6676 	MPASS(sc->params.nports <= nitems(sc->tq));
6677 	for (i = 0; i < sc->params.nports; i++) {
6678 		if (sc->tq[i] != NULL)
6679 			continue;
6680 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6681 		    taskqueue_thread_enqueue, &sc->tq[i]);
6682 		if (sc->tq[i] == NULL) {
6683 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6684 			return (ENOMEM);
6685 		}
6686 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6687 		    device_get_nameunit(sc->dev), i);
6688 	}
6689 
6690 	if (!(sc->flags & IS_VF)) {
6691 		write_global_rss_key(sc);
6692 		t4_intr_enable(sc);
6693 	}
6694 	return (0);
6695 }
6696 
6697 int
6698 adapter_init(struct adapter *sc)
6699 {
6700 	int rc;
6701 
6702 	ASSERT_SYNCHRONIZED_OP(sc);
6703 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6704 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6705 	    ("%s: FULL_INIT_DONE already", __func__));
6706 
6707 	rc = adapter_full_init(sc);
6708 	if (rc != 0)
6709 		adapter_full_uninit(sc);
6710 	else
6711 		sc->flags |= FULL_INIT_DONE;
6712 
6713 	return (rc);
6714 }
6715 
6716 /*
6717  * Idempotent.
6718  */
6719 static void
6720 adapter_full_uninit(struct adapter *sc)
6721 {
6722 	int i;
6723 
6724 	t4_teardown_adapter_queues(sc);
6725 
6726 	for (i = 0; i < nitems(sc->tq); i++) {
6727 		if (sc->tq[i] == NULL)
6728 			continue;
6729 		taskqueue_free(sc->tq[i]);
6730 		sc->tq[i] = NULL;
6731 	}
6732 
6733 	sc->flags &= ~FULL_INIT_DONE;
6734 }
6735 
6736 #ifdef RSS
6737 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6738     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6739     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6740     RSS_HASHTYPE_RSS_UDP_IPV6)
6741 
6742 /* Translates kernel hash types to hardware. */
6743 static int
6744 hashconfig_to_hashen(int hashconfig)
6745 {
6746 	int hashen = 0;
6747 
6748 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6749 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6750 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6751 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6752 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6753 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6754 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6755 	}
6756 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6757 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6758 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6759 	}
6760 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6761 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6762 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6763 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6764 
6765 	return (hashen);
6766 }
6767 
6768 /* Translates hardware hash types to kernel. */
6769 static int
6770 hashen_to_hashconfig(int hashen)
6771 {
6772 	int hashconfig = 0;
6773 
6774 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6775 		/*
6776 		 * If UDP hashing was enabled it must have been enabled for
6777 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6778 		 * enabling any 4-tuple hash is nonsense configuration.
6779 		 */
6780 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6781 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6782 
6783 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6784 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6785 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6786 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6787 	}
6788 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6789 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6790 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6791 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6792 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6793 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6794 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6795 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6796 
6797 	return (hashconfig);
6798 }
6799 #endif
6800 
6801 /*
6802  * Idempotent.
6803  */
6804 static int
6805 vi_full_init(struct vi_info *vi)
6806 {
6807 	struct adapter *sc = vi->adapter;
6808 	struct sge_rxq *rxq;
6809 	int rc, i, j;
6810 #ifdef RSS
6811 	int nbuckets = rss_getnumbuckets();
6812 	int hashconfig = rss_gethashconfig();
6813 	int extra;
6814 #endif
6815 
6816 	ASSERT_SYNCHRONIZED_OP(sc);
6817 
6818 	/*
6819 	 * Allocate tx/rx/fl queues for this VI.
6820 	 */
6821 	rc = t4_setup_vi_queues(vi);
6822 	if (rc != 0)
6823 		return (rc);
6824 
6825 	/*
6826 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6827 	 */
6828 	if (vi->nrxq > vi->rss_size) {
6829 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6830 		    "some queues will never receive traffic.\n", vi->nrxq,
6831 		    vi->rss_size);
6832 	} else if (vi->rss_size % vi->nrxq) {
6833 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6834 		    "expect uneven traffic distribution.\n", vi->nrxq,
6835 		    vi->rss_size);
6836 	}
6837 #ifdef RSS
6838 	if (vi->nrxq != nbuckets) {
6839 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6840 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6841 	}
6842 #endif
6843 	if (vi->rss == NULL)
6844 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6845 		    M_ZERO | M_WAITOK);
6846 	for (i = 0; i < vi->rss_size;) {
6847 #ifdef RSS
6848 		j = rss_get_indirection_to_bucket(i);
6849 		j %= vi->nrxq;
6850 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6851 		vi->rss[i++] = rxq->iq.abs_id;
6852 #else
6853 		for_each_rxq(vi, j, rxq) {
6854 			vi->rss[i++] = rxq->iq.abs_id;
6855 			if (i == vi->rss_size)
6856 				break;
6857 		}
6858 #endif
6859 	}
6860 
6861 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6862 	    vi->rss, vi->rss_size);
6863 	if (rc != 0) {
6864 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6865 		return (rc);
6866 	}
6867 
6868 #ifdef RSS
6869 	vi->hashen = hashconfig_to_hashen(hashconfig);
6870 
6871 	/*
6872 	 * We may have had to enable some hashes even though the global config
6873 	 * wants them disabled.  This is a potential problem that must be
6874 	 * reported to the user.
6875 	 */
6876 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6877 
6878 	/*
6879 	 * If we consider only the supported hash types, then the enabled hashes
6880 	 * are a superset of the requested hashes.  In other words, there cannot
6881 	 * be any supported hash that was requested but not enabled, but there
6882 	 * can be hashes that were not requested but had to be enabled.
6883 	 */
6884 	extra &= SUPPORTED_RSS_HASHTYPES;
6885 	MPASS((extra & hashconfig) == 0);
6886 
6887 	if (extra) {
6888 		CH_ALERT(vi,
6889 		    "global RSS config (0x%x) cannot be accommodated.\n",
6890 		    hashconfig);
6891 	}
6892 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6893 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6894 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6895 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6896 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6897 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6898 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6899 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6900 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6901 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6902 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6903 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6904 #else
6905 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6906 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6907 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6908 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6909 #endif
6910 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6911 	    0, 0);
6912 	if (rc != 0) {
6913 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6914 		return (rc);
6915 	}
6916 
6917 	return (0);
6918 }
6919 
6920 int
6921 vi_init(struct vi_info *vi)
6922 {
6923 	int rc;
6924 
6925 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6926 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6927 	    ("%s: VI_INIT_DONE already", __func__));
6928 
6929 	rc = vi_full_init(vi);
6930 	if (rc != 0)
6931 		vi_full_uninit(vi);
6932 	else
6933 		vi->flags |= VI_INIT_DONE;
6934 
6935 	return (rc);
6936 }
6937 
6938 /*
6939  * Idempotent.
6940  */
6941 static void
6942 vi_full_uninit(struct vi_info *vi)
6943 {
6944 
6945 	if (vi->flags & VI_INIT_DONE) {
6946 		quiesce_vi(vi);
6947 		free(vi->rss, M_CXGBE);
6948 		free(vi->nm_rss, M_CXGBE);
6949 	}
6950 
6951 	t4_teardown_vi_queues(vi);
6952 	vi->flags &= ~VI_INIT_DONE;
6953 }
6954 
6955 static void
6956 quiesce_txq(struct sge_txq *txq)
6957 {
6958 	struct sge_eq *eq = &txq->eq;
6959 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6960 
6961 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6962 	MPASS(!(eq->flags & EQ_ENABLED));
6963 
6964 	/* Wait for the mp_ring to empty. */
6965 	while (!mp_ring_is_idle(txq->r)) {
6966 		mp_ring_check_drainage(txq->r, 4096);
6967 		pause("rquiesce", 1);
6968 	}
6969 	MPASS(txq->txp.npkt == 0);
6970 
6971 	if (eq->flags & EQ_HW_ALLOCATED) {
6972 		/*
6973 		 * Hardware is alive and working normally.  Wait for it to
6974 		 * finish and then wait for the driver to catch up and reclaim
6975 		 * all descriptors.
6976 		 */
6977 		while (spg->cidx != htobe16(eq->pidx))
6978 			pause("equiesce", 1);
6979 		while (eq->cidx != eq->pidx)
6980 			pause("dquiesce", 1);
6981 	} else {
6982 		/*
6983 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6984 		 * descriptors directly.
6985 		 */
6986 		TXQ_LOCK(txq);
6987 		while (eq->cidx != eq->pidx) {
6988 			struct mbuf *m, *nextpkt;
6989 			struct tx_sdesc *txsd;
6990 
6991 			txsd = &txq->sdesc[eq->cidx];
6992 			for (m = txsd->m; m != NULL; m = nextpkt) {
6993 				nextpkt = m->m_nextpkt;
6994 				m->m_nextpkt = NULL;
6995 				m_freem(m);
6996 			}
6997 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6998 		}
6999 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7000 		TXQ_UNLOCK(txq);
7001 	}
7002 }
7003 
7004 static void
7005 quiesce_wrq(struct sge_wrq *wrq)
7006 {
7007 
7008 	/* XXXTX */
7009 }
7010 
7011 static void
7012 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7013 {
7014 	/* Synchronize with the interrupt handler */
7015 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7016 		pause("iqfree", 1);
7017 
7018 	if (fl != NULL) {
7019 		MPASS(iq->flags & IQ_HAS_FL);
7020 
7021 		mtx_lock(&sc->sfl_lock);
7022 		FL_LOCK(fl);
7023 		fl->flags |= FL_DOOMED;
7024 		FL_UNLOCK(fl);
7025 		callout_stop(&sc->sfl_callout);
7026 		mtx_unlock(&sc->sfl_lock);
7027 
7028 		KASSERT((fl->flags & FL_STARVING) == 0,
7029 		    ("%s: still starving", __func__));
7030 
7031 		/* Release all buffers if hardware is no longer available. */
7032 		if (!(iq->flags & IQ_HW_ALLOCATED))
7033 			free_fl_buffers(sc, fl);
7034 	}
7035 }
7036 
7037 /*
7038  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7039  * that no new work is being enqueued by the hardware or the driver.  That part
7040  * should be arranged before calling this function.
7041  */
7042 static void
7043 quiesce_vi(struct vi_info *vi)
7044 {
7045 	int i;
7046 	struct adapter *sc = vi->adapter;
7047 	struct sge_rxq *rxq;
7048 	struct sge_txq *txq;
7049 #ifdef TCP_OFFLOAD
7050 	struct sge_ofld_rxq *ofld_rxq;
7051 #endif
7052 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7053 	struct sge_ofld_txq *ofld_txq;
7054 #endif
7055 
7056 	if (!(vi->flags & VI_INIT_DONE))
7057 		return;
7058 
7059 	for_each_txq(vi, i, txq) {
7060 		quiesce_txq(txq);
7061 	}
7062 
7063 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7064 	for_each_ofld_txq(vi, i, ofld_txq) {
7065 		quiesce_wrq(&ofld_txq->wrq);
7066 	}
7067 #endif
7068 
7069 	for_each_rxq(vi, i, rxq) {
7070 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7071 	}
7072 
7073 #ifdef TCP_OFFLOAD
7074 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7075 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7076 	}
7077 #endif
7078 }
7079 
7080 static int
7081 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7082     driver_intr_t *handler, void *arg, char *name)
7083 {
7084 	int rc;
7085 
7086 	irq->rid = rid;
7087 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7088 	    RF_SHAREABLE | RF_ACTIVE);
7089 	if (irq->res == NULL) {
7090 		device_printf(sc->dev,
7091 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7092 		return (ENOMEM);
7093 	}
7094 
7095 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7096 	    NULL, handler, arg, &irq->tag);
7097 	if (rc != 0) {
7098 		device_printf(sc->dev,
7099 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7100 		    rid, name, rc);
7101 	} else if (name)
7102 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7103 
7104 	return (rc);
7105 }
7106 
7107 static int
7108 t4_free_irq(struct adapter *sc, struct irq *irq)
7109 {
7110 	if (irq->tag)
7111 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7112 	if (irq->res)
7113 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7114 
7115 	bzero(irq, sizeof(*irq));
7116 
7117 	return (0);
7118 }
7119 
7120 static void
7121 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7122 {
7123 
7124 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7125 	t4_get_regs(sc, buf, regs->len);
7126 }
7127 
7128 #define	A_PL_INDIR_CMD	0x1f8
7129 
7130 #define	S_PL_AUTOINC	31
7131 #define	M_PL_AUTOINC	0x1U
7132 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7133 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7134 
7135 #define	S_PL_VFID	20
7136 #define	M_PL_VFID	0xffU
7137 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7138 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7139 
7140 #define	S_PL_ADDR	0
7141 #define	M_PL_ADDR	0xfffffU
7142 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7143 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7144 
7145 #define	A_PL_INDIR_DATA	0x1fc
7146 
7147 static uint64_t
7148 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7149 {
7150 	u32 stats[2];
7151 
7152 	if (sc->flags & IS_VF) {
7153 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7154 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7155 	} else {
7156 		mtx_assert(&sc->reg_lock, MA_OWNED);
7157 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7158 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7159 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7160 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7161 	}
7162 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7163 }
7164 
7165 static void
7166 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7167 {
7168 
7169 #define GET_STAT(name) \
7170 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7171 
7172 	if (!(sc->flags & IS_VF))
7173 		mtx_lock(&sc->reg_lock);
7174 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7175 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7176 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7177 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7178 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7179 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7180 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7181 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7182 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7183 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7184 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7185 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7186 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7187 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7188 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7189 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7190 	if (!(sc->flags & IS_VF))
7191 		mtx_unlock(&sc->reg_lock);
7192 
7193 #undef GET_STAT
7194 }
7195 
7196 static void
7197 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7198 {
7199 	int reg;
7200 
7201 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7202 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7203 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7204 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7205 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7206 }
7207 
7208 static void
7209 vi_refresh_stats(struct vi_info *vi)
7210 {
7211 	struct timeval tv;
7212 	const struct timeval interval = {0, 250000};	/* 250ms */
7213 
7214 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7215 
7216 	if (vi->flags & VI_SKIP_STATS)
7217 		return;
7218 
7219 	getmicrotime(&tv);
7220 	timevalsub(&tv, &interval);
7221 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7222 		return;
7223 
7224 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7225 	getmicrotime(&vi->last_refreshed);
7226 }
7227 
7228 static void
7229 cxgbe_refresh_stats(struct vi_info *vi)
7230 {
7231 	u_int i, v, tnl_cong_drops, chan_map;
7232 	struct timeval tv;
7233 	const struct timeval interval = {0, 250000};	/* 250ms */
7234 	struct port_info *pi;
7235 	struct adapter *sc;
7236 
7237 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7238 
7239 	if (vi->flags & VI_SKIP_STATS)
7240 		return;
7241 
7242 	getmicrotime(&tv);
7243 	timevalsub(&tv, &interval);
7244 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7245 		return;
7246 
7247 	pi = vi->pi;
7248 	sc = vi->adapter;
7249 	tnl_cong_drops = 0;
7250 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7251 	chan_map = pi->rx_e_chan_map;
7252 	while (chan_map) {
7253 		i = ffs(chan_map) - 1;
7254 		mtx_lock(&sc->reg_lock);
7255 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7256 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7257 		mtx_unlock(&sc->reg_lock);
7258 		tnl_cong_drops += v;
7259 		chan_map &= ~(1 << i);
7260 	}
7261 	pi->tnl_cong_drops = tnl_cong_drops;
7262 	getmicrotime(&vi->last_refreshed);
7263 }
7264 
7265 static void
7266 cxgbe_tick(void *arg)
7267 {
7268 	struct vi_info *vi = arg;
7269 
7270 	MPASS(IS_MAIN_VI(vi));
7271 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7272 
7273 	cxgbe_refresh_stats(vi);
7274 	callout_schedule(&vi->tick, hz);
7275 }
7276 
7277 static void
7278 vi_tick(void *arg)
7279 {
7280 	struct vi_info *vi = arg;
7281 
7282 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7283 
7284 	vi_refresh_stats(vi);
7285 	callout_schedule(&vi->tick, hz);
7286 }
7287 
7288 /*
7289  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7290  */
7291 static char *caps_decoder[] = {
7292 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7293 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7294 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7295 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7296 	    "\006HASHFILTER\007ETHOFLD",
7297 	"\20\001TOE",					/* 4: TOE */
7298 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7299 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7300 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7301 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7302 	    "\007T10DIF"
7303 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7304 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7305 	    "\004TLS_HW",
7306 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7307 		    "\004PO_INITIATOR\005PO_TARGET",
7308 };
7309 
7310 void
7311 t4_sysctls(struct adapter *sc)
7312 {
7313 	struct sysctl_ctx_list *ctx = &sc->ctx;
7314 	struct sysctl_oid *oid;
7315 	struct sysctl_oid_list *children, *c0;
7316 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7317 
7318 	/*
7319 	 * dev.t4nex.X.
7320 	 */
7321 	oid = device_get_sysctl_tree(sc->dev);
7322 	c0 = children = SYSCTL_CHILDREN(oid);
7323 
7324 	sc->sc_do_rxcopy = 1;
7325 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7326 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7327 
7328 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7329 	    sc->params.nports, "# of ports");
7330 
7331 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7332 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7333 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7334 	    "available doorbells");
7335 
7336 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7337 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7338 
7339 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7340 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7341 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7342 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7343 
7344 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7345 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7346 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7347 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7348 
7349 	t4_sge_sysctls(sc, ctx, children);
7350 
7351 	sc->lro_timeout = 100;
7352 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7353 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7354 
7355 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7356 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7357 
7358 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7359 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7360 
7361 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7362 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7363 
7364 	if (sc->flags & IS_VF)
7365 		return;
7366 
7367 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7368 	    NULL, chip_rev(sc), "chip hardware revision");
7369 
7370 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7371 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7372 
7373 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7374 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7375 
7376 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7377 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7378 
7379 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7380 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7381 
7382 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7383 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7384 
7385 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7386 	    sc->er_version, 0, "expansion ROM version");
7387 
7388 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7389 	    sc->bs_version, 0, "bootstrap firmware version");
7390 
7391 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7392 	    NULL, sc->params.scfg_vers, "serial config version");
7393 
7394 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7395 	    NULL, sc->params.vpd_vers, "VPD version");
7396 
7397 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7398 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7399 
7400 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7401 	    sc->cfcsum, "config file checksum");
7402 
7403 #define SYSCTL_CAP(name, n, text) \
7404 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7405 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7406 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7407 	    "available " text " capabilities")
7408 
7409 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7410 	SYSCTL_CAP(linkcaps, 1, "link");
7411 	SYSCTL_CAP(switchcaps, 2, "switch");
7412 	SYSCTL_CAP(niccaps, 3, "NIC");
7413 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7414 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7415 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7416 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7417 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7418 #undef SYSCTL_CAP
7419 
7420 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7421 	    NULL, sc->tids.nftids, "number of filters");
7422 
7423 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7424 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7425 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7426 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7427 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7428 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7429 
7430 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7431 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7432 	    sysctl_loadavg, "A",
7433 	    "microprocessor load averages (debug firmwares only)");
7434 
7435 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7436 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7437 	    "I", "core Vdd (in mV)");
7438 
7439 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7440 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7441 	    sysctl_cpus, "A", "local CPUs");
7442 
7443 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7444 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7445 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7446 
7447 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7448 	    &sc->swintr, 0, "software triggered interrupts");
7449 
7450 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7451 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7452 	    "1 = reset adapter, 0 = zero reset counter");
7453 
7454 	/*
7455 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7456 	 */
7457 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7458 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7459 	    "logs and miscellaneous information");
7460 	children = SYSCTL_CHILDREN(oid);
7461 
7462 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7463 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7464 	    sysctl_cctrl, "A", "congestion control");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7467 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7469 
7470 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7471 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7472 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7473 
7474 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7475 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7476 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7479 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7480 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7484 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7488 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7489 
7490 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7491 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7492 	    sysctl_cim_la, "A", "CIM logic analyzer");
7493 
7494 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7495 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7496 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7497 
7498 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7499 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7500 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7501 
7502 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7503 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7504 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7505 
7506 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7507 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7508 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7509 
7510 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7511 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7512 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7513 
7514 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7515 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7516 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7517 
7518 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7519 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7520 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7521 
7522 	if (chip_id(sc) > CHELSIO_T4) {
7523 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7524 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7525 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7526 		    "CIM OBQ 6 (SGE0-RX)");
7527 
7528 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7529 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7530 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7531 		    "CIM OBQ 7 (SGE1-RX)");
7532 	}
7533 
7534 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7535 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7536 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7537 
7538 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7539 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7540 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7541 
7542 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7543 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7544 	    sysctl_cpl_stats, "A", "CPL statistics");
7545 
7546 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7547 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7548 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7549 
7550 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7551 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7552 	    sysctl_tid_stats, "A", "tid stats");
7553 
7554 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7555 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7556 	    sysctl_devlog, "A", "firmware's device log");
7557 
7558 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7559 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7560 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7561 
7562 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7563 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7564 	    sysctl_hw_sched, "A", "hardware scheduler ");
7565 
7566 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7567 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7568 	    sysctl_l2t, "A", "hardware L2 table");
7569 
7570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7571 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7572 	    sysctl_smt, "A", "hardware source MAC table");
7573 
7574 #ifdef INET6
7575 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7576 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7577 	    sysctl_clip, "A", "active CLIP table entries");
7578 #endif
7579 
7580 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7581 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7582 	    sysctl_lb_stats, "A", "loopback statistics");
7583 
7584 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7585 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7586 	    sysctl_meminfo, "A", "memory regions");
7587 
7588 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7589 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7590 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7591 	    "A", "MPS TCAM entries");
7592 
7593 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7594 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7595 	    sysctl_path_mtus, "A", "path MTUs");
7596 
7597 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7598 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7599 	    sysctl_pm_stats, "A", "PM statistics");
7600 
7601 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7602 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7603 	    sysctl_rdma_stats, "A", "RDMA statistics");
7604 
7605 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7606 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 	    sysctl_tcp_stats, "A", "TCP statistics");
7608 
7609 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7610 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 	    sysctl_tids, "A", "TID information");
7612 
7613 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7614 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7615 	    sysctl_tp_err_stats, "A", "TP error statistics");
7616 
7617 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7618 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7619 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7620 
7621 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7622 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7623 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7624 
7625 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7626 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7627 	    sysctl_tp_la, "A", "TP logic analyzer");
7628 
7629 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7630 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7631 	    sysctl_tx_rate, "A", "Tx rate");
7632 
7633 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7634 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7635 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7636 
7637 	if (chip_id(sc) >= CHELSIO_T5) {
7638 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7639 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7640 		    sysctl_wcwr_stats, "A", "write combined work requests");
7641 	}
7642 
7643 #ifdef KERN_TLS
7644 	if (is_ktls(sc)) {
7645 		/*
7646 		 * dev.t4nex.0.tls.
7647 		 */
7648 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7649 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7650 		children = SYSCTL_CHILDREN(oid);
7651 
7652 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7653 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7654 		    "keys in work requests (1) or attempt to store TLS keys "
7655 		    "in card memory.");
7656 
7657 		if (is_t6(sc))
7658 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7659 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7660 			    "combine TCB field updates with TLS record work "
7661 			    "requests.");
7662 	}
7663 #endif
7664 
7665 #ifdef TCP_OFFLOAD
7666 	if (is_offload(sc)) {
7667 		int i;
7668 		char s[4];
7669 
7670 		/*
7671 		 * dev.t4nex.X.toe.
7672 		 */
7673 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7674 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7675 		children = SYSCTL_CHILDREN(oid);
7676 
7677 		sc->tt.cong_algorithm = -1;
7678 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7679 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7680 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7681 		    "3 = highspeed)");
7682 
7683 		sc->tt.sndbuf = -1;
7684 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7685 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7686 
7687 		sc->tt.ddp = 0;
7688 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7689 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7690 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7691 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7692 
7693 		sc->tt.rx_coalesce = -1;
7694 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7695 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7696 
7697 		sc->tt.tls = 0;
7698 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7699 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7700 		    "Inline TLS allowed");
7701 
7702 		sc->tt.tx_align = -1;
7703 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7704 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7705 
7706 		sc->tt.tx_zcopy = 0;
7707 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7708 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7709 		    "Enable zero-copy aio_write(2)");
7710 
7711 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7712 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7713 		    "cop_managed_offloading", CTLFLAG_RW,
7714 		    &sc->tt.cop_managed_offloading, 0,
7715 		    "COP (Connection Offload Policy) controls all TOE offload");
7716 
7717 		sc->tt.autorcvbuf_inc = 16 * 1024;
7718 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7719 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7720 		    "autorcvbuf increment");
7721 
7722 		sc->tt.update_hc_on_pmtu_change = 1;
7723 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7724 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7725 		    &sc->tt.update_hc_on_pmtu_change, 0,
7726 		    "Update hostcache entry if the PMTU changes");
7727 
7728 		sc->tt.iso = 1;
7729 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7730 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7731 
7732 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7733 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7734 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7735 
7736 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7737 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7738 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7739 
7740 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7741 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7742 		    sysctl_tp_tick, "A", "DACK tick (us)");
7743 
7744 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7745 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7746 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7747 
7748 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7749 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7750 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7751 		    "Minimum retransmit interval (us)");
7752 
7753 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7754 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7755 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7756 		    "Maximum retransmit interval (us)");
7757 
7758 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7759 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7760 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7761 		    "Persist timer min (us)");
7762 
7763 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7764 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7765 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7766 		    "Persist timer max (us)");
7767 
7768 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7769 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7770 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7771 		    "Keepalive idle timer (us)");
7772 
7773 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7774 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7775 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7776 		    "Keepalive interval timer (us)");
7777 
7778 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7779 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7780 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7781 
7782 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7783 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7784 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7785 		    "FINWAIT2 timer (us)");
7786 
7787 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7788 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7789 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7790 		    "Number of SYN retransmissions before abort");
7791 
7792 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7793 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7794 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7795 		    "Number of retransmissions before abort");
7796 
7797 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7798 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7799 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7800 		    "Number of keepalive probes before abort");
7801 
7802 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7803 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7804 		    "TOE retransmit backoffs");
7805 		children = SYSCTL_CHILDREN(oid);
7806 		for (i = 0; i < 16; i++) {
7807 			snprintf(s, sizeof(s), "%u", i);
7808 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7809 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7810 			    i, sysctl_tp_backoff, "IU",
7811 			    "TOE retransmit backoff");
7812 		}
7813 	}
7814 #endif
7815 }
7816 
7817 void
7818 vi_sysctls(struct vi_info *vi)
7819 {
7820 	struct sysctl_ctx_list *ctx = &vi->ctx;
7821 	struct sysctl_oid *oid;
7822 	struct sysctl_oid_list *children;
7823 
7824 	/*
7825 	 * dev.v?(cxgbe|cxl).X.
7826 	 */
7827 	oid = device_get_sysctl_tree(vi->dev);
7828 	children = SYSCTL_CHILDREN(oid);
7829 
7830 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7831 	    vi->viid, "VI identifer");
7832 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7833 	    &vi->nrxq, 0, "# of rx queues");
7834 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7835 	    &vi->ntxq, 0, "# of tx queues");
7836 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7837 	    &vi->first_rxq, 0, "index of first rx queue");
7838 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7839 	    &vi->first_txq, 0, "index of first tx queue");
7840 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7841 	    vi->rss_base, "start of RSS indirection table");
7842 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7843 	    vi->rss_size, "size of RSS indirection table");
7844 
7845 	if (IS_MAIN_VI(vi)) {
7846 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7847 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7848 		    sysctl_noflowq, "IU",
7849 		    "Reserve queue 0 for non-flowid packets");
7850 	}
7851 
7852 	if (vi->adapter->flags & IS_VF) {
7853 		MPASS(vi->flags & TX_USES_VM_WR);
7854 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7855 		    NULL, 1, "use VM work requests for transmit");
7856 	} else {
7857 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7858 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7859 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7860 	}
7861 
7862 #ifdef TCP_OFFLOAD
7863 	if (vi->nofldrxq != 0) {
7864 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7865 		    &vi->nofldrxq, 0,
7866 		    "# of rx queues for offloaded TCP connections");
7867 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7868 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7869 		    "index of first TOE rx queue");
7870 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7871 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7872 		    sysctl_holdoff_tmr_idx_ofld, "I",
7873 		    "holdoff timer index for TOE queues");
7874 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7875 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7876 		    sysctl_holdoff_pktc_idx_ofld, "I",
7877 		    "holdoff packet counter index for TOE queues");
7878 	}
7879 #endif
7880 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7881 	if (vi->nofldtxq != 0) {
7882 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7883 		    &vi->nofldtxq, 0,
7884 		    "# of tx queues for TOE/ETHOFLD");
7885 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7886 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7887 		    "index of first TOE/ETHOFLD tx queue");
7888 	}
7889 #endif
7890 #ifdef DEV_NETMAP
7891 	if (vi->nnmrxq != 0) {
7892 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7893 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7894 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7895 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7896 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7897 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7898 		    "index of first netmap rx queue");
7899 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7900 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7901 		    "index of first netmap tx queue");
7902 	}
7903 #endif
7904 
7905 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7906 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7907 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7908 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7909 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7910 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7911 
7912 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7913 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7914 	    sysctl_qsize_rxq, "I", "rx queue size");
7915 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7916 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7917 	    sysctl_qsize_txq, "I", "tx queue size");
7918 }
7919 
7920 static void
7921 cxgbe_sysctls(struct port_info *pi)
7922 {
7923 	struct sysctl_ctx_list *ctx = &pi->ctx;
7924 	struct sysctl_oid *oid;
7925 	struct sysctl_oid_list *children, *children2;
7926 	struct adapter *sc = pi->adapter;
7927 	int i;
7928 	char name[16];
7929 	static char *tc_flags = {"\20\1USER"};
7930 
7931 	/*
7932 	 * dev.cxgbe.X.
7933 	 */
7934 	oid = device_get_sysctl_tree(pi->dev);
7935 	children = SYSCTL_CHILDREN(oid);
7936 
7937 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7938 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7939 	    sysctl_linkdnrc, "A", "reason why link is down");
7940 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7941 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7942 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7943 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7944 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7945 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7946 		    sysctl_btphy, "I", "PHY firmware version");
7947 	}
7948 
7949 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7950 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7951 	    sysctl_pause_settings, "A",
7952 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7953 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7954 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7955 	    "FEC in use on the link");
7956 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7957 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7958 	    sysctl_requested_fec, "A",
7959 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7960 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7961 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7962 	    "FEC recommended by the cable/transceiver");
7963 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7964 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7965 	    sysctl_autoneg, "I",
7966 	    "autonegotiation (-1 = not supported)");
7967 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7968 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7969 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7970 
7971 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7972 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7973 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7974 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7975 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7976 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7977 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7978 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7979 
7980 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7981 	    port_top_speed(pi), "max speed (in Gbps)");
7982 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7983 	    pi->mps_bg_map, "MPS buffer group map");
7984 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7985 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7986 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
7987 	    pi->tx_chan, "TP tx c-channel");
7988 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
7989 	    pi->rx_chan, "TP rx c-channel");
7990 
7991 	if (sc->flags & IS_VF)
7992 		return;
7993 
7994 	/*
7995 	 * dev.(cxgbe|cxl).X.tc.
7996 	 */
7997 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7998 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7999 	    "Tx scheduler traffic classes (cl_rl)");
8000 	children2 = SYSCTL_CHILDREN(oid);
8001 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8002 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8003 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8004 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8005 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8006 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8007 	for (i = 0; i < sc->params.nsched_cls; i++) {
8008 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8009 
8010 		snprintf(name, sizeof(name), "%d", i);
8011 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8012 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8013 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8014 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8015 		    CTLFLAG_RD, &tc->state, 0, "current state");
8016 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8017 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8018 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8019 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8020 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8021 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8022 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8023 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8024 		    "traffic class parameters");
8025 	}
8026 
8027 	/*
8028 	 * dev.cxgbe.X.stats.
8029 	 */
8030 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8031 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8032 	children = SYSCTL_CHILDREN(oid);
8033 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8034 	    &pi->tx_parse_error, 0,
8035 	    "# of tx packets with invalid length or # of segments");
8036 
8037 #define T4_REGSTAT(name, stat, desc) \
8038     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8039 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8040 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8041         sysctl_handle_t4_reg64, "QU", desc)
8042 
8043 /* We get these from port_stats and they may be stale by up to 1s */
8044 #define T4_PORTSTAT(name, desc) \
8045 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8046 	    &pi->stats.name, desc)
8047 
8048 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8049 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8050 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8051 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8052 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8053 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8054 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8055 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8056 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8057 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8058 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8059 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8060 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8061 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8062 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8063 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8064 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8065 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8066 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8067 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8068 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8069 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8070 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8071 
8072 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8073 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8074 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8075 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8076 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8077 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8078 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8079 	if (is_t6(sc)) {
8080 		T4_PORTSTAT(rx_fcs_err,
8081 		    "# of frames received with bad FCS since last link up");
8082 	} else {
8083 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8084 		    "# of frames received with bad FCS");
8085 	}
8086 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8087 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8088 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8089 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8090 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8091 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8092 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8093 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8094 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8095 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8096 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8097 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8098 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8099 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8100 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8101 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8102 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8103 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8104 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8105 
8106 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8107 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8108 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8109 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8110 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8111 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8112 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8113 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8114 
8115 #undef T4_REGSTAT
8116 #undef T4_PORTSTAT
8117 }
8118 
8119 static int
8120 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8121 {
8122 	int rc, *i, space = 0;
8123 	struct sbuf sb;
8124 
8125 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8126 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8127 		if (space)
8128 			sbuf_printf(&sb, " ");
8129 		sbuf_printf(&sb, "%d", *i);
8130 		space = 1;
8131 	}
8132 	rc = sbuf_finish(&sb);
8133 	sbuf_delete(&sb);
8134 	return (rc);
8135 }
8136 
8137 static int
8138 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8139 {
8140 	int rc;
8141 	struct sbuf *sb;
8142 
8143 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8144 	if (sb == NULL)
8145 		return (ENOMEM);
8146 
8147 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8148 	rc = sbuf_finish(sb);
8149 	sbuf_delete(sb);
8150 
8151 	return (rc);
8152 }
8153 
8154 static int
8155 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8156 {
8157 	int rc;
8158 	struct sbuf *sb;
8159 
8160 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8161 	if (sb == NULL)
8162 		return (ENOMEM);
8163 
8164 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8165 	rc = sbuf_finish(sb);
8166 	sbuf_delete(sb);
8167 
8168 	return (rc);
8169 }
8170 
8171 static int
8172 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8173 {
8174 	struct port_info *pi = arg1;
8175 	int op = arg2;
8176 	struct adapter *sc = pi->adapter;
8177 	u_int v;
8178 	int rc;
8179 
8180 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8181 	if (rc)
8182 		return (rc);
8183 	if (hw_off_limits(sc))
8184 		rc = ENXIO;
8185 	else {
8186 		/* XXX: magic numbers */
8187 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8188 		    op ? 0x20 : 0xc820, &v);
8189 	}
8190 	end_synchronized_op(sc, 0);
8191 	if (rc)
8192 		return (rc);
8193 	if (op == 0)
8194 		v /= 256;
8195 
8196 	rc = sysctl_handle_int(oidp, &v, 0, req);
8197 	return (rc);
8198 }
8199 
8200 static int
8201 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8202 {
8203 	struct vi_info *vi = arg1;
8204 	int rc, val;
8205 
8206 	val = vi->rsrv_noflowq;
8207 	rc = sysctl_handle_int(oidp, &val, 0, req);
8208 	if (rc != 0 || req->newptr == NULL)
8209 		return (rc);
8210 
8211 	if ((val >= 1) && (vi->ntxq > 1))
8212 		vi->rsrv_noflowq = 1;
8213 	else
8214 		vi->rsrv_noflowq = 0;
8215 
8216 	return (rc);
8217 }
8218 
8219 static int
8220 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8221 {
8222 	struct vi_info *vi = arg1;
8223 	struct adapter *sc = vi->adapter;
8224 	int rc, val, i;
8225 
8226 	MPASS(!(sc->flags & IS_VF));
8227 
8228 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8229 	rc = sysctl_handle_int(oidp, &val, 0, req);
8230 	if (rc != 0 || req->newptr == NULL)
8231 		return (rc);
8232 
8233 	if (val != 0 && val != 1)
8234 		return (EINVAL);
8235 
8236 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8237 	    "t4txvm");
8238 	if (rc)
8239 		return (rc);
8240 	if (hw_off_limits(sc))
8241 		rc = ENXIO;
8242 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8243 		/*
8244 		 * We don't want parse_pkt to run with one setting (VF or PF)
8245 		 * and then eth_tx to see a different setting but still use
8246 		 * stale information calculated by parse_pkt.
8247 		 */
8248 		rc = EBUSY;
8249 	} else {
8250 		struct port_info *pi = vi->pi;
8251 		struct sge_txq *txq;
8252 		uint32_t ctrl0;
8253 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8254 
8255 		if (val) {
8256 			vi->flags |= TX_USES_VM_WR;
8257 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8258 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8259 			    V_TXPKT_INTF(pi->tx_chan));
8260 			if (!(sc->flags & IS_VF))
8261 				npkt--;
8262 		} else {
8263 			vi->flags &= ~TX_USES_VM_WR;
8264 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8265 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8266 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8267 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8268 		}
8269 		for_each_txq(vi, i, txq) {
8270 			txq->cpl_ctrl0 = ctrl0;
8271 			txq->txp.max_npkt = npkt;
8272 		}
8273 	}
8274 	end_synchronized_op(sc, LOCK_HELD);
8275 	return (rc);
8276 }
8277 
8278 static int
8279 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8280 {
8281 	struct vi_info *vi = arg1;
8282 	struct adapter *sc = vi->adapter;
8283 	int idx, rc, i;
8284 	struct sge_rxq *rxq;
8285 	uint8_t v;
8286 
8287 	idx = vi->tmr_idx;
8288 
8289 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8290 	if (rc != 0 || req->newptr == NULL)
8291 		return (rc);
8292 
8293 	if (idx < 0 || idx >= SGE_NTIMERS)
8294 		return (EINVAL);
8295 
8296 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8297 	    "t4tmr");
8298 	if (rc)
8299 		return (rc);
8300 
8301 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8302 	for_each_rxq(vi, i, rxq) {
8303 #ifdef atomic_store_rel_8
8304 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8305 #else
8306 		rxq->iq.intr_params = v;
8307 #endif
8308 	}
8309 	vi->tmr_idx = idx;
8310 
8311 	end_synchronized_op(sc, LOCK_HELD);
8312 	return (0);
8313 }
8314 
8315 static int
8316 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8317 {
8318 	struct vi_info *vi = arg1;
8319 	struct adapter *sc = vi->adapter;
8320 	int idx, rc;
8321 
8322 	idx = vi->pktc_idx;
8323 
8324 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8325 	if (rc != 0 || req->newptr == NULL)
8326 		return (rc);
8327 
8328 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8329 		return (EINVAL);
8330 
8331 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8332 	    "t4pktc");
8333 	if (rc)
8334 		return (rc);
8335 
8336 	if (vi->flags & VI_INIT_DONE)
8337 		rc = EBUSY; /* cannot be changed once the queues are created */
8338 	else
8339 		vi->pktc_idx = idx;
8340 
8341 	end_synchronized_op(sc, LOCK_HELD);
8342 	return (rc);
8343 }
8344 
8345 static int
8346 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8347 {
8348 	struct vi_info *vi = arg1;
8349 	struct adapter *sc = vi->adapter;
8350 	int qsize, rc;
8351 
8352 	qsize = vi->qsize_rxq;
8353 
8354 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8355 	if (rc != 0 || req->newptr == NULL)
8356 		return (rc);
8357 
8358 	if (qsize < 128 || (qsize & 7))
8359 		return (EINVAL);
8360 
8361 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8362 	    "t4rxqs");
8363 	if (rc)
8364 		return (rc);
8365 
8366 	if (vi->flags & VI_INIT_DONE)
8367 		rc = EBUSY; /* cannot be changed once the queues are created */
8368 	else
8369 		vi->qsize_rxq = qsize;
8370 
8371 	end_synchronized_op(sc, LOCK_HELD);
8372 	return (rc);
8373 }
8374 
8375 static int
8376 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8377 {
8378 	struct vi_info *vi = arg1;
8379 	struct adapter *sc = vi->adapter;
8380 	int qsize, rc;
8381 
8382 	qsize = vi->qsize_txq;
8383 
8384 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8385 	if (rc != 0 || req->newptr == NULL)
8386 		return (rc);
8387 
8388 	if (qsize < 128 || qsize > 65536)
8389 		return (EINVAL);
8390 
8391 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8392 	    "t4txqs");
8393 	if (rc)
8394 		return (rc);
8395 
8396 	if (vi->flags & VI_INIT_DONE)
8397 		rc = EBUSY; /* cannot be changed once the queues are created */
8398 	else
8399 		vi->qsize_txq = qsize;
8400 
8401 	end_synchronized_op(sc, LOCK_HELD);
8402 	return (rc);
8403 }
8404 
8405 static int
8406 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8407 {
8408 	struct port_info *pi = arg1;
8409 	struct adapter *sc = pi->adapter;
8410 	struct link_config *lc = &pi->link_cfg;
8411 	int rc;
8412 
8413 	if (req->newptr == NULL) {
8414 		struct sbuf *sb;
8415 		static char *bits = "\20\1RX\2TX\3AUTO";
8416 
8417 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8418 		if (sb == NULL)
8419 			return (ENOMEM);
8420 
8421 		if (lc->link_ok) {
8422 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8423 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8424 		} else {
8425 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8426 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8427 		}
8428 		rc = sbuf_finish(sb);
8429 		sbuf_delete(sb);
8430 	} else {
8431 		char s[2];
8432 		int n;
8433 
8434 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8435 		    PAUSE_AUTONEG));
8436 		s[1] = 0;
8437 
8438 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8439 		if (rc != 0)
8440 			return(rc);
8441 
8442 		if (s[1] != 0)
8443 			return (EINVAL);
8444 		if (s[0] < '0' || s[0] > '9')
8445 			return (EINVAL);	/* not a number */
8446 		n = s[0] - '0';
8447 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8448 			return (EINVAL);	/* some other bit is set too */
8449 
8450 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8451 		    "t4PAUSE");
8452 		if (rc)
8453 			return (rc);
8454 		if (!hw_off_limits(sc)) {
8455 			PORT_LOCK(pi);
8456 			lc->requested_fc = n;
8457 			fixup_link_config(pi);
8458 			if (pi->up_vis > 0)
8459 				rc = apply_link_config(pi);
8460 			set_current_media(pi);
8461 			PORT_UNLOCK(pi);
8462 		}
8463 		end_synchronized_op(sc, 0);
8464 	}
8465 
8466 	return (rc);
8467 }
8468 
8469 static int
8470 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8471 {
8472 	struct port_info *pi = arg1;
8473 	struct link_config *lc = &pi->link_cfg;
8474 	int rc;
8475 	struct sbuf *sb;
8476 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8477 
8478 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8479 	if (sb == NULL)
8480 		return (ENOMEM);
8481 	if (lc->link_ok)
8482 		sbuf_printf(sb, "%b", lc->fec, bits);
8483 	else
8484 		sbuf_printf(sb, "no link");
8485 	rc = sbuf_finish(sb);
8486 	sbuf_delete(sb);
8487 
8488 	return (rc);
8489 }
8490 
8491 static int
8492 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8493 {
8494 	struct port_info *pi = arg1;
8495 	struct adapter *sc = pi->adapter;
8496 	struct link_config *lc = &pi->link_cfg;
8497 	int rc;
8498 	int8_t old;
8499 
8500 	if (req->newptr == NULL) {
8501 		struct sbuf *sb;
8502 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8503 		    "\5RSVD3\6auto\7module";
8504 
8505 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8506 		if (sb == NULL)
8507 			return (ENOMEM);
8508 
8509 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8510 		rc = sbuf_finish(sb);
8511 		sbuf_delete(sb);
8512 	} else {
8513 		char s[8];
8514 		int n;
8515 
8516 		snprintf(s, sizeof(s), "%d",
8517 		    lc->requested_fec == FEC_AUTO ? -1 :
8518 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8519 
8520 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8521 		if (rc != 0)
8522 			return(rc);
8523 
8524 		n = strtol(&s[0], NULL, 0);
8525 		if (n < 0 || n & FEC_AUTO)
8526 			n = FEC_AUTO;
8527 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8528 			return (EINVAL);/* some other bit is set too */
8529 
8530 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8531 		    "t4reqf");
8532 		if (rc)
8533 			return (rc);
8534 		PORT_LOCK(pi);
8535 		old = lc->requested_fec;
8536 		if (n == FEC_AUTO)
8537 			lc->requested_fec = FEC_AUTO;
8538 		else if (n == 0 || n == FEC_NONE)
8539 			lc->requested_fec = FEC_NONE;
8540 		else {
8541 			if ((lc->pcaps |
8542 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8543 			    lc->pcaps) {
8544 				rc = ENOTSUP;
8545 				goto done;
8546 			}
8547 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8548 			    FEC_MODULE);
8549 		}
8550 		if (!hw_off_limits(sc)) {
8551 			fixup_link_config(pi);
8552 			if (pi->up_vis > 0) {
8553 				rc = apply_link_config(pi);
8554 				if (rc != 0) {
8555 					lc->requested_fec = old;
8556 					if (rc == FW_EPROTO)
8557 						rc = ENOTSUP;
8558 				}
8559 			}
8560 		}
8561 done:
8562 		PORT_UNLOCK(pi);
8563 		end_synchronized_op(sc, 0);
8564 	}
8565 
8566 	return (rc);
8567 }
8568 
8569 static int
8570 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8571 {
8572 	struct port_info *pi = arg1;
8573 	struct adapter *sc = pi->adapter;
8574 	struct link_config *lc = &pi->link_cfg;
8575 	int rc;
8576 	int8_t fec;
8577 	struct sbuf *sb;
8578 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8579 
8580 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8581 	if (sb == NULL)
8582 		return (ENOMEM);
8583 
8584 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8585 		rc = EBUSY;
8586 		goto done;
8587 	}
8588 	if (hw_off_limits(sc)) {
8589 		rc = ENXIO;
8590 		goto done;
8591 	}
8592 	PORT_LOCK(pi);
8593 	if (pi->up_vis == 0) {
8594 		/*
8595 		 * If all the interfaces are administratively down the firmware
8596 		 * does not report transceiver changes.  Refresh port info here.
8597 		 * This is the only reason we have a synchronized op in this
8598 		 * function.  Just PORT_LOCK would have been enough otherwise.
8599 		 */
8600 		t4_update_port_info(pi);
8601 	}
8602 
8603 	fec = lc->fec_hint;
8604 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8605 	    !fec_supported(lc->pcaps)) {
8606 		PORT_UNLOCK(pi);
8607 		sbuf_printf(sb, "n/a");
8608 	} else {
8609 		if (fec == 0)
8610 			fec = FEC_NONE;
8611 		PORT_UNLOCK(pi);
8612 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8613 	}
8614 	rc = sbuf_finish(sb);
8615 done:
8616 	sbuf_delete(sb);
8617 	end_synchronized_op(sc, 0);
8618 
8619 	return (rc);
8620 }
8621 
8622 static int
8623 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8624 {
8625 	struct port_info *pi = arg1;
8626 	struct adapter *sc = pi->adapter;
8627 	struct link_config *lc = &pi->link_cfg;
8628 	int rc, val;
8629 
8630 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8631 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8632 	else
8633 		val = -1;
8634 	rc = sysctl_handle_int(oidp, &val, 0, req);
8635 	if (rc != 0 || req->newptr == NULL)
8636 		return (rc);
8637 	if (val == 0)
8638 		val = AUTONEG_DISABLE;
8639 	else if (val == 1)
8640 		val = AUTONEG_ENABLE;
8641 	else
8642 		val = AUTONEG_AUTO;
8643 
8644 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8645 	    "t4aneg");
8646 	if (rc)
8647 		return (rc);
8648 	PORT_LOCK(pi);
8649 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8650 		rc = ENOTSUP;
8651 		goto done;
8652 	}
8653 	lc->requested_aneg = val;
8654 	if (!hw_off_limits(sc)) {
8655 		fixup_link_config(pi);
8656 		if (pi->up_vis > 0)
8657 			rc = apply_link_config(pi);
8658 		set_current_media(pi);
8659 	}
8660 done:
8661 	PORT_UNLOCK(pi);
8662 	end_synchronized_op(sc, 0);
8663 	return (rc);
8664 }
8665 
8666 static int
8667 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8668 {
8669 	struct port_info *pi = arg1;
8670 	struct adapter *sc = pi->adapter;
8671 	struct link_config *lc = &pi->link_cfg;
8672 	int rc, val;
8673 
8674 	val = lc->force_fec;
8675 	MPASS(val >= -1 && val <= 1);
8676 	rc = sysctl_handle_int(oidp, &val, 0, req);
8677 	if (rc != 0 || req->newptr == NULL)
8678 		return (rc);
8679 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8680 		return (ENOTSUP);
8681 	if (val < -1 || val > 1)
8682 		return (EINVAL);
8683 
8684 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8685 	if (rc)
8686 		return (rc);
8687 	PORT_LOCK(pi);
8688 	lc->force_fec = val;
8689 	if (!hw_off_limits(sc)) {
8690 		fixup_link_config(pi);
8691 		if (pi->up_vis > 0)
8692 			rc = apply_link_config(pi);
8693 	}
8694 	PORT_UNLOCK(pi);
8695 	end_synchronized_op(sc, 0);
8696 	return (rc);
8697 }
8698 
8699 static int
8700 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8701 {
8702 	struct adapter *sc = arg1;
8703 	int rc, reg = arg2;
8704 	uint64_t val;
8705 
8706 	mtx_lock(&sc->reg_lock);
8707 	if (hw_off_limits(sc))
8708 		rc = ENXIO;
8709 	else {
8710 		rc = 0;
8711 		val = t4_read_reg64(sc, reg);
8712 	}
8713 	mtx_unlock(&sc->reg_lock);
8714 	if (rc == 0)
8715 		rc = sysctl_handle_64(oidp, &val, 0, req);
8716 	return (rc);
8717 }
8718 
8719 static int
8720 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8721 {
8722 	struct adapter *sc = arg1;
8723 	int rc, t;
8724 	uint32_t param, val;
8725 
8726 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8727 	if (rc)
8728 		return (rc);
8729 	if (hw_off_limits(sc))
8730 		rc = ENXIO;
8731 	else {
8732 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8733 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8734 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8735 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8736 	}
8737 	end_synchronized_op(sc, 0);
8738 	if (rc)
8739 		return (rc);
8740 
8741 	/* unknown is returned as 0 but we display -1 in that case */
8742 	t = val == 0 ? -1 : val;
8743 
8744 	rc = sysctl_handle_int(oidp, &t, 0, req);
8745 	return (rc);
8746 }
8747 
8748 static int
8749 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8750 {
8751 	struct adapter *sc = arg1;
8752 	int rc;
8753 	uint32_t param, val;
8754 
8755 	if (sc->params.core_vdd == 0) {
8756 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8757 		    "t4vdd");
8758 		if (rc)
8759 			return (rc);
8760 		if (hw_off_limits(sc))
8761 			rc = ENXIO;
8762 		else {
8763 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8764 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8765 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8766 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8767 			    &param, &val);
8768 		}
8769 		end_synchronized_op(sc, 0);
8770 		if (rc)
8771 			return (rc);
8772 		sc->params.core_vdd = val;
8773 	}
8774 
8775 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8776 }
8777 
8778 static int
8779 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8780 {
8781 	struct adapter *sc = arg1;
8782 	int rc, v;
8783 	uint32_t param, val;
8784 
8785 	v = sc->sensor_resets;
8786 	rc = sysctl_handle_int(oidp, &v, 0, req);
8787 	if (rc != 0 || req->newptr == NULL || v <= 0)
8788 		return (rc);
8789 
8790 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8791 	    chip_id(sc) < CHELSIO_T5)
8792 		return (ENOTSUP);
8793 
8794 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8795 	if (rc)
8796 		return (rc);
8797 	if (hw_off_limits(sc))
8798 		rc = ENXIO;
8799 	else {
8800 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8801 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8802 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8803 		val = 1;
8804 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8805 	}
8806 	end_synchronized_op(sc, 0);
8807 	if (rc == 0)
8808 		sc->sensor_resets++;
8809 	return (rc);
8810 }
8811 
8812 static int
8813 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8814 {
8815 	struct adapter *sc = arg1;
8816 	struct sbuf *sb;
8817 	int rc;
8818 	uint32_t param, val;
8819 
8820 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8821 	if (rc)
8822 		return (rc);
8823 	if (hw_off_limits(sc))
8824 		rc = ENXIO;
8825 	else {
8826 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8827 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8828 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8829 	}
8830 	end_synchronized_op(sc, 0);
8831 	if (rc)
8832 		return (rc);
8833 
8834 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8835 	if (sb == NULL)
8836 		return (ENOMEM);
8837 
8838 	if (val == 0xffffffff) {
8839 		/* Only debug and custom firmwares report load averages. */
8840 		sbuf_printf(sb, "not available");
8841 	} else {
8842 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8843 		    (val >> 16) & 0xff);
8844 	}
8845 	rc = sbuf_finish(sb);
8846 	sbuf_delete(sb);
8847 
8848 	return (rc);
8849 }
8850 
8851 static int
8852 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8853 {
8854 	struct adapter *sc = arg1;
8855 	struct sbuf *sb;
8856 	int rc, i;
8857 	uint16_t incr[NMTUS][NCCTRL_WIN];
8858 	static const char *dec_fac[] = {
8859 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8860 		"0.9375"
8861 	};
8862 
8863 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8864 	if (sb == NULL)
8865 		return (ENOMEM);
8866 
8867 	rc = 0;
8868 	mtx_lock(&sc->reg_lock);
8869 	if (hw_off_limits(sc))
8870 		rc = ENXIO;
8871 	else
8872 		t4_read_cong_tbl(sc, incr);
8873 	mtx_unlock(&sc->reg_lock);
8874 	if (rc)
8875 		goto done;
8876 
8877 	for (i = 0; i < NCCTRL_WIN; ++i) {
8878 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8879 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8880 		    incr[5][i], incr[6][i], incr[7][i]);
8881 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8882 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8883 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8884 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8885 	}
8886 
8887 	rc = sbuf_finish(sb);
8888 done:
8889 	sbuf_delete(sb);
8890 	return (rc);
8891 }
8892 
8893 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8894 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8895 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8896 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8897 };
8898 
8899 static int
8900 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8901 {
8902 	struct adapter *sc = arg1;
8903 	struct sbuf *sb;
8904 	int rc, i, n, qid = arg2;
8905 	uint32_t *buf, *p;
8906 	char *qtype;
8907 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8908 
8909 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8910 	    ("%s: bad qid %d\n", __func__, qid));
8911 
8912 	if (qid < CIM_NUM_IBQ) {
8913 		/* inbound queue */
8914 		qtype = "IBQ";
8915 		n = 4 * CIM_IBQ_SIZE;
8916 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8917 		mtx_lock(&sc->reg_lock);
8918 		if (hw_off_limits(sc))
8919 			rc = -ENXIO;
8920 		else
8921 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8922 		mtx_unlock(&sc->reg_lock);
8923 	} else {
8924 		/* outbound queue */
8925 		qtype = "OBQ";
8926 		qid -= CIM_NUM_IBQ;
8927 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8928 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8929 		mtx_lock(&sc->reg_lock);
8930 		if (hw_off_limits(sc))
8931 			rc = -ENXIO;
8932 		else
8933 			rc = t4_read_cim_obq(sc, qid, buf, n);
8934 		mtx_unlock(&sc->reg_lock);
8935 	}
8936 
8937 	if (rc < 0) {
8938 		rc = -rc;
8939 		goto done;
8940 	}
8941 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8942 
8943 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8944 	if (sb == NULL) {
8945 		rc = ENOMEM;
8946 		goto done;
8947 	}
8948 
8949 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8950 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8951 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8952 		    p[2], p[3]);
8953 
8954 	rc = sbuf_finish(sb);
8955 	sbuf_delete(sb);
8956 done:
8957 	free(buf, M_CXGBE);
8958 	return (rc);
8959 }
8960 
8961 static void
8962 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8963 {
8964 	uint32_t *p;
8965 
8966 	sbuf_printf(sb, "Status   Data      PC%s",
8967 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8968 	    "     LS0Stat  LS0Addr             LS0Data");
8969 
8970 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8971 		if (cfg & F_UPDBGLACAPTPCONLY) {
8972 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8973 			    p[6], p[7]);
8974 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8975 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8976 			    p[4] & 0xff, p[5] >> 8);
8977 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8978 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8979 			    p[1] & 0xf, p[2] >> 4);
8980 		} else {
8981 			sbuf_printf(sb,
8982 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8983 			    "%08x%08x%08x%08x",
8984 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8985 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8986 			    p[6], p[7]);
8987 		}
8988 	}
8989 }
8990 
8991 static void
8992 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8993 {
8994 	uint32_t *p;
8995 
8996 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
8997 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8998 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
8999 
9000 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9001 		if (cfg & F_UPDBGLACAPTPCONLY) {
9002 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9003 			    p[3] & 0xff, p[2], p[1], p[0]);
9004 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9005 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9006 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9007 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9008 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9009 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9010 			    p[6] >> 16);
9011 		} else {
9012 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9013 			    "%08x %08x %08x %08x %08x %08x",
9014 			    (p[9] >> 16) & 0xff,
9015 			    p[9] & 0xffff, p[8] >> 16,
9016 			    p[8] & 0xffff, p[7] >> 16,
9017 			    p[7] & 0xffff, p[6] >> 16,
9018 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9019 		}
9020 	}
9021 }
9022 
9023 static int
9024 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9025 {
9026 	uint32_t cfg, *buf;
9027 	int rc;
9028 
9029 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9030 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9031 	    M_ZERO | flags);
9032 	if (buf == NULL)
9033 		return (ENOMEM);
9034 
9035 	mtx_lock(&sc->reg_lock);
9036 	if (hw_off_limits(sc))
9037 		rc = ENXIO;
9038 	else {
9039 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9040 		if (rc == 0)
9041 			rc = -t4_cim_read_la(sc, buf, NULL);
9042 	}
9043 	mtx_unlock(&sc->reg_lock);
9044 	if (rc == 0) {
9045 		if (chip_id(sc) < CHELSIO_T6)
9046 			sbuf_cim_la4(sc, sb, buf, cfg);
9047 		else
9048 			sbuf_cim_la6(sc, sb, buf, cfg);
9049 	}
9050 	free(buf, M_CXGBE);
9051 	return (rc);
9052 }
9053 
9054 static int
9055 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9056 {
9057 	struct adapter *sc = arg1;
9058 	struct sbuf *sb;
9059 	int rc;
9060 
9061 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9062 	if (sb == NULL)
9063 		return (ENOMEM);
9064 
9065 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9066 	if (rc == 0)
9067 		rc = sbuf_finish(sb);
9068 	sbuf_delete(sb);
9069 	return (rc);
9070 }
9071 
9072 static void
9073 dump_cim_regs(struct adapter *sc)
9074 {
9075 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9076 	    device_get_nameunit(sc->dev),
9077 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9078 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9079 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9080 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9081 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9082 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9083 	    device_get_nameunit(sc->dev),
9084 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9085 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9086 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9087 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9088 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9089 }
9090 
9091 static void
9092 dump_cimla(struct adapter *sc)
9093 {
9094 	struct sbuf sb;
9095 	int rc;
9096 
9097 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9098 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9099 		    device_get_nameunit(sc->dev));
9100 		return;
9101 	}
9102 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9103 	if (rc == 0) {
9104 		rc = sbuf_finish(&sb);
9105 		if (rc == 0) {
9106 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9107 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9108 		}
9109 	}
9110 	sbuf_delete(&sb);
9111 }
9112 
9113 void
9114 t4_os_cim_err(struct adapter *sc)
9115 {
9116 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9117 }
9118 
9119 static int
9120 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9121 {
9122 	struct adapter *sc = arg1;
9123 	u_int i;
9124 	struct sbuf *sb;
9125 	uint32_t *buf, *p;
9126 	int rc;
9127 
9128 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9129 	if (sb == NULL)
9130 		return (ENOMEM);
9131 
9132 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9133 	    M_ZERO | M_WAITOK);
9134 
9135 	rc = 0;
9136 	mtx_lock(&sc->reg_lock);
9137 	if (hw_off_limits(sc))
9138 		rc = ENXIO;
9139 	else
9140 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9141 	mtx_unlock(&sc->reg_lock);
9142 	if (rc)
9143 		goto done;
9144 
9145 	p = buf;
9146 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9147 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9148 		    p[1], p[0]);
9149 	}
9150 
9151 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9152 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9153 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9154 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9155 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9156 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9157 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9158 		    p[0] & 1);
9159 	}
9160 	rc = sbuf_finish(sb);
9161 done:
9162 	sbuf_delete(sb);
9163 	free(buf, M_CXGBE);
9164 	return (rc);
9165 }
9166 
9167 static int
9168 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9169 {
9170 	struct adapter *sc = arg1;
9171 	u_int i;
9172 	struct sbuf *sb;
9173 	uint32_t *buf, *p;
9174 	int rc;
9175 
9176 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9177 	if (sb == NULL)
9178 		return (ENOMEM);
9179 
9180 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9181 	    M_ZERO | M_WAITOK);
9182 
9183 	rc = 0;
9184 	mtx_lock(&sc->reg_lock);
9185 	if (hw_off_limits(sc))
9186 		rc = ENXIO;
9187 	else
9188 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9189 	mtx_unlock(&sc->reg_lock);
9190 	if (rc)
9191 		goto done;
9192 
9193 	p = buf;
9194 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9195 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9196 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9197 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9198 		    p[4], p[3], p[2], p[1], p[0]);
9199 	}
9200 
9201 	sbuf_printf(sb, "\n\nCntl ID               Data");
9202 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9203 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9204 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9205 	}
9206 
9207 	rc = sbuf_finish(sb);
9208 done:
9209 	sbuf_delete(sb);
9210 	free(buf, M_CXGBE);
9211 	return (rc);
9212 }
9213 
9214 static int
9215 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9216 {
9217 	struct adapter *sc = arg1;
9218 	struct sbuf *sb;
9219 	int rc, i;
9220 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9221 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9222 	uint16_t thres[CIM_NUM_IBQ];
9223 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9224 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9225 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9226 
9227 	cim_num_obq = sc->chip_params->cim_num_obq;
9228 	if (is_t4(sc)) {
9229 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9230 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9231 	} else {
9232 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9233 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9234 	}
9235 	nq = CIM_NUM_IBQ + cim_num_obq;
9236 
9237 	mtx_lock(&sc->reg_lock);
9238 	if (hw_off_limits(sc))
9239 		rc = ENXIO;
9240 	else {
9241 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9242 		if (rc == 0) {
9243 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9244 			    obq_wr);
9245 			if (rc == 0)
9246 				t4_read_cimq_cfg(sc, base, size, thres);
9247 		}
9248 	}
9249 	mtx_unlock(&sc->reg_lock);
9250 	if (rc)
9251 		return (rc);
9252 
9253 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9254 	if (sb == NULL)
9255 		return (ENOMEM);
9256 
9257 	sbuf_printf(sb,
9258 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9259 
9260 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9261 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9262 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9263 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9264 		    G_QUEREMFLITS(p[2]) * 16);
9265 	for ( ; i < nq; i++, p += 4, wr += 2)
9266 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9267 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9268 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9269 		    G_QUEREMFLITS(p[2]) * 16);
9270 
9271 	rc = sbuf_finish(sb);
9272 	sbuf_delete(sb);
9273 
9274 	return (rc);
9275 }
9276 
9277 static int
9278 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9279 {
9280 	struct adapter *sc = arg1;
9281 	struct sbuf *sb;
9282 	int rc;
9283 	struct tp_cpl_stats stats;
9284 
9285 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9286 	if (sb == NULL)
9287 		return (ENOMEM);
9288 
9289 	rc = 0;
9290 	mtx_lock(&sc->reg_lock);
9291 	if (hw_off_limits(sc))
9292 		rc = ENXIO;
9293 	else
9294 		t4_tp_get_cpl_stats(sc, &stats, 0);
9295 	mtx_unlock(&sc->reg_lock);
9296 	if (rc)
9297 		goto done;
9298 
9299 	if (sc->chip_params->nchan > 2) {
9300 		sbuf_printf(sb, "                 channel 0  channel 1"
9301 		    "  channel 2  channel 3");
9302 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9303 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9304 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9305 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9306 	} else {
9307 		sbuf_printf(sb, "                 channel 0  channel 1");
9308 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9309 		    stats.req[0], stats.req[1]);
9310 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9311 		    stats.rsp[0], stats.rsp[1]);
9312 	}
9313 
9314 	rc = sbuf_finish(sb);
9315 done:
9316 	sbuf_delete(sb);
9317 	return (rc);
9318 }
9319 
9320 static int
9321 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9322 {
9323 	struct adapter *sc = arg1;
9324 	struct sbuf *sb;
9325 	int rc;
9326 	struct tp_usm_stats stats;
9327 
9328 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9329 	if (sb == NULL)
9330 		return (ENOMEM);
9331 
9332 	rc = 0;
9333 	mtx_lock(&sc->reg_lock);
9334 	if (hw_off_limits(sc))
9335 		rc = ENXIO;
9336 	else
9337 		t4_get_usm_stats(sc, &stats, 1);
9338 	mtx_unlock(&sc->reg_lock);
9339 	if (rc == 0) {
9340 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9341 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9342 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9343 		rc = sbuf_finish(sb);
9344 	}
9345 	sbuf_delete(sb);
9346 
9347 	return (rc);
9348 }
9349 
9350 static int
9351 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9352 {
9353 	struct adapter *sc = arg1;
9354 	struct sbuf *sb;
9355 	int rc;
9356 	struct tp_tid_stats stats;
9357 
9358 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9359 	if (sb == NULL)
9360 		return (ENOMEM);
9361 
9362 	rc = 0;
9363 	mtx_lock(&sc->reg_lock);
9364 	if (hw_off_limits(sc))
9365 		rc = ENXIO;
9366 	else
9367 		t4_tp_get_tid_stats(sc, &stats, 1);
9368 	mtx_unlock(&sc->reg_lock);
9369 	if (rc == 0) {
9370 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9371 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9372 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9373 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9374 		rc = sbuf_finish(sb);
9375 	}
9376 	sbuf_delete(sb);
9377 
9378 	return (rc);
9379 }
9380 
9381 static const char * const devlog_level_strings[] = {
9382 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9383 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9384 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9385 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9386 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9387 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9388 };
9389 
9390 static const char * const devlog_facility_strings[] = {
9391 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9392 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9393 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9394 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9395 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9396 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9397 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9398 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9399 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9400 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9401 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9402 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9403 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9404 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9405 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9406 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9407 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9408 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9409 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9410 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9411 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9412 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9413 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9414 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9415 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9416 };
9417 
9418 static int
9419 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9420 {
9421 	int i, j, rc, nentries, first = 0;
9422 	struct devlog_params *dparams = &sc->params.devlog;
9423 	struct fw_devlog_e *buf, *e;
9424 	uint64_t ftstamp = UINT64_MAX;
9425 
9426 	if (dparams->addr == 0)
9427 		return (ENXIO);
9428 
9429 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9430 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9431 	if (buf == NULL)
9432 		return (ENOMEM);
9433 
9434 	mtx_lock(&sc->reg_lock);
9435 	if (hw_off_limits(sc))
9436 		rc = ENXIO;
9437 	else
9438 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9439 		    dparams->size);
9440 	mtx_unlock(&sc->reg_lock);
9441 	if (rc != 0)
9442 		goto done;
9443 
9444 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9445 	for (i = 0; i < nentries; i++) {
9446 		e = &buf[i];
9447 
9448 		if (e->timestamp == 0)
9449 			break;	/* end */
9450 
9451 		e->timestamp = be64toh(e->timestamp);
9452 		e->seqno = be32toh(e->seqno);
9453 		for (j = 0; j < 8; j++)
9454 			e->params[j] = be32toh(e->params[j]);
9455 
9456 		if (e->timestamp < ftstamp) {
9457 			ftstamp = e->timestamp;
9458 			first = i;
9459 		}
9460 	}
9461 
9462 	if (buf[first].timestamp == 0)
9463 		goto done;	/* nothing in the log */
9464 
9465 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9466 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9467 
9468 	i = first;
9469 	do {
9470 		e = &buf[i];
9471 		if (e->timestamp == 0)
9472 			break;	/* end */
9473 
9474 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9475 		    e->seqno, e->timestamp,
9476 		    (e->level < nitems(devlog_level_strings) ?
9477 			devlog_level_strings[e->level] : "UNKNOWN"),
9478 		    (e->facility < nitems(devlog_facility_strings) ?
9479 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9480 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9481 		    e->params[2], e->params[3], e->params[4],
9482 		    e->params[5], e->params[6], e->params[7]);
9483 
9484 		if (++i == nentries)
9485 			i = 0;
9486 	} while (i != first);
9487 done:
9488 	free(buf, M_CXGBE);
9489 	return (rc);
9490 }
9491 
9492 static int
9493 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9494 {
9495 	struct adapter *sc = arg1;
9496 	int rc;
9497 	struct sbuf *sb;
9498 
9499 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9500 	if (sb == NULL)
9501 		return (ENOMEM);
9502 
9503 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9504 	if (rc == 0)
9505 		rc = sbuf_finish(sb);
9506 	sbuf_delete(sb);
9507 	return (rc);
9508 }
9509 
9510 static void
9511 dump_devlog(struct adapter *sc)
9512 {
9513 	int rc;
9514 	struct sbuf sb;
9515 
9516 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9517 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9518 		    device_get_nameunit(sc->dev));
9519 		return;
9520 	}
9521 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9522 	if (rc == 0) {
9523 		rc = sbuf_finish(&sb);
9524 		if (rc == 0) {
9525 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9526 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9527 		}
9528 	}
9529 	sbuf_delete(&sb);
9530 }
9531 
9532 static int
9533 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9534 {
9535 	struct adapter *sc = arg1;
9536 	struct sbuf *sb;
9537 	int rc;
9538 	struct tp_fcoe_stats stats[MAX_NCHAN];
9539 	int i, nchan = sc->chip_params->nchan;
9540 
9541 	rc = 0;
9542 	mtx_lock(&sc->reg_lock);
9543 	if (hw_off_limits(sc))
9544 		rc = ENXIO;
9545 	else {
9546 		for (i = 0; i < nchan; i++)
9547 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9548 	}
9549 	mtx_unlock(&sc->reg_lock);
9550 	if (rc != 0)
9551 		return (rc);
9552 
9553 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9554 	if (sb == NULL)
9555 		return (ENOMEM);
9556 
9557 	if (nchan > 2) {
9558 		sbuf_printf(sb, "                   channel 0        channel 1"
9559 		    "        channel 2        channel 3");
9560 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9561 		    stats[0].octets_ddp, stats[1].octets_ddp,
9562 		    stats[2].octets_ddp, stats[3].octets_ddp);
9563 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9564 		    stats[0].frames_ddp, stats[1].frames_ddp,
9565 		    stats[2].frames_ddp, stats[3].frames_ddp);
9566 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9567 		    stats[0].frames_drop, stats[1].frames_drop,
9568 		    stats[2].frames_drop, stats[3].frames_drop);
9569 	} else {
9570 		sbuf_printf(sb, "                   channel 0        channel 1");
9571 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9572 		    stats[0].octets_ddp, stats[1].octets_ddp);
9573 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9574 		    stats[0].frames_ddp, stats[1].frames_ddp);
9575 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9576 		    stats[0].frames_drop, stats[1].frames_drop);
9577 	}
9578 
9579 	rc = sbuf_finish(sb);
9580 	sbuf_delete(sb);
9581 
9582 	return (rc);
9583 }
9584 
9585 static int
9586 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9587 {
9588 	struct adapter *sc = arg1;
9589 	struct sbuf *sb;
9590 	int rc, i;
9591 	unsigned int map, kbps, ipg, mode;
9592 	unsigned int pace_tab[NTX_SCHED];
9593 
9594 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9595 	if (sb == NULL)
9596 		return (ENOMEM);
9597 
9598 	mtx_lock(&sc->reg_lock);
9599 	if (hw_off_limits(sc)) {
9600 		mtx_unlock(&sc->reg_lock);
9601 		rc = ENXIO;
9602 		goto done;
9603 	}
9604 
9605 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9606 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9607 	t4_read_pace_tbl(sc, pace_tab);
9608 	mtx_unlock(&sc->reg_lock);
9609 
9610 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9611 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9612 
9613 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9614 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9615 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9616 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9617 		if (kbps)
9618 			sbuf_printf(sb, "%9u     ", kbps);
9619 		else
9620 			sbuf_printf(sb, " disabled     ");
9621 
9622 		if (ipg)
9623 			sbuf_printf(sb, "%13u        ", ipg);
9624 		else
9625 			sbuf_printf(sb, "     disabled        ");
9626 
9627 		if (pace_tab[i])
9628 			sbuf_printf(sb, "%10u", pace_tab[i]);
9629 		else
9630 			sbuf_printf(sb, "  disabled");
9631 	}
9632 	rc = sbuf_finish(sb);
9633 done:
9634 	sbuf_delete(sb);
9635 	return (rc);
9636 }
9637 
9638 static int
9639 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9640 {
9641 	struct adapter *sc = arg1;
9642 	struct sbuf *sb;
9643 	int rc, i, j;
9644 	uint64_t *p0, *p1;
9645 	struct lb_port_stats s[2];
9646 	static const char *stat_name[] = {
9647 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9648 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9649 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9650 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9651 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9652 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9653 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9654 	};
9655 
9656 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9657 	if (sb == NULL)
9658 		return (ENOMEM);
9659 
9660 	memset(s, 0, sizeof(s));
9661 
9662 	rc = 0;
9663 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9664 		mtx_lock(&sc->reg_lock);
9665 		if (hw_off_limits(sc))
9666 			rc = ENXIO;
9667 		else {
9668 			t4_get_lb_stats(sc, i, &s[0]);
9669 			t4_get_lb_stats(sc, i + 1, &s[1]);
9670 		}
9671 		mtx_unlock(&sc->reg_lock);
9672 		if (rc != 0)
9673 			break;
9674 
9675 		p0 = &s[0].octets;
9676 		p1 = &s[1].octets;
9677 		sbuf_printf(sb, "%s                       Loopback %u"
9678 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9679 
9680 		for (j = 0; j < nitems(stat_name); j++)
9681 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9682 				   *p0++, *p1++);
9683 	}
9684 
9685 	if (rc == 0)
9686 		rc = sbuf_finish(sb);
9687 	sbuf_delete(sb);
9688 
9689 	return (rc);
9690 }
9691 
9692 static int
9693 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9694 {
9695 	int rc = 0;
9696 	struct port_info *pi = arg1;
9697 	struct link_config *lc = &pi->link_cfg;
9698 	struct sbuf *sb;
9699 
9700 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9701 	if (sb == NULL)
9702 		return (ENOMEM);
9703 
9704 	if (lc->link_ok || lc->link_down_rc == 255)
9705 		sbuf_printf(sb, "n/a");
9706 	else
9707 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9708 
9709 	rc = sbuf_finish(sb);
9710 	sbuf_delete(sb);
9711 
9712 	return (rc);
9713 }
9714 
9715 struct mem_desc {
9716 	u_int base;
9717 	u_int limit;
9718 	u_int idx;
9719 };
9720 
9721 static int
9722 mem_desc_cmp(const void *a, const void *b)
9723 {
9724 	const u_int v1 = ((const struct mem_desc *)a)->base;
9725 	const u_int v2 = ((const struct mem_desc *)b)->base;
9726 
9727 	if (v1 < v2)
9728 		return (-1);
9729 	else if (v1 > v2)
9730 		return (1);
9731 
9732 	return (0);
9733 }
9734 
9735 static void
9736 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9737     unsigned int to)
9738 {
9739 	unsigned int size;
9740 
9741 	if (from == to)
9742 		return;
9743 
9744 	size = to - from + 1;
9745 	if (size == 0)
9746 		return;
9747 
9748 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9749 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9750 }
9751 
9752 static int
9753 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9754 {
9755 	struct adapter *sc = arg1;
9756 	struct sbuf *sb;
9757 	int rc, i, n;
9758 	uint32_t lo, hi, used, free, alloc;
9759 	static const char *memory[] = {
9760 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9761 	};
9762 	static const char *region[] = {
9763 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9764 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9765 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9766 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9767 		"RQUDP region:", "PBL region:", "TXPBL region:",
9768 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9769 		"ULPTX state:", "On-chip queues:",
9770 	};
9771 	struct mem_desc avail[4];
9772 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9773 	struct mem_desc *md = mem;
9774 
9775 	rc = sysctl_wire_old_buffer(req, 0);
9776 	if (rc != 0)
9777 		return (rc);
9778 
9779 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9780 	if (sb == NULL)
9781 		return (ENOMEM);
9782 
9783 	for (i = 0; i < nitems(mem); i++) {
9784 		mem[i].limit = 0;
9785 		mem[i].idx = i;
9786 	}
9787 
9788 	mtx_lock(&sc->reg_lock);
9789 	if (hw_off_limits(sc)) {
9790 		rc = ENXIO;
9791 		goto done;
9792 	}
9793 
9794 	/* Find and sort the populated memory ranges */
9795 	i = 0;
9796 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9797 	if (lo & F_EDRAM0_ENABLE) {
9798 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9799 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9800 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9801 		avail[i].idx = 0;
9802 		i++;
9803 	}
9804 	if (lo & F_EDRAM1_ENABLE) {
9805 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9806 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9807 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9808 		avail[i].idx = 1;
9809 		i++;
9810 	}
9811 	if (lo & F_EXT_MEM_ENABLE) {
9812 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9813 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9814 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9815 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9816 		i++;
9817 	}
9818 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9819 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9820 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9821 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9822 		avail[i].idx = 4;
9823 		i++;
9824 	}
9825 	if (is_t6(sc) && lo & F_HMA_MUX) {
9826 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9827 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9828 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9829 		avail[i].idx = 5;
9830 		i++;
9831 	}
9832 	MPASS(i <= nitems(avail));
9833 	if (!i)                                    /* no memory available */
9834 		goto done;
9835 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9836 
9837 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9838 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9839 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9840 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9841 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9842 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9843 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9844 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9845 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9846 
9847 	/* the next few have explicit upper bounds */
9848 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9849 	md->limit = md->base - 1 +
9850 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9851 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9852 	md++;
9853 
9854 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9855 	md->limit = md->base - 1 +
9856 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9857 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9858 	md++;
9859 
9860 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9861 		if (chip_id(sc) <= CHELSIO_T5)
9862 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9863 		else
9864 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9865 		md->limit = 0;
9866 	} else {
9867 		md->base = 0;
9868 		md->idx = nitems(region);  /* hide it */
9869 	}
9870 	md++;
9871 
9872 #define ulp_region(reg) \
9873 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9874 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9875 
9876 	ulp_region(RX_ISCSI);
9877 	ulp_region(RX_TDDP);
9878 	ulp_region(TX_TPT);
9879 	ulp_region(RX_STAG);
9880 	ulp_region(RX_RQ);
9881 	ulp_region(RX_RQUDP);
9882 	ulp_region(RX_PBL);
9883 	ulp_region(TX_PBL);
9884 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9885 		ulp_region(RX_TLS_KEY);
9886 	}
9887 #undef ulp_region
9888 
9889 	md->base = 0;
9890 	if (is_t4(sc))
9891 		md->idx = nitems(region);
9892 	else {
9893 		uint32_t size = 0;
9894 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9895 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9896 
9897 		if (is_t5(sc)) {
9898 			if (sge_ctrl & F_VFIFO_ENABLE)
9899 				size = fifo_size << 2;
9900 		} else
9901 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9902 
9903 		if (size) {
9904 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9905 			md->limit = md->base + size - 1;
9906 		} else
9907 			md->idx = nitems(region);
9908 	}
9909 	md++;
9910 
9911 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9912 	md->limit = 0;
9913 	md++;
9914 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9915 	md->limit = 0;
9916 	md++;
9917 
9918 	md->base = sc->vres.ocq.start;
9919 	if (sc->vres.ocq.size)
9920 		md->limit = md->base + sc->vres.ocq.size - 1;
9921 	else
9922 		md->idx = nitems(region);  /* hide it */
9923 	md++;
9924 
9925 	/* add any address-space holes, there can be up to 3 */
9926 	for (n = 0; n < i - 1; n++)
9927 		if (avail[n].limit < avail[n + 1].base)
9928 			(md++)->base = avail[n].limit;
9929 	if (avail[n].limit)
9930 		(md++)->base = avail[n].limit;
9931 
9932 	n = md - mem;
9933 	MPASS(n <= nitems(mem));
9934 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9935 
9936 	for (lo = 0; lo < i; lo++)
9937 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9938 				avail[lo].limit - 1);
9939 
9940 	sbuf_printf(sb, "\n");
9941 	for (i = 0; i < n; i++) {
9942 		if (mem[i].idx >= nitems(region))
9943 			continue;                        /* skip holes */
9944 		if (!mem[i].limit)
9945 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9946 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9947 				mem[i].limit);
9948 	}
9949 
9950 	sbuf_printf(sb, "\n");
9951 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9952 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9953 	mem_region_show(sb, "uP RAM:", lo, hi);
9954 
9955 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9956 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
9957 	mem_region_show(sb, "uP Extmem2:", lo, hi);
9958 
9959 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
9960 	for (i = 0, free = 0; i < 2; i++)
9961 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
9962 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
9963 		   G_PMRXMAXPAGE(lo), free,
9964 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
9965 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
9966 
9967 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
9968 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
9969 	for (i = 0, free = 0; i < 4; i++)
9970 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
9971 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
9972 		   G_PMTXMAXPAGE(lo), free,
9973 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
9974 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
9975 	sbuf_printf(sb, "%u p-structs (%u free)\n",
9976 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
9977 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
9978 
9979 	for (i = 0; i < 4; i++) {
9980 		if (chip_id(sc) > CHELSIO_T5)
9981 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
9982 		else
9983 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
9984 		if (is_t5(sc)) {
9985 			used = G_T5_USED(lo);
9986 			alloc = G_T5_ALLOC(lo);
9987 		} else {
9988 			used = G_USED(lo);
9989 			alloc = G_ALLOC(lo);
9990 		}
9991 		/* For T6 these are MAC buffer groups */
9992 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
9993 		    i, used, alloc);
9994 	}
9995 	for (i = 0; i < sc->chip_params->nchan; i++) {
9996 		if (chip_id(sc) > CHELSIO_T5)
9997 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
9998 		else
9999 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10000 		if (is_t5(sc)) {
10001 			used = G_T5_USED(lo);
10002 			alloc = G_T5_ALLOC(lo);
10003 		} else {
10004 			used = G_USED(lo);
10005 			alloc = G_ALLOC(lo);
10006 		}
10007 		/* For T6 these are MAC buffer groups */
10008 		sbuf_printf(sb,
10009 		    "\nLoopback %d using %u pages out of %u allocated",
10010 		    i, used, alloc);
10011 	}
10012 done:
10013 	mtx_unlock(&sc->reg_lock);
10014 	if (rc == 0)
10015 		rc = sbuf_finish(sb);
10016 	sbuf_delete(sb);
10017 	return (rc);
10018 }
10019 
10020 static inline void
10021 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10022 {
10023 	*mask = x | y;
10024 	y = htobe64(y);
10025 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10026 }
10027 
10028 static int
10029 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10030 {
10031 	struct adapter *sc = arg1;
10032 	struct sbuf *sb;
10033 	int rc, i;
10034 
10035 	MPASS(chip_id(sc) <= CHELSIO_T5);
10036 
10037 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10038 	if (sb == NULL)
10039 		return (ENOMEM);
10040 
10041 	sbuf_printf(sb,
10042 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10043 	    "  VF              Replication             P0 P1 P2 P3  ML");
10044 	rc = 0;
10045 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10046 		uint64_t tcamx, tcamy, mask;
10047 		uint32_t cls_lo, cls_hi;
10048 		uint8_t addr[ETHER_ADDR_LEN];
10049 
10050 		mtx_lock(&sc->reg_lock);
10051 		if (hw_off_limits(sc))
10052 			rc = ENXIO;
10053 		else {
10054 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10055 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10056 		}
10057 		mtx_unlock(&sc->reg_lock);
10058 		if (rc != 0)
10059 			break;
10060 		if (tcamx & tcamy)
10061 			continue;
10062 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10063 		mtx_lock(&sc->reg_lock);
10064 		if (hw_off_limits(sc))
10065 			rc = ENXIO;
10066 		else {
10067 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10068 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10069 		}
10070 		mtx_unlock(&sc->reg_lock);
10071 		if (rc != 0)
10072 			break;
10073 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10074 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10075 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10076 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10077 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10078 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10079 
10080 		if (cls_lo & F_REPLICATE) {
10081 			struct fw_ldst_cmd ldst_cmd;
10082 
10083 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10084 			ldst_cmd.op_to_addrspace =
10085 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10086 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10087 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10088 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10089 			ldst_cmd.u.mps.rplc.fid_idx =
10090 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10091 				V_FW_LDST_CMD_IDX(i));
10092 
10093 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10094 			    "t4mps");
10095 			if (rc)
10096 				break;
10097 			if (hw_off_limits(sc))
10098 				rc = ENXIO;
10099 			else
10100 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10101 				    sizeof(ldst_cmd), &ldst_cmd);
10102 			end_synchronized_op(sc, 0);
10103 			if (rc != 0)
10104 				break;
10105 			else {
10106 				sbuf_printf(sb, " %08x %08x %08x %08x",
10107 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10108 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10109 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10110 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10111 			}
10112 		} else
10113 			sbuf_printf(sb, "%36s", "");
10114 
10115 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10116 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10117 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10118 	}
10119 
10120 	if (rc)
10121 		(void) sbuf_finish(sb);
10122 	else
10123 		rc = sbuf_finish(sb);
10124 	sbuf_delete(sb);
10125 
10126 	return (rc);
10127 }
10128 
10129 static int
10130 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10131 {
10132 	struct adapter *sc = arg1;
10133 	struct sbuf *sb;
10134 	int rc, i;
10135 
10136 	MPASS(chip_id(sc) > CHELSIO_T5);
10137 
10138 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10139 	if (sb == NULL)
10140 		return (ENOMEM);
10141 
10142 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10143 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10144 	    "                           Replication"
10145 	    "                                    P0 P1 P2 P3  ML\n");
10146 
10147 	rc = 0;
10148 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10149 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10150 		uint16_t ivlan;
10151 		uint64_t tcamx, tcamy, val, mask;
10152 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10153 		uint8_t addr[ETHER_ADDR_LEN];
10154 
10155 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10156 		if (i < 256)
10157 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10158 		else
10159 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10160 		mtx_lock(&sc->reg_lock);
10161 		if (hw_off_limits(sc))
10162 			rc = ENXIO;
10163 		else {
10164 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10165 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10166 			tcamy = G_DMACH(val) << 32;
10167 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10168 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10169 		}
10170 		mtx_unlock(&sc->reg_lock);
10171 		if (rc != 0)
10172 			break;
10173 
10174 		lookup_type = G_DATALKPTYPE(data2);
10175 		port_num = G_DATAPORTNUM(data2);
10176 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10177 			/* Inner header VNI */
10178 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10179 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10180 			dip_hit = data2 & F_DATADIPHIT;
10181 			vlan_vld = 0;
10182 		} else {
10183 			vniy = 0;
10184 			dip_hit = 0;
10185 			vlan_vld = data2 & F_DATAVIDH2;
10186 			ivlan = G_VIDL(val);
10187 		}
10188 
10189 		ctl |= V_CTLXYBITSEL(1);
10190 		mtx_lock(&sc->reg_lock);
10191 		if (hw_off_limits(sc))
10192 			rc = ENXIO;
10193 		else {
10194 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10195 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10196 			tcamx = G_DMACH(val) << 32;
10197 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10198 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10199 		}
10200 		mtx_unlock(&sc->reg_lock);
10201 		if (rc != 0)
10202 			break;
10203 
10204 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10205 			/* Inner header VNI mask */
10206 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10207 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10208 		} else
10209 			vnix = 0;
10210 
10211 		if (tcamx & tcamy)
10212 			continue;
10213 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10214 
10215 		mtx_lock(&sc->reg_lock);
10216 		if (hw_off_limits(sc))
10217 			rc = ENXIO;
10218 		else {
10219 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10220 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10221 		}
10222 		mtx_unlock(&sc->reg_lock);
10223 		if (rc != 0)
10224 			break;
10225 
10226 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10227 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10228 			    "%012jx %06x %06x    -    -   %3c"
10229 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10230 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10231 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10232 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10233 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10234 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10235 		} else {
10236 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10237 			    "%012jx    -       -   ", i, addr[0], addr[1],
10238 			    addr[2], addr[3], addr[4], addr[5],
10239 			    (uintmax_t)mask);
10240 
10241 			if (vlan_vld)
10242 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10243 			else
10244 				sbuf_printf(sb, "  -    N     ");
10245 
10246 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10247 			    lookup_type ? 'I' : 'O', port_num,
10248 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10249 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10250 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10251 		}
10252 
10253 
10254 		if (cls_lo & F_T6_REPLICATE) {
10255 			struct fw_ldst_cmd ldst_cmd;
10256 
10257 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10258 			ldst_cmd.op_to_addrspace =
10259 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10260 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10261 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10262 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10263 			ldst_cmd.u.mps.rplc.fid_idx =
10264 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10265 				V_FW_LDST_CMD_IDX(i));
10266 
10267 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10268 			    "t6mps");
10269 			if (rc)
10270 				break;
10271 			if (hw_off_limits(sc))
10272 				rc = ENXIO;
10273 			else
10274 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10275 				    sizeof(ldst_cmd), &ldst_cmd);
10276 			end_synchronized_op(sc, 0);
10277 			if (rc != 0)
10278 				break;
10279 			else {
10280 				sbuf_printf(sb, " %08x %08x %08x %08x"
10281 				    " %08x %08x %08x %08x",
10282 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10283 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10284 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10285 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10286 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10287 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10288 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10289 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10290 			}
10291 		} else
10292 			sbuf_printf(sb, "%72s", "");
10293 
10294 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10295 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10296 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10297 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10298 	}
10299 
10300 	if (rc)
10301 		(void) sbuf_finish(sb);
10302 	else
10303 		rc = sbuf_finish(sb);
10304 	sbuf_delete(sb);
10305 
10306 	return (rc);
10307 }
10308 
10309 static int
10310 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10311 {
10312 	struct adapter *sc = arg1;
10313 	struct sbuf *sb;
10314 	int rc;
10315 	uint16_t mtus[NMTUS];
10316 
10317 	rc = 0;
10318 	mtx_lock(&sc->reg_lock);
10319 	if (hw_off_limits(sc))
10320 		rc = ENXIO;
10321 	else
10322 		t4_read_mtu_tbl(sc, mtus, NULL);
10323 	mtx_unlock(&sc->reg_lock);
10324 	if (rc != 0)
10325 		return (rc);
10326 
10327 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10328 	if (sb == NULL)
10329 		return (ENOMEM);
10330 
10331 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10332 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10333 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10334 	    mtus[14], mtus[15]);
10335 
10336 	rc = sbuf_finish(sb);
10337 	sbuf_delete(sb);
10338 
10339 	return (rc);
10340 }
10341 
10342 static int
10343 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10344 {
10345 	struct adapter *sc = arg1;
10346 	struct sbuf *sb;
10347 	int rc, i;
10348 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10349 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10350 	static const char *tx_stats[MAX_PM_NSTATS] = {
10351 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10352 		"Tx FIFO wait", NULL, "Tx latency"
10353 	};
10354 	static const char *rx_stats[MAX_PM_NSTATS] = {
10355 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10356 		"Rx FIFO wait", NULL, "Rx latency"
10357 	};
10358 
10359 	rc = 0;
10360 	mtx_lock(&sc->reg_lock);
10361 	if (hw_off_limits(sc))
10362 		rc = ENXIO;
10363 	else {
10364 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10365 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10366 	}
10367 	mtx_unlock(&sc->reg_lock);
10368 	if (rc != 0)
10369 		return (rc);
10370 
10371 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10372 	if (sb == NULL)
10373 		return (ENOMEM);
10374 
10375 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10376 	for (i = 0; i < 4; i++) {
10377 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10378 		    tx_cyc[i]);
10379 	}
10380 
10381 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10382 	for (i = 0; i < 4; i++) {
10383 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10384 		    rx_cyc[i]);
10385 	}
10386 
10387 	if (chip_id(sc) > CHELSIO_T5) {
10388 		sbuf_printf(sb,
10389 		    "\n              Total wait      Total occupancy");
10390 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10391 		    tx_cyc[i]);
10392 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10393 		    rx_cyc[i]);
10394 
10395 		i += 2;
10396 		MPASS(i < nitems(tx_stats));
10397 
10398 		sbuf_printf(sb,
10399 		    "\n                   Reads           Total wait");
10400 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10401 		    tx_cyc[i]);
10402 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10403 		    rx_cyc[i]);
10404 	}
10405 
10406 	rc = sbuf_finish(sb);
10407 	sbuf_delete(sb);
10408 
10409 	return (rc);
10410 }
10411 
10412 static int
10413 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10414 {
10415 	struct adapter *sc = arg1;
10416 	struct sbuf *sb;
10417 	int rc;
10418 	struct tp_rdma_stats stats;
10419 
10420 	rc = 0;
10421 	mtx_lock(&sc->reg_lock);
10422 	if (hw_off_limits(sc))
10423 		rc = ENXIO;
10424 	else
10425 		t4_tp_get_rdma_stats(sc, &stats, 0);
10426 	mtx_unlock(&sc->reg_lock);
10427 	if (rc != 0)
10428 		return (rc);
10429 
10430 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10431 	if (sb == NULL)
10432 		return (ENOMEM);
10433 
10434 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10435 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10436 
10437 	rc = sbuf_finish(sb);
10438 	sbuf_delete(sb);
10439 
10440 	return (rc);
10441 }
10442 
10443 static int
10444 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10445 {
10446 	struct adapter *sc = arg1;
10447 	struct sbuf *sb;
10448 	int rc;
10449 	struct tp_tcp_stats v4, v6;
10450 
10451 	rc = 0;
10452 	mtx_lock(&sc->reg_lock);
10453 	if (hw_off_limits(sc))
10454 		rc = ENXIO;
10455 	else
10456 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10457 	mtx_unlock(&sc->reg_lock);
10458 	if (rc != 0)
10459 		return (rc);
10460 
10461 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10462 	if (sb == NULL)
10463 		return (ENOMEM);
10464 
10465 	sbuf_printf(sb,
10466 	    "                                IP                 IPv6\n");
10467 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10468 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10469 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10470 	    v4.tcp_in_segs, v6.tcp_in_segs);
10471 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10472 	    v4.tcp_out_segs, v6.tcp_out_segs);
10473 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10474 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10475 
10476 	rc = sbuf_finish(sb);
10477 	sbuf_delete(sb);
10478 
10479 	return (rc);
10480 }
10481 
10482 static int
10483 sysctl_tids(SYSCTL_HANDLER_ARGS)
10484 {
10485 	struct adapter *sc = arg1;
10486 	struct sbuf *sb;
10487 	int rc;
10488 	uint32_t x, y;
10489 	struct tid_info *t = &sc->tids;
10490 
10491 	rc = 0;
10492 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10493 	if (sb == NULL)
10494 		return (ENOMEM);
10495 
10496 	if (t->natids) {
10497 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10498 		    t->atids_in_use);
10499 	}
10500 
10501 	if (t->nhpftids) {
10502 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10503 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10504 	}
10505 
10506 	if (t->ntids) {
10507 		bool hashen = false;
10508 
10509 		mtx_lock(&sc->reg_lock);
10510 		if (hw_off_limits(sc))
10511 			rc = ENXIO;
10512 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10513 			hashen = true;
10514 			if (chip_id(sc) <= CHELSIO_T5) {
10515 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10516 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10517 			} else {
10518 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10519 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10520 			}
10521 		}
10522 		mtx_unlock(&sc->reg_lock);
10523 		if (rc != 0)
10524 			goto done;
10525 
10526 		sbuf_printf(sb, "TID range: ");
10527 		if (hashen) {
10528 			if (x)
10529 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10530 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10531 		} else {
10532 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10533 			    t->ntids - 1);
10534 		}
10535 		sbuf_printf(sb, ", in use: %u\n",
10536 		    atomic_load_acq_int(&t->tids_in_use));
10537 	}
10538 
10539 	if (t->nstids) {
10540 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10541 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10542 	}
10543 
10544 	if (t->nftids) {
10545 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10546 		    t->ftid_end, t->ftids_in_use);
10547 	}
10548 
10549 	if (t->netids) {
10550 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10551 		    t->etid_base + t->netids - 1, t->etids_in_use);
10552 	}
10553 
10554 	mtx_lock(&sc->reg_lock);
10555 	if (hw_off_limits(sc))
10556 		rc = ENXIO;
10557 	else {
10558 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10559 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10560 	}
10561 	mtx_unlock(&sc->reg_lock);
10562 	if (rc != 0)
10563 		goto done;
10564 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10565 done:
10566 	if (rc == 0)
10567 		rc = sbuf_finish(sb);
10568 	else
10569 		(void)sbuf_finish(sb);
10570 	sbuf_delete(sb);
10571 
10572 	return (rc);
10573 }
10574 
10575 static int
10576 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10577 {
10578 	struct adapter *sc = arg1;
10579 	struct sbuf *sb;
10580 	int rc;
10581 	struct tp_err_stats stats;
10582 
10583 	rc = 0;
10584 	mtx_lock(&sc->reg_lock);
10585 	if (hw_off_limits(sc))
10586 		rc = ENXIO;
10587 	else
10588 		t4_tp_get_err_stats(sc, &stats, 0);
10589 	mtx_unlock(&sc->reg_lock);
10590 	if (rc != 0)
10591 		return (rc);
10592 
10593 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10594 	if (sb == NULL)
10595 		return (ENOMEM);
10596 
10597 	if (sc->chip_params->nchan > 2) {
10598 		sbuf_printf(sb, "                 channel 0  channel 1"
10599 		    "  channel 2  channel 3\n");
10600 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10601 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10602 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10603 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10604 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10605 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10606 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10607 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10608 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10609 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10610 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10611 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10612 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10613 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10614 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10615 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10616 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10617 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10618 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10619 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10620 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10621 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10622 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10623 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10624 	} else {
10625 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10626 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10627 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10628 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10629 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10630 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10631 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10632 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10633 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10634 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10635 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10636 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10637 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10638 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10639 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10640 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10641 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10642 	}
10643 
10644 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10645 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10646 
10647 	rc = sbuf_finish(sb);
10648 	sbuf_delete(sb);
10649 
10650 	return (rc);
10651 }
10652 
10653 static int
10654 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10655 {
10656 	struct adapter *sc = arg1;
10657 	struct sbuf *sb;
10658 	int rc;
10659 	struct tp_tnl_stats stats;
10660 
10661 	rc = 0;
10662 	mtx_lock(&sc->reg_lock);
10663 	if (hw_off_limits(sc))
10664 		rc = ENXIO;
10665 	else
10666 		t4_tp_get_tnl_stats(sc, &stats, 1);
10667 	mtx_unlock(&sc->reg_lock);
10668 	if (rc != 0)
10669 		return (rc);
10670 
10671 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10672 	if (sb == NULL)
10673 		return (ENOMEM);
10674 
10675 	if (sc->chip_params->nchan > 2) {
10676 		sbuf_printf(sb, "           channel 0  channel 1"
10677 		    "  channel 2  channel 3\n");
10678 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10679 		    stats.out_pkt[0], stats.out_pkt[1],
10680 		    stats.out_pkt[2], stats.out_pkt[3]);
10681 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10682 		    stats.in_pkt[0], stats.in_pkt[1],
10683 		    stats.in_pkt[2], stats.in_pkt[3]);
10684 	} else {
10685 		sbuf_printf(sb, "           channel 0  channel 1\n");
10686 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10687 		    stats.out_pkt[0], stats.out_pkt[1]);
10688 		sbuf_printf(sb, "InPkts:   %10u %10u",
10689 		    stats.in_pkt[0], stats.in_pkt[1]);
10690 	}
10691 
10692 	rc = sbuf_finish(sb);
10693 	sbuf_delete(sb);
10694 
10695 	return (rc);
10696 }
10697 
10698 static int
10699 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10700 {
10701 	struct adapter *sc = arg1;
10702 	struct tp_params *tpp = &sc->params.tp;
10703 	u_int mask;
10704 	int rc;
10705 
10706 	mask = tpp->la_mask >> 16;
10707 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10708 	if (rc != 0 || req->newptr == NULL)
10709 		return (rc);
10710 	if (mask > 0xffff)
10711 		return (EINVAL);
10712 	mtx_lock(&sc->reg_lock);
10713 	if (hw_off_limits(sc))
10714 		rc = ENXIO;
10715 	else {
10716 		tpp->la_mask = mask << 16;
10717 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10718 		    tpp->la_mask);
10719 	}
10720 	mtx_unlock(&sc->reg_lock);
10721 
10722 	return (rc);
10723 }
10724 
10725 struct field_desc {
10726 	const char *name;
10727 	u_int start;
10728 	u_int width;
10729 };
10730 
10731 static void
10732 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10733 {
10734 	char buf[32];
10735 	int line_size = 0;
10736 
10737 	while (f->name) {
10738 		uint64_t mask = (1ULL << f->width) - 1;
10739 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10740 		    ((uintmax_t)v >> f->start) & mask);
10741 
10742 		if (line_size + len >= 79) {
10743 			line_size = 8;
10744 			sbuf_printf(sb, "\n        ");
10745 		}
10746 		sbuf_printf(sb, "%s ", buf);
10747 		line_size += len + 1;
10748 		f++;
10749 	}
10750 	sbuf_printf(sb, "\n");
10751 }
10752 
10753 static const struct field_desc tp_la0[] = {
10754 	{ "RcfOpCodeOut", 60, 4 },
10755 	{ "State", 56, 4 },
10756 	{ "WcfState", 52, 4 },
10757 	{ "RcfOpcSrcOut", 50, 2 },
10758 	{ "CRxError", 49, 1 },
10759 	{ "ERxError", 48, 1 },
10760 	{ "SanityFailed", 47, 1 },
10761 	{ "SpuriousMsg", 46, 1 },
10762 	{ "FlushInputMsg", 45, 1 },
10763 	{ "FlushInputCpl", 44, 1 },
10764 	{ "RssUpBit", 43, 1 },
10765 	{ "RssFilterHit", 42, 1 },
10766 	{ "Tid", 32, 10 },
10767 	{ "InitTcb", 31, 1 },
10768 	{ "LineNumber", 24, 7 },
10769 	{ "Emsg", 23, 1 },
10770 	{ "EdataOut", 22, 1 },
10771 	{ "Cmsg", 21, 1 },
10772 	{ "CdataOut", 20, 1 },
10773 	{ "EreadPdu", 19, 1 },
10774 	{ "CreadPdu", 18, 1 },
10775 	{ "TunnelPkt", 17, 1 },
10776 	{ "RcfPeerFin", 16, 1 },
10777 	{ "RcfReasonOut", 12, 4 },
10778 	{ "TxCchannel", 10, 2 },
10779 	{ "RcfTxChannel", 8, 2 },
10780 	{ "RxEchannel", 6, 2 },
10781 	{ "RcfRxChannel", 5, 1 },
10782 	{ "RcfDataOutSrdy", 4, 1 },
10783 	{ "RxDvld", 3, 1 },
10784 	{ "RxOoDvld", 2, 1 },
10785 	{ "RxCongestion", 1, 1 },
10786 	{ "TxCongestion", 0, 1 },
10787 	{ NULL }
10788 };
10789 
10790 static const struct field_desc tp_la1[] = {
10791 	{ "CplCmdIn", 56, 8 },
10792 	{ "CplCmdOut", 48, 8 },
10793 	{ "ESynOut", 47, 1 },
10794 	{ "EAckOut", 46, 1 },
10795 	{ "EFinOut", 45, 1 },
10796 	{ "ERstOut", 44, 1 },
10797 	{ "SynIn", 43, 1 },
10798 	{ "AckIn", 42, 1 },
10799 	{ "FinIn", 41, 1 },
10800 	{ "RstIn", 40, 1 },
10801 	{ "DataIn", 39, 1 },
10802 	{ "DataInVld", 38, 1 },
10803 	{ "PadIn", 37, 1 },
10804 	{ "RxBufEmpty", 36, 1 },
10805 	{ "RxDdp", 35, 1 },
10806 	{ "RxFbCongestion", 34, 1 },
10807 	{ "TxFbCongestion", 33, 1 },
10808 	{ "TxPktSumSrdy", 32, 1 },
10809 	{ "RcfUlpType", 28, 4 },
10810 	{ "Eread", 27, 1 },
10811 	{ "Ebypass", 26, 1 },
10812 	{ "Esave", 25, 1 },
10813 	{ "Static0", 24, 1 },
10814 	{ "Cread", 23, 1 },
10815 	{ "Cbypass", 22, 1 },
10816 	{ "Csave", 21, 1 },
10817 	{ "CPktOut", 20, 1 },
10818 	{ "RxPagePoolFull", 18, 2 },
10819 	{ "RxLpbkPkt", 17, 1 },
10820 	{ "TxLpbkPkt", 16, 1 },
10821 	{ "RxVfValid", 15, 1 },
10822 	{ "SynLearned", 14, 1 },
10823 	{ "SetDelEntry", 13, 1 },
10824 	{ "SetInvEntry", 12, 1 },
10825 	{ "CpcmdDvld", 11, 1 },
10826 	{ "CpcmdSave", 10, 1 },
10827 	{ "RxPstructsFull", 8, 2 },
10828 	{ "EpcmdDvld", 7, 1 },
10829 	{ "EpcmdFlush", 6, 1 },
10830 	{ "EpcmdTrimPrefix", 5, 1 },
10831 	{ "EpcmdTrimPostfix", 4, 1 },
10832 	{ "ERssIp4Pkt", 3, 1 },
10833 	{ "ERssIp6Pkt", 2, 1 },
10834 	{ "ERssTcpUdpPkt", 1, 1 },
10835 	{ "ERssFceFipPkt", 0, 1 },
10836 	{ NULL }
10837 };
10838 
10839 static const struct field_desc tp_la2[] = {
10840 	{ "CplCmdIn", 56, 8 },
10841 	{ "MpsVfVld", 55, 1 },
10842 	{ "MpsPf", 52, 3 },
10843 	{ "MpsVf", 44, 8 },
10844 	{ "SynIn", 43, 1 },
10845 	{ "AckIn", 42, 1 },
10846 	{ "FinIn", 41, 1 },
10847 	{ "RstIn", 40, 1 },
10848 	{ "DataIn", 39, 1 },
10849 	{ "DataInVld", 38, 1 },
10850 	{ "PadIn", 37, 1 },
10851 	{ "RxBufEmpty", 36, 1 },
10852 	{ "RxDdp", 35, 1 },
10853 	{ "RxFbCongestion", 34, 1 },
10854 	{ "TxFbCongestion", 33, 1 },
10855 	{ "TxPktSumSrdy", 32, 1 },
10856 	{ "RcfUlpType", 28, 4 },
10857 	{ "Eread", 27, 1 },
10858 	{ "Ebypass", 26, 1 },
10859 	{ "Esave", 25, 1 },
10860 	{ "Static0", 24, 1 },
10861 	{ "Cread", 23, 1 },
10862 	{ "Cbypass", 22, 1 },
10863 	{ "Csave", 21, 1 },
10864 	{ "CPktOut", 20, 1 },
10865 	{ "RxPagePoolFull", 18, 2 },
10866 	{ "RxLpbkPkt", 17, 1 },
10867 	{ "TxLpbkPkt", 16, 1 },
10868 	{ "RxVfValid", 15, 1 },
10869 	{ "SynLearned", 14, 1 },
10870 	{ "SetDelEntry", 13, 1 },
10871 	{ "SetInvEntry", 12, 1 },
10872 	{ "CpcmdDvld", 11, 1 },
10873 	{ "CpcmdSave", 10, 1 },
10874 	{ "RxPstructsFull", 8, 2 },
10875 	{ "EpcmdDvld", 7, 1 },
10876 	{ "EpcmdFlush", 6, 1 },
10877 	{ "EpcmdTrimPrefix", 5, 1 },
10878 	{ "EpcmdTrimPostfix", 4, 1 },
10879 	{ "ERssIp4Pkt", 3, 1 },
10880 	{ "ERssIp6Pkt", 2, 1 },
10881 	{ "ERssTcpUdpPkt", 1, 1 },
10882 	{ "ERssFceFipPkt", 0, 1 },
10883 	{ NULL }
10884 };
10885 
10886 static void
10887 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10888 {
10889 
10890 	field_desc_show(sb, *p, tp_la0);
10891 }
10892 
10893 static void
10894 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10895 {
10896 
10897 	if (idx)
10898 		sbuf_printf(sb, "\n");
10899 	field_desc_show(sb, p[0], tp_la0);
10900 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10901 		field_desc_show(sb, p[1], tp_la0);
10902 }
10903 
10904 static void
10905 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10906 {
10907 
10908 	if (idx)
10909 		sbuf_printf(sb, "\n");
10910 	field_desc_show(sb, p[0], tp_la0);
10911 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10912 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10913 }
10914 
10915 static int
10916 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10917 {
10918 	struct adapter *sc = arg1;
10919 	struct sbuf *sb;
10920 	uint64_t *buf, *p;
10921 	int rc;
10922 	u_int i, inc;
10923 	void (*show_func)(struct sbuf *, uint64_t *, int);
10924 
10925 	rc = 0;
10926 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10927 	if (sb == NULL)
10928 		return (ENOMEM);
10929 
10930 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10931 
10932 	mtx_lock(&sc->reg_lock);
10933 	if (hw_off_limits(sc))
10934 		rc = ENXIO;
10935 	else {
10936 		t4_tp_read_la(sc, buf, NULL);
10937 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10938 		case 2:
10939 			inc = 2;
10940 			show_func = tp_la_show2;
10941 			break;
10942 		case 3:
10943 			inc = 2;
10944 			show_func = tp_la_show3;
10945 			break;
10946 		default:
10947 			inc = 1;
10948 			show_func = tp_la_show;
10949 		}
10950 	}
10951 	mtx_unlock(&sc->reg_lock);
10952 	if (rc != 0)
10953 		goto done;
10954 
10955 	p = buf;
10956 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
10957 		(*show_func)(sb, p, i);
10958 	rc = sbuf_finish(sb);
10959 done:
10960 	sbuf_delete(sb);
10961 	free(buf, M_CXGBE);
10962 	return (rc);
10963 }
10964 
10965 static int
10966 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
10967 {
10968 	struct adapter *sc = arg1;
10969 	struct sbuf *sb;
10970 	int rc;
10971 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
10972 
10973 	rc = 0;
10974 	mtx_lock(&sc->reg_lock);
10975 	if (hw_off_limits(sc))
10976 		rc = ENXIO;
10977 	else
10978 		t4_get_chan_txrate(sc, nrate, orate);
10979 	mtx_unlock(&sc->reg_lock);
10980 	if (rc != 0)
10981 		return (rc);
10982 
10983 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10984 	if (sb == NULL)
10985 		return (ENOMEM);
10986 
10987 	if (sc->chip_params->nchan > 2) {
10988 		sbuf_printf(sb, "              channel 0   channel 1"
10989 		    "   channel 2   channel 3\n");
10990 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
10991 		    nrate[0], nrate[1], nrate[2], nrate[3]);
10992 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
10993 		    orate[0], orate[1], orate[2], orate[3]);
10994 	} else {
10995 		sbuf_printf(sb, "              channel 0   channel 1\n");
10996 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
10997 		    nrate[0], nrate[1]);
10998 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
10999 		    orate[0], orate[1]);
11000 	}
11001 
11002 	rc = sbuf_finish(sb);
11003 	sbuf_delete(sb);
11004 
11005 	return (rc);
11006 }
11007 
11008 static int
11009 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11010 {
11011 	struct adapter *sc = arg1;
11012 	struct sbuf *sb;
11013 	uint32_t *buf, *p;
11014 	int rc, i;
11015 
11016 	rc = 0;
11017 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11018 	if (sb == NULL)
11019 		return (ENOMEM);
11020 
11021 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11022 	    M_ZERO | M_WAITOK);
11023 
11024 	mtx_lock(&sc->reg_lock);
11025 	if (hw_off_limits(sc))
11026 		rc = ENXIO;
11027 	else
11028 		t4_ulprx_read_la(sc, buf);
11029 	mtx_unlock(&sc->reg_lock);
11030 	if (rc != 0)
11031 		goto done;
11032 
11033 	p = buf;
11034 	sbuf_printf(sb, "      Pcmd        Type   Message"
11035 	    "                Data");
11036 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11037 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11038 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11039 	}
11040 	rc = sbuf_finish(sb);
11041 done:
11042 	sbuf_delete(sb);
11043 	free(buf, M_CXGBE);
11044 	return (rc);
11045 }
11046 
11047 static int
11048 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11049 {
11050 	struct adapter *sc = arg1;
11051 	struct sbuf *sb;
11052 	int rc;
11053 	uint32_t cfg, s1, s2;
11054 
11055 	MPASS(chip_id(sc) >= CHELSIO_T5);
11056 
11057 	rc = 0;
11058 	mtx_lock(&sc->reg_lock);
11059 	if (hw_off_limits(sc))
11060 		rc = ENXIO;
11061 	else {
11062 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11063 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11064 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11065 	}
11066 	mtx_unlock(&sc->reg_lock);
11067 	if (rc != 0)
11068 		return (rc);
11069 
11070 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11071 	if (sb == NULL)
11072 		return (ENOMEM);
11073 
11074 	if (G_STATSOURCE_T5(cfg) == 7) {
11075 		int mode;
11076 
11077 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11078 		if (mode == 0)
11079 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11080 		else if (mode == 1)
11081 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11082 		else
11083 			sbuf_printf(sb, "unknown mode %d", mode);
11084 	}
11085 	rc = sbuf_finish(sb);
11086 	sbuf_delete(sb);
11087 
11088 	return (rc);
11089 }
11090 
11091 static int
11092 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11093 {
11094 	struct adapter *sc = arg1;
11095 	enum cpu_sets op = arg2;
11096 	cpuset_t cpuset;
11097 	struct sbuf *sb;
11098 	int i, rc;
11099 
11100 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11101 
11102 	CPU_ZERO(&cpuset);
11103 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11104 	if (rc != 0)
11105 		return (rc);
11106 
11107 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11108 	if (sb == NULL)
11109 		return (ENOMEM);
11110 
11111 	CPU_FOREACH(i)
11112 		sbuf_printf(sb, "%d ", i);
11113 	rc = sbuf_finish(sb);
11114 	sbuf_delete(sb);
11115 
11116 	return (rc);
11117 }
11118 
11119 static int
11120 sysctl_reset(SYSCTL_HANDLER_ARGS)
11121 {
11122 	struct adapter *sc = arg1;
11123 	u_int val;
11124 	int rc;
11125 
11126 	val = atomic_load_int(&sc->num_resets);
11127 	rc = sysctl_handle_int(oidp, &val, 0, req);
11128 	if (rc != 0 || req->newptr == NULL)
11129 		return (rc);
11130 
11131 	if (val == 0) {
11132 		/* Zero out the counter that tracks reset. */
11133 		atomic_store_int(&sc->num_resets, 0);
11134 		return (0);
11135 	}
11136 
11137 	if (val != 1)
11138 		return (EINVAL);	/* 0 or 1 are the only legal values */
11139 
11140 	if (hw_off_limits(sc))		/* harmless race */
11141 		return (EALREADY);
11142 
11143 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11144 	return (0);
11145 }
11146 
11147 #ifdef TCP_OFFLOAD
11148 static int
11149 sysctl_tls(SYSCTL_HANDLER_ARGS)
11150 {
11151 	struct adapter *sc = arg1;
11152 	int i, j, v, rc;
11153 	struct vi_info *vi;
11154 
11155 	v = sc->tt.tls;
11156 	rc = sysctl_handle_int(oidp, &v, 0, req);
11157 	if (rc != 0 || req->newptr == NULL)
11158 		return (rc);
11159 
11160 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11161 		return (ENOTSUP);
11162 
11163 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11164 	if (rc)
11165 		return (rc);
11166 	if (hw_off_limits(sc))
11167 		rc = ENXIO;
11168 	else {
11169 		sc->tt.tls = !!v;
11170 		for_each_port(sc, i) {
11171 			for_each_vi(sc->port[i], j, vi) {
11172 				if (vi->flags & VI_INIT_DONE)
11173 					t4_update_fl_bufsize(vi->ifp);
11174 			}
11175 		}
11176 	}
11177 	end_synchronized_op(sc, 0);
11178 
11179 	return (rc);
11180 
11181 }
11182 
11183 static void
11184 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11185 {
11186 	u_int rem = val % factor;
11187 
11188 	if (rem == 0)
11189 		snprintf(buf, len, "%u", val / factor);
11190 	else {
11191 		while (rem % 10 == 0)
11192 			rem /= 10;
11193 		snprintf(buf, len, "%u.%u", val / factor, rem);
11194 	}
11195 }
11196 
11197 static int
11198 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11199 {
11200 	struct adapter *sc = arg1;
11201 	char buf[16];
11202 	u_int res, re;
11203 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11204 
11205 	mtx_lock(&sc->reg_lock);
11206 	if (hw_off_limits(sc))
11207 		res = (u_int)-1;
11208 	else
11209 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11210 	mtx_unlock(&sc->reg_lock);
11211 	if (res == (u_int)-1)
11212 		return (ENXIO);
11213 
11214 	switch (arg2) {
11215 	case 0:
11216 		/* timer_tick */
11217 		re = G_TIMERRESOLUTION(res);
11218 		break;
11219 	case 1:
11220 		/* TCP timestamp tick */
11221 		re = G_TIMESTAMPRESOLUTION(res);
11222 		break;
11223 	case 2:
11224 		/* DACK tick */
11225 		re = G_DELAYEDACKRESOLUTION(res);
11226 		break;
11227 	default:
11228 		return (EDOOFUS);
11229 	}
11230 
11231 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11232 
11233 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11234 }
11235 
11236 static int
11237 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11238 {
11239 	struct adapter *sc = arg1;
11240 	int rc;
11241 	u_int dack_tmr, dack_re, v;
11242 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11243 
11244 	mtx_lock(&sc->reg_lock);
11245 	if (hw_off_limits(sc))
11246 		rc = ENXIO;
11247 	else {
11248 		rc = 0;
11249 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11250 		    A_TP_TIMER_RESOLUTION));
11251 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11252 	}
11253 	mtx_unlock(&sc->reg_lock);
11254 	if (rc != 0)
11255 		return (rc);
11256 
11257 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11258 
11259 	return (sysctl_handle_int(oidp, &v, 0, req));
11260 }
11261 
11262 static int
11263 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11264 {
11265 	struct adapter *sc = arg1;
11266 	int rc, reg = arg2;
11267 	u_int tre;
11268 	u_long tp_tick_us, v;
11269 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11270 
11271 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11272 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11273 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11274 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11275 
11276 	mtx_lock(&sc->reg_lock);
11277 	if (hw_off_limits(sc))
11278 		rc = ENXIO;
11279 	else {
11280 		rc = 0;
11281 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11282 		tp_tick_us = (cclk_ps << tre) / 1000000;
11283 		if (reg == A_TP_INIT_SRTT)
11284 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11285 		else
11286 			v = tp_tick_us * t4_read_reg(sc, reg);
11287 	}
11288 	mtx_unlock(&sc->reg_lock);
11289 	if (rc != 0)
11290 		return (rc);
11291 	else
11292 		return (sysctl_handle_long(oidp, &v, 0, req));
11293 }
11294 
11295 /*
11296  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11297  * passed to this function.
11298  */
11299 static int
11300 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11301 {
11302 	struct adapter *sc = arg1;
11303 	int rc, idx = arg2;
11304 	u_int v;
11305 
11306 	MPASS(idx >= 0 && idx <= 24);
11307 
11308 	mtx_lock(&sc->reg_lock);
11309 	if (hw_off_limits(sc))
11310 		rc = ENXIO;
11311 	else {
11312 		rc = 0;
11313 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11314 	}
11315 	mtx_unlock(&sc->reg_lock);
11316 	if (rc != 0)
11317 		return (rc);
11318 	else
11319 		return (sysctl_handle_int(oidp, &v, 0, req));
11320 }
11321 
11322 static int
11323 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11324 {
11325 	struct adapter *sc = arg1;
11326 	int rc, idx = arg2;
11327 	u_int shift, v, r;
11328 
11329 	MPASS(idx >= 0 && idx < 16);
11330 
11331 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11332 	shift = (idx & 3) << 3;
11333 	mtx_lock(&sc->reg_lock);
11334 	if (hw_off_limits(sc))
11335 		rc = ENXIO;
11336 	else {
11337 		rc = 0;
11338 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11339 	}
11340 	mtx_unlock(&sc->reg_lock);
11341 	if (rc != 0)
11342 		return (rc);
11343 	else
11344 		return (sysctl_handle_int(oidp, &v, 0, req));
11345 }
11346 
11347 static int
11348 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11349 {
11350 	struct vi_info *vi = arg1;
11351 	struct adapter *sc = vi->adapter;
11352 	int idx, rc, i;
11353 	struct sge_ofld_rxq *ofld_rxq;
11354 	uint8_t v;
11355 
11356 	idx = vi->ofld_tmr_idx;
11357 
11358 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11359 	if (rc != 0 || req->newptr == NULL)
11360 		return (rc);
11361 
11362 	if (idx < 0 || idx >= SGE_NTIMERS)
11363 		return (EINVAL);
11364 
11365 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11366 	    "t4otmr");
11367 	if (rc)
11368 		return (rc);
11369 
11370 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11371 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11372 #ifdef atomic_store_rel_8
11373 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11374 #else
11375 		ofld_rxq->iq.intr_params = v;
11376 #endif
11377 	}
11378 	vi->ofld_tmr_idx = idx;
11379 
11380 	end_synchronized_op(sc, LOCK_HELD);
11381 	return (0);
11382 }
11383 
11384 static int
11385 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11386 {
11387 	struct vi_info *vi = arg1;
11388 	struct adapter *sc = vi->adapter;
11389 	int idx, rc;
11390 
11391 	idx = vi->ofld_pktc_idx;
11392 
11393 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11394 	if (rc != 0 || req->newptr == NULL)
11395 		return (rc);
11396 
11397 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11398 		return (EINVAL);
11399 
11400 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11401 	    "t4opktc");
11402 	if (rc)
11403 		return (rc);
11404 
11405 	if (vi->flags & VI_INIT_DONE)
11406 		rc = EBUSY; /* cannot be changed once the queues are created */
11407 	else
11408 		vi->ofld_pktc_idx = idx;
11409 
11410 	end_synchronized_op(sc, LOCK_HELD);
11411 	return (rc);
11412 }
11413 #endif
11414 
11415 static int
11416 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11417 {
11418 	int rc;
11419 
11420 	if (cntxt->cid > M_CTXTQID)
11421 		return (EINVAL);
11422 
11423 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11424 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11425 		return (EINVAL);
11426 
11427 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11428 	if (rc)
11429 		return (rc);
11430 
11431 	if (hw_off_limits(sc)) {
11432 		rc = ENXIO;
11433 		goto done;
11434 	}
11435 
11436 	if (sc->flags & FW_OK) {
11437 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11438 		    &cntxt->data[0]);
11439 		if (rc == 0)
11440 			goto done;
11441 	}
11442 
11443 	/*
11444 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11445 	 * the backdoor.
11446 	 */
11447 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11448 done:
11449 	end_synchronized_op(sc, 0);
11450 	return (rc);
11451 }
11452 
11453 static int
11454 load_fw(struct adapter *sc, struct t4_data *fw)
11455 {
11456 	int rc;
11457 	uint8_t *fw_data;
11458 
11459 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11460 	if (rc)
11461 		return (rc);
11462 
11463 	if (hw_off_limits(sc)) {
11464 		rc = ENXIO;
11465 		goto done;
11466 	}
11467 
11468 	/*
11469 	 * The firmware, with the sole exception of the memory parity error
11470 	 * handler, runs from memory and not flash.  It is almost always safe to
11471 	 * install a new firmware on a running system.  Just set bit 1 in
11472 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11473 	 */
11474 	if (sc->flags & FULL_INIT_DONE &&
11475 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11476 		rc = EBUSY;
11477 		goto done;
11478 	}
11479 
11480 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11481 
11482 	rc = copyin(fw->data, fw_data, fw->len);
11483 	if (rc == 0)
11484 		rc = -t4_load_fw(sc, fw_data, fw->len);
11485 
11486 	free(fw_data, M_CXGBE);
11487 done:
11488 	end_synchronized_op(sc, 0);
11489 	return (rc);
11490 }
11491 
11492 static int
11493 load_cfg(struct adapter *sc, struct t4_data *cfg)
11494 {
11495 	int rc;
11496 	uint8_t *cfg_data = NULL;
11497 
11498 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11499 	if (rc)
11500 		return (rc);
11501 
11502 	if (hw_off_limits(sc)) {
11503 		rc = ENXIO;
11504 		goto done;
11505 	}
11506 
11507 	if (cfg->len == 0) {
11508 		/* clear */
11509 		rc = -t4_load_cfg(sc, NULL, 0);
11510 		goto done;
11511 	}
11512 
11513 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11514 
11515 	rc = copyin(cfg->data, cfg_data, cfg->len);
11516 	if (rc == 0)
11517 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11518 
11519 	free(cfg_data, M_CXGBE);
11520 done:
11521 	end_synchronized_op(sc, 0);
11522 	return (rc);
11523 }
11524 
11525 static int
11526 load_boot(struct adapter *sc, struct t4_bootrom *br)
11527 {
11528 	int rc;
11529 	uint8_t *br_data = NULL;
11530 	u_int offset;
11531 
11532 	if (br->len > 1024 * 1024)
11533 		return (EFBIG);
11534 
11535 	if (br->pf_offset == 0) {
11536 		/* pfidx */
11537 		if (br->pfidx_addr > 7)
11538 			return (EINVAL);
11539 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11540 		    A_PCIE_PF_EXPROM_OFST)));
11541 	} else if (br->pf_offset == 1) {
11542 		/* offset */
11543 		offset = G_OFFSET(br->pfidx_addr);
11544 	} else {
11545 		return (EINVAL);
11546 	}
11547 
11548 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11549 	if (rc)
11550 		return (rc);
11551 
11552 	if (hw_off_limits(sc)) {
11553 		rc = ENXIO;
11554 		goto done;
11555 	}
11556 
11557 	if (br->len == 0) {
11558 		/* clear */
11559 		rc = -t4_load_boot(sc, NULL, offset, 0);
11560 		goto done;
11561 	}
11562 
11563 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11564 
11565 	rc = copyin(br->data, br_data, br->len);
11566 	if (rc == 0)
11567 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11568 
11569 	free(br_data, M_CXGBE);
11570 done:
11571 	end_synchronized_op(sc, 0);
11572 	return (rc);
11573 }
11574 
11575 static int
11576 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11577 {
11578 	int rc;
11579 	uint8_t *bc_data = NULL;
11580 
11581 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11582 	if (rc)
11583 		return (rc);
11584 
11585 	if (hw_off_limits(sc)) {
11586 		rc = ENXIO;
11587 		goto done;
11588 	}
11589 
11590 	if (bc->len == 0) {
11591 		/* clear */
11592 		rc = -t4_load_bootcfg(sc, NULL, 0);
11593 		goto done;
11594 	}
11595 
11596 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11597 
11598 	rc = copyin(bc->data, bc_data, bc->len);
11599 	if (rc == 0)
11600 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11601 
11602 	free(bc_data, M_CXGBE);
11603 done:
11604 	end_synchronized_op(sc, 0);
11605 	return (rc);
11606 }
11607 
11608 static int
11609 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11610 {
11611 	int rc;
11612 	struct cudbg_init *cudbg;
11613 	void *handle, *buf;
11614 
11615 	/* buf is large, don't block if no memory is available */
11616 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11617 	if (buf == NULL)
11618 		return (ENOMEM);
11619 
11620 	handle = cudbg_alloc_handle();
11621 	if (handle == NULL) {
11622 		rc = ENOMEM;
11623 		goto done;
11624 	}
11625 
11626 	cudbg = cudbg_get_init(handle);
11627 	cudbg->adap = sc;
11628 	cudbg->print = (cudbg_print_cb)printf;
11629 
11630 #ifndef notyet
11631 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11632 	    __func__, dump->wr_flash, dump->len, dump->data);
11633 #endif
11634 
11635 	if (dump->wr_flash)
11636 		cudbg->use_flash = 1;
11637 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11638 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11639 
11640 	rc = cudbg_collect(handle, buf, &dump->len);
11641 	if (rc != 0)
11642 		goto done;
11643 
11644 	rc = copyout(buf, dump->data, dump->len);
11645 done:
11646 	cudbg_free_handle(handle);
11647 	free(buf, M_CXGBE);
11648 	return (rc);
11649 }
11650 
11651 static void
11652 free_offload_policy(struct t4_offload_policy *op)
11653 {
11654 	struct offload_rule *r;
11655 	int i;
11656 
11657 	if (op == NULL)
11658 		return;
11659 
11660 	r = &op->rule[0];
11661 	for (i = 0; i < op->nrules; i++, r++) {
11662 		free(r->bpf_prog.bf_insns, M_CXGBE);
11663 	}
11664 	free(op->rule, M_CXGBE);
11665 	free(op, M_CXGBE);
11666 }
11667 
11668 static int
11669 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11670 {
11671 	int i, rc, len;
11672 	struct t4_offload_policy *op, *old;
11673 	struct bpf_program *bf;
11674 	const struct offload_settings *s;
11675 	struct offload_rule *r;
11676 	void *u;
11677 
11678 	if (!is_offload(sc))
11679 		return (ENODEV);
11680 
11681 	if (uop->nrules == 0) {
11682 		/* Delete installed policies. */
11683 		op = NULL;
11684 		goto set_policy;
11685 	} else if (uop->nrules > 256) { /* arbitrary */
11686 		return (E2BIG);
11687 	}
11688 
11689 	/* Copy userspace offload policy to kernel */
11690 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11691 	op->nrules = uop->nrules;
11692 	len = op->nrules * sizeof(struct offload_rule);
11693 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11694 	rc = copyin(uop->rule, op->rule, len);
11695 	if (rc) {
11696 		free(op->rule, M_CXGBE);
11697 		free(op, M_CXGBE);
11698 		return (rc);
11699 	}
11700 
11701 	r = &op->rule[0];
11702 	for (i = 0; i < op->nrules; i++, r++) {
11703 
11704 		/* Validate open_type */
11705 		if (r->open_type != OPEN_TYPE_LISTEN &&
11706 		    r->open_type != OPEN_TYPE_ACTIVE &&
11707 		    r->open_type != OPEN_TYPE_PASSIVE &&
11708 		    r->open_type != OPEN_TYPE_DONTCARE) {
11709 error:
11710 			/*
11711 			 * Rules 0 to i have malloc'd filters that need to be
11712 			 * freed.  Rules i+1 to nrules have userspace pointers
11713 			 * and should be left alone.
11714 			 */
11715 			op->nrules = i;
11716 			free_offload_policy(op);
11717 			return (rc);
11718 		}
11719 
11720 		/* Validate settings */
11721 		s = &r->settings;
11722 		if ((s->offload != 0 && s->offload != 1) ||
11723 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11724 		    s->sched_class < -1 ||
11725 		    s->sched_class >= sc->params.nsched_cls) {
11726 			rc = EINVAL;
11727 			goto error;
11728 		}
11729 
11730 		bf = &r->bpf_prog;
11731 		u = bf->bf_insns;	/* userspace ptr */
11732 		bf->bf_insns = NULL;
11733 		if (bf->bf_len == 0) {
11734 			/* legal, matches everything */
11735 			continue;
11736 		}
11737 		len = bf->bf_len * sizeof(*bf->bf_insns);
11738 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11739 		rc = copyin(u, bf->bf_insns, len);
11740 		if (rc != 0)
11741 			goto error;
11742 
11743 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11744 			rc = EINVAL;
11745 			goto error;
11746 		}
11747 	}
11748 set_policy:
11749 	rw_wlock(&sc->policy_lock);
11750 	old = sc->policy;
11751 	sc->policy = op;
11752 	rw_wunlock(&sc->policy_lock);
11753 	free_offload_policy(old);
11754 
11755 	return (0);
11756 }
11757 
11758 #define MAX_READ_BUF_SIZE (128 * 1024)
11759 static int
11760 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11761 {
11762 	uint32_t addr, remaining, n;
11763 	uint32_t *buf;
11764 	int rc;
11765 	uint8_t *dst;
11766 
11767 	mtx_lock(&sc->reg_lock);
11768 	if (hw_off_limits(sc))
11769 		rc = ENXIO;
11770 	else
11771 		rc = validate_mem_range(sc, mr->addr, mr->len);
11772 	mtx_unlock(&sc->reg_lock);
11773 	if (rc != 0)
11774 		return (rc);
11775 
11776 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11777 	addr = mr->addr;
11778 	remaining = mr->len;
11779 	dst = (void *)mr->data;
11780 
11781 	while (remaining) {
11782 		n = min(remaining, MAX_READ_BUF_SIZE);
11783 		mtx_lock(&sc->reg_lock);
11784 		if (hw_off_limits(sc))
11785 			rc = ENXIO;
11786 		else
11787 			read_via_memwin(sc, 2, addr, buf, n);
11788 		mtx_unlock(&sc->reg_lock);
11789 		if (rc != 0)
11790 			break;
11791 
11792 		rc = copyout(buf, dst, n);
11793 		if (rc != 0)
11794 			break;
11795 
11796 		dst += n;
11797 		remaining -= n;
11798 		addr += n;
11799 	}
11800 
11801 	free(buf, M_CXGBE);
11802 	return (rc);
11803 }
11804 #undef MAX_READ_BUF_SIZE
11805 
11806 static int
11807 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11808 {
11809 	int rc;
11810 
11811 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11812 		return (EINVAL);
11813 
11814 	if (i2cd->len > sizeof(i2cd->data))
11815 		return (EFBIG);
11816 
11817 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11818 	if (rc)
11819 		return (rc);
11820 	if (hw_off_limits(sc))
11821 		rc = ENXIO;
11822 	else
11823 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11824 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11825 	end_synchronized_op(sc, 0);
11826 
11827 	return (rc);
11828 }
11829 
11830 static int
11831 clear_stats(struct adapter *sc, u_int port_id)
11832 {
11833 	int i, v, chan_map;
11834 	struct port_info *pi;
11835 	struct vi_info *vi;
11836 	struct sge_rxq *rxq;
11837 	struct sge_txq *txq;
11838 	struct sge_wrq *wrq;
11839 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11840 	struct sge_ofld_txq *ofld_txq;
11841 #endif
11842 #ifdef TCP_OFFLOAD
11843 	struct sge_ofld_rxq *ofld_rxq;
11844 #endif
11845 
11846 	if (port_id >= sc->params.nports)
11847 		return (EINVAL);
11848 	pi = sc->port[port_id];
11849 	if (pi == NULL)
11850 		return (EIO);
11851 
11852 	mtx_lock(&sc->reg_lock);
11853 	if (!hw_off_limits(sc)) {
11854 		/* MAC stats */
11855 		t4_clr_port_stats(sc, pi->tx_chan);
11856 		if (is_t6(sc)) {
11857 			if (pi->fcs_reg != -1)
11858 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11859 			else
11860 				pi->stats.rx_fcs_err = 0;
11861 		}
11862 		for_each_vi(pi, v, vi) {
11863 			if (vi->flags & VI_INIT_DONE)
11864 				t4_clr_vi_stats(sc, vi->vin);
11865 		}
11866 		chan_map = pi->rx_e_chan_map;
11867 		v = 0;	/* reuse */
11868 		while (chan_map) {
11869 			i = ffs(chan_map) - 1;
11870 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11871 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11872 			chan_map &= ~(1 << i);
11873 		}
11874 	}
11875 	mtx_unlock(&sc->reg_lock);
11876 	pi->tx_parse_error = 0;
11877 	pi->tnl_cong_drops = 0;
11878 
11879 	/*
11880 	 * Since this command accepts a port, clear stats for
11881 	 * all VIs on this port.
11882 	 */
11883 	for_each_vi(pi, v, vi) {
11884 		if (vi->flags & VI_INIT_DONE) {
11885 
11886 			for_each_rxq(vi, i, rxq) {
11887 #if defined(INET) || defined(INET6)
11888 				rxq->lro.lro_queued = 0;
11889 				rxq->lro.lro_flushed = 0;
11890 #endif
11891 				rxq->rxcsum = 0;
11892 				rxq->vlan_extraction = 0;
11893 				rxq->vxlan_rxcsum = 0;
11894 
11895 				rxq->fl.cl_allocated = 0;
11896 				rxq->fl.cl_recycled = 0;
11897 				rxq->fl.cl_fast_recycled = 0;
11898 			}
11899 
11900 			for_each_txq(vi, i, txq) {
11901 				txq->txcsum = 0;
11902 				txq->tso_wrs = 0;
11903 				txq->vlan_insertion = 0;
11904 				txq->imm_wrs = 0;
11905 				txq->sgl_wrs = 0;
11906 				txq->txpkt_wrs = 0;
11907 				txq->txpkts0_wrs = 0;
11908 				txq->txpkts1_wrs = 0;
11909 				txq->txpkts0_pkts = 0;
11910 				txq->txpkts1_pkts = 0;
11911 				txq->txpkts_flush = 0;
11912 				txq->raw_wrs = 0;
11913 				txq->vxlan_tso_wrs = 0;
11914 				txq->vxlan_txcsum = 0;
11915 				txq->kern_tls_records = 0;
11916 				txq->kern_tls_short = 0;
11917 				txq->kern_tls_partial = 0;
11918 				txq->kern_tls_full = 0;
11919 				txq->kern_tls_octets = 0;
11920 				txq->kern_tls_waste = 0;
11921 				txq->kern_tls_options = 0;
11922 				txq->kern_tls_header = 0;
11923 				txq->kern_tls_fin = 0;
11924 				txq->kern_tls_fin_short = 0;
11925 				txq->kern_tls_cbc = 0;
11926 				txq->kern_tls_gcm = 0;
11927 				mp_ring_reset_stats(txq->r);
11928 			}
11929 
11930 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11931 			for_each_ofld_txq(vi, i, ofld_txq) {
11932 				ofld_txq->wrq.tx_wrs_direct = 0;
11933 				ofld_txq->wrq.tx_wrs_copied = 0;
11934 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11935 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11936 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11937 				counter_u64_zero(ofld_txq->tx_aio_jobs);
11938 				counter_u64_zero(ofld_txq->tx_aio_octets);
11939 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11940 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11941 			}
11942 #endif
11943 #ifdef TCP_OFFLOAD
11944 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11945 				ofld_rxq->fl.cl_allocated = 0;
11946 				ofld_rxq->fl.cl_recycled = 0;
11947 				ofld_rxq->fl.cl_fast_recycled = 0;
11948 				counter_u64_zero(
11949 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11950 				counter_u64_zero(
11951 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11952 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11953 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11954 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11955 				ofld_rxq->rx_iscsi_fl_octets = 0;
11956 				ofld_rxq->rx_aio_ddp_jobs = 0;
11957 				ofld_rxq->rx_aio_ddp_octets = 0;
11958 				ofld_rxq->rx_toe_tls_records = 0;
11959 				ofld_rxq->rx_toe_tls_octets = 0;
11960 				ofld_rxq->rx_toe_ddp_octets = 0;
11961 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
11962 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
11963 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
11964 			}
11965 #endif
11966 
11967 			if (IS_MAIN_VI(vi)) {
11968 				wrq = &sc->sge.ctrlq[pi->port_id];
11969 				wrq->tx_wrs_direct = 0;
11970 				wrq->tx_wrs_copied = 0;
11971 			}
11972 		}
11973 	}
11974 
11975 	return (0);
11976 }
11977 
11978 static int
11979 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11980 {
11981 #ifdef INET6
11982 	struct in6_addr in6;
11983 
11984 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
11985 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
11986 		return (0);
11987 	else
11988 		return (EIO);
11989 #else
11990 	return (ENOTSUP);
11991 #endif
11992 }
11993 
11994 static int
11995 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
11996 {
11997 #ifdef INET6
11998 	struct in6_addr in6;
11999 
12000 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12001 	return (t4_release_clip_addr(sc, &in6));
12002 #else
12003 	return (ENOTSUP);
12004 #endif
12005 }
12006 
12007 int
12008 t4_os_find_pci_capability(struct adapter *sc, int cap)
12009 {
12010 	int i;
12011 
12012 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12013 }
12014 
12015 int
12016 t4_os_pci_save_state(struct adapter *sc)
12017 {
12018 	device_t dev;
12019 	struct pci_devinfo *dinfo;
12020 
12021 	dev = sc->dev;
12022 	dinfo = device_get_ivars(dev);
12023 
12024 	pci_cfg_save(dev, dinfo, 0);
12025 	return (0);
12026 }
12027 
12028 int
12029 t4_os_pci_restore_state(struct adapter *sc)
12030 {
12031 	device_t dev;
12032 	struct pci_devinfo *dinfo;
12033 
12034 	dev = sc->dev;
12035 	dinfo = device_get_ivars(dev);
12036 
12037 	pci_cfg_restore(dev, dinfo);
12038 	return (0);
12039 }
12040 
12041 void
12042 t4_os_portmod_changed(struct port_info *pi)
12043 {
12044 	struct adapter *sc = pi->adapter;
12045 	struct vi_info *vi;
12046 	if_t ifp;
12047 	static const char *mod_str[] = {
12048 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12049 	};
12050 
12051 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12052 	    ("%s: port_type %u", __func__, pi->port_type));
12053 
12054 	vi = &pi->vi[0];
12055 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12056 		PORT_LOCK(pi);
12057 		build_medialist(pi);
12058 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12059 			fixup_link_config(pi);
12060 			apply_link_config(pi);
12061 		}
12062 		PORT_UNLOCK(pi);
12063 		end_synchronized_op(sc, LOCK_HELD);
12064 	}
12065 
12066 	ifp = vi->ifp;
12067 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12068 		if_printf(ifp, "transceiver unplugged.\n");
12069 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12070 		if_printf(ifp, "unknown transceiver inserted.\n");
12071 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12072 		if_printf(ifp, "unsupported transceiver inserted.\n");
12073 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12074 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12075 		    port_top_speed(pi), mod_str[pi->mod_type]);
12076 	} else {
12077 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12078 		    pi->mod_type);
12079 	}
12080 }
12081 
12082 void
12083 t4_os_link_changed(struct port_info *pi)
12084 {
12085 	struct vi_info *vi;
12086 	if_t ifp;
12087 	struct link_config *lc = &pi->link_cfg;
12088 	struct adapter *sc = pi->adapter;
12089 	int v;
12090 
12091 	PORT_LOCK_ASSERT_OWNED(pi);
12092 
12093 	if (is_t6(sc)) {
12094 		if (lc->link_ok) {
12095 			if (lc->speed > 25000 ||
12096 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12097 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12098 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12099 			} else {
12100 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12101 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12102 			}
12103 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12104 			pi->stats.rx_fcs_err = 0;
12105 		} else {
12106 			pi->fcs_reg = -1;
12107 		}
12108 	} else {
12109 		MPASS(pi->fcs_reg != -1);
12110 		MPASS(pi->fcs_base == 0);
12111 	}
12112 
12113 	for_each_vi(pi, v, vi) {
12114 		ifp = vi->ifp;
12115 		if (ifp == NULL || IS_DETACHING(vi))
12116 			continue;
12117 
12118 		if (lc->link_ok) {
12119 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12120 			if_link_state_change(ifp, LINK_STATE_UP);
12121 		} else {
12122 			if_link_state_change(ifp, LINK_STATE_DOWN);
12123 		}
12124 	}
12125 }
12126 
12127 void
12128 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12129 {
12130 	struct adapter *sc;
12131 
12132 	sx_slock(&t4_list_lock);
12133 	SLIST_FOREACH(sc, &t4_list, link) {
12134 		/*
12135 		 * func should not make any assumptions about what state sc is
12136 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12137 		 */
12138 		func(sc, arg);
12139 	}
12140 	sx_sunlock(&t4_list_lock);
12141 }
12142 
12143 static int
12144 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12145     struct thread *td)
12146 {
12147 	int rc;
12148 	struct adapter *sc = dev->si_drv1;
12149 
12150 	rc = priv_check(td, PRIV_DRIVER);
12151 	if (rc != 0)
12152 		return (rc);
12153 
12154 	switch (cmd) {
12155 	case CHELSIO_T4_GETREG: {
12156 		struct t4_reg *edata = (struct t4_reg *)data;
12157 
12158 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12159 			return (EFAULT);
12160 
12161 		mtx_lock(&sc->reg_lock);
12162 		if (hw_off_limits(sc))
12163 			rc = ENXIO;
12164 		else if (edata->size == 4)
12165 			edata->val = t4_read_reg(sc, edata->addr);
12166 		else if (edata->size == 8)
12167 			edata->val = t4_read_reg64(sc, edata->addr);
12168 		else
12169 			rc = EINVAL;
12170 		mtx_unlock(&sc->reg_lock);
12171 
12172 		break;
12173 	}
12174 	case CHELSIO_T4_SETREG: {
12175 		struct t4_reg *edata = (struct t4_reg *)data;
12176 
12177 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12178 			return (EFAULT);
12179 
12180 		mtx_lock(&sc->reg_lock);
12181 		if (hw_off_limits(sc))
12182 			rc = ENXIO;
12183 		else if (edata->size == 4) {
12184 			if (edata->val & 0xffffffff00000000)
12185 				rc = EINVAL;
12186 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12187 		} else if (edata->size == 8)
12188 			t4_write_reg64(sc, edata->addr, edata->val);
12189 		else
12190 			rc = EINVAL;
12191 		mtx_unlock(&sc->reg_lock);
12192 
12193 		break;
12194 	}
12195 	case CHELSIO_T4_REGDUMP: {
12196 		struct t4_regdump *regs = (struct t4_regdump *)data;
12197 		int reglen = t4_get_regs_len(sc);
12198 		uint8_t *buf;
12199 
12200 		if (regs->len < reglen) {
12201 			regs->len = reglen; /* hint to the caller */
12202 			return (ENOBUFS);
12203 		}
12204 
12205 		regs->len = reglen;
12206 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12207 		mtx_lock(&sc->reg_lock);
12208 		if (hw_off_limits(sc))
12209 			rc = ENXIO;
12210 		else
12211 			get_regs(sc, regs, buf);
12212 		mtx_unlock(&sc->reg_lock);
12213 		if (rc == 0)
12214 			rc = copyout(buf, regs->data, reglen);
12215 		free(buf, M_CXGBE);
12216 		break;
12217 	}
12218 	case CHELSIO_T4_GET_FILTER_MODE:
12219 		rc = get_filter_mode(sc, (uint32_t *)data);
12220 		break;
12221 	case CHELSIO_T4_SET_FILTER_MODE:
12222 		rc = set_filter_mode(sc, *(uint32_t *)data);
12223 		break;
12224 	case CHELSIO_T4_SET_FILTER_MASK:
12225 		rc = set_filter_mask(sc, *(uint32_t *)data);
12226 		break;
12227 	case CHELSIO_T4_GET_FILTER:
12228 		rc = get_filter(sc, (struct t4_filter *)data);
12229 		break;
12230 	case CHELSIO_T4_SET_FILTER:
12231 		rc = set_filter(sc, (struct t4_filter *)data);
12232 		break;
12233 	case CHELSIO_T4_DEL_FILTER:
12234 		rc = del_filter(sc, (struct t4_filter *)data);
12235 		break;
12236 	case CHELSIO_T4_GET_SGE_CONTEXT:
12237 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12238 		break;
12239 	case CHELSIO_T4_LOAD_FW:
12240 		rc = load_fw(sc, (struct t4_data *)data);
12241 		break;
12242 	case CHELSIO_T4_GET_MEM:
12243 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12244 		break;
12245 	case CHELSIO_T4_GET_I2C:
12246 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12247 		break;
12248 	case CHELSIO_T4_CLEAR_STATS:
12249 		rc = clear_stats(sc, *(uint32_t *)data);
12250 		break;
12251 	case CHELSIO_T4_SCHED_CLASS:
12252 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12253 		break;
12254 	case CHELSIO_T4_SCHED_QUEUE:
12255 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12256 		break;
12257 	case CHELSIO_T4_GET_TRACER:
12258 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12259 		break;
12260 	case CHELSIO_T4_SET_TRACER:
12261 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12262 		break;
12263 	case CHELSIO_T4_LOAD_CFG:
12264 		rc = load_cfg(sc, (struct t4_data *)data);
12265 		break;
12266 	case CHELSIO_T4_LOAD_BOOT:
12267 		rc = load_boot(sc, (struct t4_bootrom *)data);
12268 		break;
12269 	case CHELSIO_T4_LOAD_BOOTCFG:
12270 		rc = load_bootcfg(sc, (struct t4_data *)data);
12271 		break;
12272 	case CHELSIO_T4_CUDBG_DUMP:
12273 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12274 		break;
12275 	case CHELSIO_T4_SET_OFLD_POLICY:
12276 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12277 		break;
12278 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12279 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12280 		break;
12281 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12282 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12283 		break;
12284 	default:
12285 		rc = ENOTTY;
12286 	}
12287 
12288 	return (rc);
12289 }
12290 
12291 #ifdef TCP_OFFLOAD
12292 static int
12293 toe_capability(struct vi_info *vi, bool enable)
12294 {
12295 	int rc;
12296 	struct port_info *pi = vi->pi;
12297 	struct adapter *sc = pi->adapter;
12298 
12299 	ASSERT_SYNCHRONIZED_OP(sc);
12300 
12301 	if (!is_offload(sc))
12302 		return (ENODEV);
12303 	if (hw_off_limits(sc))
12304 		return (ENXIO);
12305 
12306 	if (enable) {
12307 #ifdef KERN_TLS
12308 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12309 			int i, j, n;
12310 			struct port_info *p;
12311 			struct vi_info *v;
12312 
12313 			/*
12314 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12315 			 * on any ifnet.
12316 			 */
12317 			n = 0;
12318 			for_each_port(sc, i) {
12319 				p = sc->port[i];
12320 				for_each_vi(p, j, v) {
12321 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12322 						CH_WARN(sc,
12323 						    "%s has NIC TLS enabled.\n",
12324 						    device_get_nameunit(v->dev));
12325 						n++;
12326 					}
12327 				}
12328 			}
12329 			if (n > 0) {
12330 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12331 				    "associated with this adapter before "
12332 				    "trying to enable TOE.\n");
12333 				return (EAGAIN);
12334 			}
12335 			rc = t6_config_kern_tls(sc, false);
12336 			if (rc)
12337 				return (rc);
12338 		}
12339 #endif
12340 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12341 			/* TOE is already enabled. */
12342 			return (0);
12343 		}
12344 
12345 		/*
12346 		 * We need the port's queues around so that we're able to send
12347 		 * and receive CPLs to/from the TOE even if the ifnet for this
12348 		 * port has never been UP'd administratively.
12349 		 */
12350 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12351 			return (rc);
12352 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12353 		    ((rc = vi_init(&pi->vi[0])) != 0))
12354 			return (rc);
12355 
12356 		if (isset(&sc->offload_map, pi->port_id)) {
12357 			/* TOE is enabled on another VI of this port. */
12358 			pi->uld_vis++;
12359 			return (0);
12360 		}
12361 
12362 		if (!uld_active(sc, ULD_TOM)) {
12363 			rc = t4_activate_uld(sc, ULD_TOM);
12364 			if (rc == EAGAIN) {
12365 				log(LOG_WARNING,
12366 				    "You must kldload t4_tom.ko before trying "
12367 				    "to enable TOE on a cxgbe interface.\n");
12368 			}
12369 			if (rc != 0)
12370 				return (rc);
12371 			KASSERT(sc->tom_softc != NULL,
12372 			    ("%s: TOM activated but softc NULL", __func__));
12373 			KASSERT(uld_active(sc, ULD_TOM),
12374 			    ("%s: TOM activated but flag not set", __func__));
12375 		}
12376 
12377 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12378 		if (!uld_active(sc, ULD_IWARP))
12379 			(void) t4_activate_uld(sc, ULD_IWARP);
12380 		if (!uld_active(sc, ULD_ISCSI))
12381 			(void) t4_activate_uld(sc, ULD_ISCSI);
12382 
12383 		pi->uld_vis++;
12384 		setbit(&sc->offload_map, pi->port_id);
12385 	} else {
12386 		pi->uld_vis--;
12387 
12388 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12389 			return (0);
12390 
12391 		KASSERT(uld_active(sc, ULD_TOM),
12392 		    ("%s: TOM never initialized?", __func__));
12393 		clrbit(&sc->offload_map, pi->port_id);
12394 	}
12395 
12396 	return (0);
12397 }
12398 
12399 /*
12400  * Add an upper layer driver to the global list.
12401  */
12402 int
12403 t4_register_uld(struct uld_info *ui)
12404 {
12405 	int rc = 0;
12406 	struct uld_info *u;
12407 
12408 	sx_xlock(&t4_uld_list_lock);
12409 	SLIST_FOREACH(u, &t4_uld_list, link) {
12410 	    if (u->uld_id == ui->uld_id) {
12411 		    rc = EEXIST;
12412 		    goto done;
12413 	    }
12414 	}
12415 
12416 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12417 	ui->refcount = 0;
12418 done:
12419 	sx_xunlock(&t4_uld_list_lock);
12420 	return (rc);
12421 }
12422 
12423 int
12424 t4_unregister_uld(struct uld_info *ui)
12425 {
12426 	int rc = EINVAL;
12427 	struct uld_info *u;
12428 
12429 	sx_xlock(&t4_uld_list_lock);
12430 
12431 	SLIST_FOREACH(u, &t4_uld_list, link) {
12432 	    if (u == ui) {
12433 		    if (ui->refcount > 0) {
12434 			    rc = EBUSY;
12435 			    goto done;
12436 		    }
12437 
12438 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12439 		    rc = 0;
12440 		    goto done;
12441 	    }
12442 	}
12443 done:
12444 	sx_xunlock(&t4_uld_list_lock);
12445 	return (rc);
12446 }
12447 
12448 int
12449 t4_activate_uld(struct adapter *sc, int id)
12450 {
12451 	int rc;
12452 	struct uld_info *ui;
12453 
12454 	ASSERT_SYNCHRONIZED_OP(sc);
12455 
12456 	if (id < 0 || id > ULD_MAX)
12457 		return (EINVAL);
12458 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12459 
12460 	sx_slock(&t4_uld_list_lock);
12461 
12462 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12463 		if (ui->uld_id == id) {
12464 			if (!(sc->flags & FULL_INIT_DONE)) {
12465 				rc = adapter_init(sc);
12466 				if (rc != 0)
12467 					break;
12468 			}
12469 
12470 			rc = ui->activate(sc);
12471 			if (rc == 0) {
12472 				setbit(&sc->active_ulds, id);
12473 				ui->refcount++;
12474 			}
12475 			break;
12476 		}
12477 	}
12478 
12479 	sx_sunlock(&t4_uld_list_lock);
12480 
12481 	return (rc);
12482 }
12483 
12484 int
12485 t4_deactivate_uld(struct adapter *sc, int id)
12486 {
12487 	int rc;
12488 	struct uld_info *ui;
12489 
12490 	ASSERT_SYNCHRONIZED_OP(sc);
12491 
12492 	if (id < 0 || id > ULD_MAX)
12493 		return (EINVAL);
12494 	rc = ENXIO;
12495 
12496 	sx_slock(&t4_uld_list_lock);
12497 
12498 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12499 		if (ui->uld_id == id) {
12500 			rc = ui->deactivate(sc);
12501 			if (rc == 0) {
12502 				clrbit(&sc->active_ulds, id);
12503 				ui->refcount--;
12504 			}
12505 			break;
12506 		}
12507 	}
12508 
12509 	sx_sunlock(&t4_uld_list_lock);
12510 
12511 	return (rc);
12512 }
12513 
12514 static int
12515 t4_deactivate_all_uld(struct adapter *sc)
12516 {
12517 	int rc;
12518 	struct uld_info *ui;
12519 
12520 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12521 	if (rc != 0)
12522 		return (ENXIO);
12523 
12524 	sx_slock(&t4_uld_list_lock);
12525 
12526 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12527 		if (isset(&sc->active_ulds, ui->uld_id)) {
12528 			rc = ui->deactivate(sc);
12529 			if (rc != 0)
12530 				break;
12531 			clrbit(&sc->active_ulds, ui->uld_id);
12532 			ui->refcount--;
12533 		}
12534 	}
12535 
12536 	sx_sunlock(&t4_uld_list_lock);
12537 	end_synchronized_op(sc, 0);
12538 
12539 	return (rc);
12540 }
12541 
12542 static void
12543 t4_async_event(struct adapter *sc)
12544 {
12545 	struct uld_info *ui;
12546 
12547 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12548 		return;
12549 	sx_slock(&t4_uld_list_lock);
12550 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12551 		if (ui->uld_id == ULD_IWARP) {
12552 			ui->async_event(sc);
12553 			break;
12554 		}
12555 	}
12556 	sx_sunlock(&t4_uld_list_lock);
12557 	end_synchronized_op(sc, 0);
12558 }
12559 
12560 int
12561 uld_active(struct adapter *sc, int uld_id)
12562 {
12563 
12564 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12565 
12566 	return (isset(&sc->active_ulds, uld_id));
12567 }
12568 #endif
12569 
12570 #ifdef KERN_TLS
12571 static int
12572 ktls_capability(struct adapter *sc, bool enable)
12573 {
12574 	ASSERT_SYNCHRONIZED_OP(sc);
12575 
12576 	if (!is_ktls(sc))
12577 		return (ENODEV);
12578 	if (!is_t6(sc))
12579 		return (0);
12580 	if (hw_off_limits(sc))
12581 		return (ENXIO);
12582 
12583 	if (enable) {
12584 		if (sc->flags & KERN_TLS_ON)
12585 			return (0);	/* already on */
12586 		if (sc->offload_map != 0) {
12587 			CH_WARN(sc,
12588 			    "Disable TOE on all interfaces associated with "
12589 			    "this adapter before trying to enable NIC TLS.\n");
12590 			return (EAGAIN);
12591 		}
12592 		return (t6_config_kern_tls(sc, true));
12593 	} else {
12594 		/*
12595 		 * Nothing to do for disable.  If TOE is enabled sometime later
12596 		 * then toe_capability will reconfigure the hardware.
12597 		 */
12598 		return (0);
12599 	}
12600 }
12601 #endif
12602 
12603 /*
12604  * t  = ptr to tunable.
12605  * nc = number of CPUs.
12606  * c  = compiled in default for that tunable.
12607  */
12608 static void
12609 calculate_nqueues(int *t, int nc, const int c)
12610 {
12611 	int nq;
12612 
12613 	if (*t > 0)
12614 		return;
12615 	nq = *t < 0 ? -*t : c;
12616 	*t = min(nc, nq);
12617 }
12618 
12619 /*
12620  * Come up with reasonable defaults for some of the tunables, provided they're
12621  * not set by the user (in which case we'll use the values as is).
12622  */
12623 static void
12624 tweak_tunables(void)
12625 {
12626 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12627 
12628 	if (t4_ntxq < 1) {
12629 #ifdef RSS
12630 		t4_ntxq = rss_getnumbuckets();
12631 #else
12632 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12633 #endif
12634 	}
12635 
12636 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12637 
12638 	if (t4_nrxq < 1) {
12639 #ifdef RSS
12640 		t4_nrxq = rss_getnumbuckets();
12641 #else
12642 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12643 #endif
12644 	}
12645 
12646 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12647 
12648 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12649 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12650 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12651 #endif
12652 #ifdef TCP_OFFLOAD
12653 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12654 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12655 #endif
12656 
12657 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12658 	if (t4_toecaps_allowed == -1)
12659 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12660 #else
12661 	if (t4_toecaps_allowed == -1)
12662 		t4_toecaps_allowed = 0;
12663 #endif
12664 
12665 #ifdef TCP_OFFLOAD
12666 	if (t4_rdmacaps_allowed == -1) {
12667 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12668 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12669 	}
12670 
12671 	if (t4_iscsicaps_allowed == -1) {
12672 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12673 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12674 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12675 	}
12676 
12677 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12678 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12679 
12680 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12681 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12682 #else
12683 	if (t4_rdmacaps_allowed == -1)
12684 		t4_rdmacaps_allowed = 0;
12685 
12686 	if (t4_iscsicaps_allowed == -1)
12687 		t4_iscsicaps_allowed = 0;
12688 #endif
12689 
12690 #ifdef DEV_NETMAP
12691 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12692 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12693 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12694 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12695 #endif
12696 
12697 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12698 		t4_tmr_idx = TMR_IDX;
12699 
12700 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12701 		t4_pktc_idx = PKTC_IDX;
12702 
12703 	if (t4_qsize_txq < 128)
12704 		t4_qsize_txq = 128;
12705 
12706 	if (t4_qsize_rxq < 128)
12707 		t4_qsize_rxq = 128;
12708 	while (t4_qsize_rxq & 7)
12709 		t4_qsize_rxq++;
12710 
12711 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12712 
12713 	/*
12714 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12715 	 * VI for the port.  The rest are additional virtual interfaces on the
12716 	 * same physical port.  Note that the main VI does not have native
12717 	 * netmap support but the extra VIs do.
12718 	 *
12719 	 * Limit the number of VIs per port to the number of available
12720 	 * MAC addresses per port.
12721 	 */
12722 	if (t4_num_vis < 1)
12723 		t4_num_vis = 1;
12724 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12725 		t4_num_vis = nitems(vi_mac_funcs);
12726 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12727 	}
12728 
12729 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12730 		pcie_relaxed_ordering = 1;
12731 #if defined(__i386__) || defined(__amd64__)
12732 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12733 			pcie_relaxed_ordering = 0;
12734 #endif
12735 	}
12736 }
12737 
12738 #ifdef DDB
12739 static void
12740 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
12741 {
12742 	uint32_t base, j, off, pf, reg, save, win_pos;
12743 
12744 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12745 	save = t4_read_reg(sc, reg);
12746 	base = sc->memwin[2].mw_base;
12747 
12748 	if (is_t4(sc)) {
12749 		pf = 0;
12750 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
12751 	} else {
12752 		pf = V_PFNUM(sc->pf);
12753 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
12754 	}
12755 	off = addr - win_pos;
12756 	t4_write_reg(sc, reg, win_pos | pf);
12757 	t4_read_reg(sc, reg);
12758 
12759 	while (len > 0 && !db_pager_quit) {
12760 		uint32_t buf[8];
12761 		for (j = 0; j < 8; j++, off += 4)
12762 			buf[j] = htonl(t4_read_reg(sc, base + off));
12763 
12764 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12765 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12766 		    buf[7]);
12767 		if (len <= sizeof(buf))
12768 			len = 0;
12769 		else
12770 			len -= sizeof(buf);
12771 	}
12772 
12773 	t4_write_reg(sc, reg, save);
12774 	t4_read_reg(sc, reg);
12775 }
12776 
12777 static void
12778 t4_dump_tcb(struct adapter *sc, int tid)
12779 {
12780 	uint32_t tcb_addr;
12781 
12782 	/* Dump TCB for the tid */
12783 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12784 	tcb_addr += tid * TCB_SIZE;
12785 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
12786 }
12787 
12788 static void
12789 t4_dump_devlog(struct adapter *sc)
12790 {
12791 	struct devlog_params *dparams = &sc->params.devlog;
12792 	struct fw_devlog_e e;
12793 	int i, first, j, m, nentries, rc;
12794 	uint64_t ftstamp = UINT64_MAX;
12795 
12796 	if (dparams->start == 0) {
12797 		db_printf("devlog params not valid\n");
12798 		return;
12799 	}
12800 
12801 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12802 	m = fwmtype_to_hwmtype(dparams->memtype);
12803 
12804 	/* Find the first entry. */
12805 	first = -1;
12806 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12807 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12808 		    sizeof(e), (void *)&e);
12809 		if (rc != 0)
12810 			break;
12811 
12812 		if (e.timestamp == 0)
12813 			break;
12814 
12815 		e.timestamp = be64toh(e.timestamp);
12816 		if (e.timestamp < ftstamp) {
12817 			ftstamp = e.timestamp;
12818 			first = i;
12819 		}
12820 	}
12821 
12822 	if (first == -1)
12823 		return;
12824 
12825 	i = first;
12826 	do {
12827 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12828 		    sizeof(e), (void *)&e);
12829 		if (rc != 0)
12830 			return;
12831 
12832 		if (e.timestamp == 0)
12833 			return;
12834 
12835 		e.timestamp = be64toh(e.timestamp);
12836 		e.seqno = be32toh(e.seqno);
12837 		for (j = 0; j < 8; j++)
12838 			e.params[j] = be32toh(e.params[j]);
12839 
12840 		db_printf("%10d  %15ju  %8s  %8s  ",
12841 		    e.seqno, e.timestamp,
12842 		    (e.level < nitems(devlog_level_strings) ?
12843 			devlog_level_strings[e.level] : "UNKNOWN"),
12844 		    (e.facility < nitems(devlog_facility_strings) ?
12845 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12846 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12847 		    e.params[3], e.params[4], e.params[5], e.params[6],
12848 		    e.params[7]);
12849 
12850 		if (++i == nentries)
12851 			i = 0;
12852 	} while (i != first && !db_pager_quit);
12853 }
12854 
12855 static DB_DEFINE_TABLE(show, t4, show_t4);
12856 
12857 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12858 {
12859 	device_t dev;
12860 	int t;
12861 	bool valid;
12862 
12863 	valid = false;
12864 	t = db_read_token();
12865 	if (t == tIDENT) {
12866 		dev = device_lookup_by_name(db_tok_string);
12867 		valid = true;
12868 	}
12869 	db_skip_to_eol();
12870 	if (!valid) {
12871 		db_printf("usage: show t4 devlog <nexus>\n");
12872 		return;
12873 	}
12874 
12875 	if (dev == NULL) {
12876 		db_printf("device not found\n");
12877 		return;
12878 	}
12879 
12880 	t4_dump_devlog(device_get_softc(dev));
12881 }
12882 
12883 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12884 {
12885 	device_t dev;
12886 	int radix, tid, t;
12887 	bool valid;
12888 
12889 	valid = false;
12890 	radix = db_radix;
12891 	db_radix = 10;
12892 	t = db_read_token();
12893 	if (t == tIDENT) {
12894 		dev = device_lookup_by_name(db_tok_string);
12895 		t = db_read_token();
12896 		if (t == tNUMBER) {
12897 			tid = db_tok_number;
12898 			valid = true;
12899 		}
12900 	}
12901 	db_radix = radix;
12902 	db_skip_to_eol();
12903 	if (!valid) {
12904 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12905 		return;
12906 	}
12907 
12908 	if (dev == NULL) {
12909 		db_printf("device not found\n");
12910 		return;
12911 	}
12912 	if (tid < 0) {
12913 		db_printf("invalid tid\n");
12914 		return;
12915 	}
12916 
12917 	t4_dump_tcb(device_get_softc(dev), tid);
12918 }
12919 
12920 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
12921 {
12922 	device_t dev;
12923 	int radix, t;
12924 	bool valid;
12925 
12926 	valid = false;
12927 	radix = db_radix;
12928 	db_radix = 10;
12929 	t = db_read_token();
12930 	if (t == tIDENT) {
12931 		dev = device_lookup_by_name(db_tok_string);
12932 		t = db_read_token();
12933 		if (t == tNUMBER) {
12934 			addr = db_tok_number;
12935 			t = db_read_token();
12936 			if (t == tNUMBER) {
12937 				count = db_tok_number;
12938 				valid = true;
12939 			}
12940 		}
12941 	}
12942 	db_radix = radix;
12943 	db_skip_to_eol();
12944 	if (!valid) {
12945 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
12946 		return;
12947 	}
12948 
12949 	if (dev == NULL) {
12950 		db_printf("device not found\n");
12951 		return;
12952 	}
12953 	if (addr < 0) {
12954 		db_printf("invalid address\n");
12955 		return;
12956 	}
12957 	if (count <= 0) {
12958 		db_printf("invalid length\n");
12959 		return;
12960 	}
12961 
12962 	t4_dump_mem(device_get_softc(dev), addr, count);
12963 }
12964 #endif
12965 
12966 static eventhandler_tag vxlan_start_evtag;
12967 static eventhandler_tag vxlan_stop_evtag;
12968 
12969 struct vxlan_evargs {
12970 	if_t ifp;
12971 	uint16_t port;
12972 };
12973 
12974 static void
12975 enable_vxlan_rx(struct adapter *sc)
12976 {
12977 	int i, rc;
12978 	struct port_info *pi;
12979 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
12980 
12981 	ASSERT_SYNCHRONIZED_OP(sc);
12982 
12983 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
12984 	    F_VXLAN_EN);
12985 	for_each_port(sc, i) {
12986 		pi = sc->port[i];
12987 		if (pi->vxlan_tcam_entry == true)
12988 			continue;
12989 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
12990 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
12991 		    true);
12992 		if (rc < 0) {
12993 			rc = -rc;
12994 			CH_ERR(&pi->vi[0],
12995 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
12996 		} else {
12997 			MPASS(rc == sc->rawf_base + pi->port_id);
12998 			pi->vxlan_tcam_entry = true;
12999 		}
13000 	}
13001 }
13002 
13003 static void
13004 t4_vxlan_start(struct adapter *sc, void *arg)
13005 {
13006 	struct vxlan_evargs *v = arg;
13007 
13008 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13009 		return;
13010 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13011 		return;
13012 
13013 	if (sc->vxlan_refcount == 0) {
13014 		sc->vxlan_port = v->port;
13015 		sc->vxlan_refcount = 1;
13016 		if (!hw_off_limits(sc))
13017 			enable_vxlan_rx(sc);
13018 	} else if (sc->vxlan_port == v->port) {
13019 		sc->vxlan_refcount++;
13020 	} else {
13021 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13022 		    "ignoring attempt to configure it on port %d\n",
13023 		    sc->vxlan_port, v->port);
13024 	}
13025 	end_synchronized_op(sc, 0);
13026 }
13027 
13028 static void
13029 t4_vxlan_stop(struct adapter *sc, void *arg)
13030 {
13031 	struct vxlan_evargs *v = arg;
13032 
13033 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13034 		return;
13035 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13036 		return;
13037 
13038 	/*
13039 	 * VXLANs may have been configured before the driver was loaded so we
13040 	 * may see more stops than starts.  This is not handled cleanly but at
13041 	 * least we keep the refcount sane.
13042 	 */
13043 	if (sc->vxlan_port != v->port)
13044 		goto done;
13045 	if (sc->vxlan_refcount == 0) {
13046 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13047 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13048 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13049 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13050 done:
13051 	end_synchronized_op(sc, 0);
13052 }
13053 
13054 static void
13055 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13056     sa_family_t family, u_int port)
13057 {
13058 	struct vxlan_evargs v;
13059 
13060 	MPASS(family == AF_INET || family == AF_INET6);
13061 	v.ifp = ifp;
13062 	v.port = port;
13063 
13064 	t4_iterate(t4_vxlan_start, &v);
13065 }
13066 
13067 static void
13068 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13069     u_int port)
13070 {
13071 	struct vxlan_evargs v;
13072 
13073 	MPASS(family == AF_INET || family == AF_INET6);
13074 	v.ifp = ifp;
13075 	v.port = port;
13076 
13077 	t4_iterate(t4_vxlan_stop, &v);
13078 }
13079 
13080 
13081 static struct sx mlu;	/* mod load unload */
13082 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13083 
13084 static int
13085 mod_event(module_t mod, int cmd, void *arg)
13086 {
13087 	int rc = 0;
13088 	static int loaded = 0;
13089 
13090 	switch (cmd) {
13091 	case MOD_LOAD:
13092 		sx_xlock(&mlu);
13093 		if (loaded++ == 0) {
13094 			t4_sge_modload();
13095 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13096 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13097 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13098 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13099 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13100 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13101 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13102 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13103 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13104 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13105 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13106 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13107 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13108 			    do_smt_write_rpl);
13109 			sx_init(&t4_list_lock, "T4/T5 adapters");
13110 			SLIST_INIT(&t4_list);
13111 			callout_init(&fatal_callout, 1);
13112 #ifdef TCP_OFFLOAD
13113 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13114 			SLIST_INIT(&t4_uld_list);
13115 #endif
13116 #ifdef INET6
13117 			t4_clip_modload();
13118 #endif
13119 #ifdef KERN_TLS
13120 			t6_ktls_modload();
13121 #endif
13122 			t4_tracer_modload();
13123 			tweak_tunables();
13124 			vxlan_start_evtag =
13125 			    EVENTHANDLER_REGISTER(vxlan_start,
13126 				t4_vxlan_start_handler, NULL,
13127 				EVENTHANDLER_PRI_ANY);
13128 			vxlan_stop_evtag =
13129 			    EVENTHANDLER_REGISTER(vxlan_stop,
13130 				t4_vxlan_stop_handler, NULL,
13131 				EVENTHANDLER_PRI_ANY);
13132 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13133 			    taskqueue_thread_enqueue, &reset_tq);
13134 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13135 			    "t4_rst_thr");
13136 		}
13137 		sx_xunlock(&mlu);
13138 		break;
13139 
13140 	case MOD_UNLOAD:
13141 		sx_xlock(&mlu);
13142 		if (--loaded == 0) {
13143 			int tries;
13144 
13145 			taskqueue_free(reset_tq);
13146 			sx_slock(&t4_list_lock);
13147 			if (!SLIST_EMPTY(&t4_list)) {
13148 				rc = EBUSY;
13149 				sx_sunlock(&t4_list_lock);
13150 				goto done_unload;
13151 			}
13152 #ifdef TCP_OFFLOAD
13153 			sx_slock(&t4_uld_list_lock);
13154 			if (!SLIST_EMPTY(&t4_uld_list)) {
13155 				rc = EBUSY;
13156 				sx_sunlock(&t4_uld_list_lock);
13157 				sx_sunlock(&t4_list_lock);
13158 				goto done_unload;
13159 			}
13160 #endif
13161 			tries = 0;
13162 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13163 				uprintf("%ju clusters with custom free routine "
13164 				    "still is use.\n", t4_sge_extfree_refs());
13165 				pause("t4unload", 2 * hz);
13166 			}
13167 #ifdef TCP_OFFLOAD
13168 			sx_sunlock(&t4_uld_list_lock);
13169 #endif
13170 			sx_sunlock(&t4_list_lock);
13171 
13172 			if (t4_sge_extfree_refs() == 0) {
13173 				EVENTHANDLER_DEREGISTER(vxlan_start,
13174 				    vxlan_start_evtag);
13175 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13176 				    vxlan_stop_evtag);
13177 				t4_tracer_modunload();
13178 #ifdef KERN_TLS
13179 				t6_ktls_modunload();
13180 #endif
13181 #ifdef INET6
13182 				t4_clip_modunload();
13183 #endif
13184 #ifdef TCP_OFFLOAD
13185 				sx_destroy(&t4_uld_list_lock);
13186 #endif
13187 				sx_destroy(&t4_list_lock);
13188 				t4_sge_modunload();
13189 				loaded = 0;
13190 			} else {
13191 				rc = EBUSY;
13192 				loaded++;	/* undo earlier decrement */
13193 			}
13194 		}
13195 done_unload:
13196 		sx_xunlock(&mlu);
13197 		break;
13198 	}
13199 
13200 	return (rc);
13201 }
13202 
13203 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13204 MODULE_VERSION(t4nex, 1);
13205 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13206 #ifdef DEV_NETMAP
13207 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13208 #endif /* DEV_NETMAP */
13209 
13210 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13211 MODULE_VERSION(t5nex, 1);
13212 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13213 #ifdef DEV_NETMAP
13214 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13215 #endif /* DEV_NETMAP */
13216 
13217 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13218 MODULE_VERSION(t6nex, 1);
13219 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13220 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13221 #ifdef DEV_NETMAP
13222 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13223 #endif /* DEV_NETMAP */
13224 
13225 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13226 MODULE_VERSION(cxgbe, 1);
13227 
13228 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13229 MODULE_VERSION(cxl, 1);
13230 
13231 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13232 MODULE_VERSION(cc, 1);
13233 
13234 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13235 MODULE_VERSION(vcxgbe, 1);
13236 
13237 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13238 MODULE_VERSION(vcxl, 1);
13239 
13240 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13241 MODULE_VERSION(vcc, 1);
13242