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