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