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