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