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