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