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