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