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