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