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