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