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