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