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