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