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