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