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