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