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