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