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