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