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