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