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