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