xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision bcccd559e20d22c29805034b912659ffd0b97813)
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 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3439 	if (rc != 0) {
3440 		device_printf(sc->dev,
3441 		    "failed to query parameters (post_init): %d.\n", rc);
3442 		return (rc);
3443 	}
3444 
3445 	sc->sge.iq_start = val[0];
3446 	sc->sge.eq_start = val[1];
3447 	sc->tids.ftid_base = val[2];
3448 	sc->tids.nftids = val[3] - val[2] + 1;
3449 	sc->params.ftid_min = val[2];
3450 	sc->params.ftid_max = val[3];
3451 	sc->vres.l2t.start = val[4];
3452 	sc->vres.l2t.size = val[5] - val[4] + 1;
3453 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
3454 	    ("%s: L2 table size (%u) larger than expected (%u)",
3455 	    __func__, sc->vres.l2t.size, L2T_SIZE));
3456 
3457 	/*
3458 	 * MPSBGMAP is queried separately because only recent firmwares support
3459 	 * it as a parameter and we don't want the compound query above to fail
3460 	 * on older firmwares.
3461 	 */
3462 	param[0] = FW_PARAM_DEV(MPSBGMAP);
3463 	val[0] = 0;
3464 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
3465 	if (rc == 0)
3466 		sc->params.mps_bg_map = val[0];
3467 	else
3468 		sc->params.mps_bg_map = 0;
3469 
3470 	/* get capabilites */
3471 	bzero(&caps, sizeof(caps));
3472 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
3473 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
3474 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
3475 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
3476 	if (rc != 0) {
3477 		device_printf(sc->dev,
3478 		    "failed to get card capabilities: %d.\n", rc);
3479 		return (rc);
3480 	}
3481 
3482 #define READ_CAPS(x) do { \
3483 	sc->x = htobe16(caps.x); \
3484 } while (0)
3485 	READ_CAPS(nbmcaps);
3486 	READ_CAPS(linkcaps);
3487 	READ_CAPS(switchcaps);
3488 	READ_CAPS(niccaps);
3489 	READ_CAPS(toecaps);
3490 	READ_CAPS(rdmacaps);
3491 	READ_CAPS(cryptocaps);
3492 	READ_CAPS(iscsicaps);
3493 	READ_CAPS(fcoecaps);
3494 
3495 	/*
3496 	 * The firmware attempts memfree TOE configuration for -SO cards and
3497 	 * will report toecaps=0 if it runs out of resources (this depends on
3498 	 * the config file).  It may not report 0 for other capabilities
3499 	 * dependent on the TOE in this case.  Set them to 0 here so that the
3500 	 * driver doesn't bother tracking resources that will never be used.
3501 	 */
3502 	if (sc->toecaps == 0) {
3503 		sc->iscsicaps = 0;
3504 		sc->rdmacaps = 0;
3505 	}
3506 
3507 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
3508 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
3509 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
3510 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3511 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
3512 		if (rc != 0) {
3513 			device_printf(sc->dev,
3514 			    "failed to query NIC parameters: %d.\n", rc);
3515 			return (rc);
3516 		}
3517 		sc->tids.etid_base = val[0];
3518 		sc->params.etid_min = val[0];
3519 		sc->tids.netids = val[1] - val[0] + 1;
3520 		sc->params.netids = sc->tids.netids;
3521 		sc->params.eo_wr_cred = val[2];
3522 		sc->params.ethoffload = 1;
3523 	}
3524 
3525 	if (sc->toecaps) {
3526 		/* query offload-related parameters */
3527 		param[0] = FW_PARAM_DEV(NTID);
3528 		param[1] = FW_PARAM_PFVF(SERVER_START);
3529 		param[2] = FW_PARAM_PFVF(SERVER_END);
3530 		param[3] = FW_PARAM_PFVF(TDDP_START);
3531 		param[4] = FW_PARAM_PFVF(TDDP_END);
3532 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
3533 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3534 		if (rc != 0) {
3535 			device_printf(sc->dev,
3536 			    "failed to query TOE parameters: %d.\n", rc);
3537 			return (rc);
3538 		}
3539 		sc->tids.ntids = val[0];
3540 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
3541 		sc->tids.stid_base = val[1];
3542 		sc->tids.nstids = val[2] - val[1] + 1;
3543 		sc->vres.ddp.start = val[3];
3544 		sc->vres.ddp.size = val[4] - val[3] + 1;
3545 		sc->params.ofldq_wr_cred = val[5];
3546 		sc->params.offload = 1;
3547 	}
3548 	if (sc->rdmacaps) {
3549 		param[0] = FW_PARAM_PFVF(STAG_START);
3550 		param[1] = FW_PARAM_PFVF(STAG_END);
3551 		param[2] = FW_PARAM_PFVF(RQ_START);
3552 		param[3] = FW_PARAM_PFVF(RQ_END);
3553 		param[4] = FW_PARAM_PFVF(PBL_START);
3554 		param[5] = FW_PARAM_PFVF(PBL_END);
3555 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3556 		if (rc != 0) {
3557 			device_printf(sc->dev,
3558 			    "failed to query RDMA parameters(1): %d.\n", rc);
3559 			return (rc);
3560 		}
3561 		sc->vres.stag.start = val[0];
3562 		sc->vres.stag.size = val[1] - val[0] + 1;
3563 		sc->vres.rq.start = val[2];
3564 		sc->vres.rq.size = val[3] - val[2] + 1;
3565 		sc->vres.pbl.start = val[4];
3566 		sc->vres.pbl.size = val[5] - val[4] + 1;
3567 
3568 		param[0] = FW_PARAM_PFVF(SQRQ_START);
3569 		param[1] = FW_PARAM_PFVF(SQRQ_END);
3570 		param[2] = FW_PARAM_PFVF(CQ_START);
3571 		param[3] = FW_PARAM_PFVF(CQ_END);
3572 		param[4] = FW_PARAM_PFVF(OCQ_START);
3573 		param[5] = FW_PARAM_PFVF(OCQ_END);
3574 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
3575 		if (rc != 0) {
3576 			device_printf(sc->dev,
3577 			    "failed to query RDMA parameters(2): %d.\n", rc);
3578 			return (rc);
3579 		}
3580 		sc->vres.qp.start = val[0];
3581 		sc->vres.qp.size = val[1] - val[0] + 1;
3582 		sc->vres.cq.start = val[2];
3583 		sc->vres.cq.size = val[3] - val[2] + 1;
3584 		sc->vres.ocq.start = val[4];
3585 		sc->vres.ocq.size = val[5] - val[4] + 1;
3586 
3587 		param[0] = FW_PARAM_PFVF(SRQ_START);
3588 		param[1] = FW_PARAM_PFVF(SRQ_END);
3589 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
3590 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
3591 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
3592 		if (rc != 0) {
3593 			device_printf(sc->dev,
3594 			    "failed to query RDMA parameters(3): %d.\n", rc);
3595 			return (rc);
3596 		}
3597 		sc->vres.srq.start = val[0];
3598 		sc->vres.srq.size = val[1] - val[0] + 1;
3599 		sc->params.max_ordird_qp = val[2];
3600 		sc->params.max_ird_adapter = val[3];
3601 	}
3602 	if (sc->iscsicaps) {
3603 		param[0] = FW_PARAM_PFVF(ISCSI_START);
3604 		param[1] = FW_PARAM_PFVF(ISCSI_END);
3605 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
3606 		if (rc != 0) {
3607 			device_printf(sc->dev,
3608 			    "failed to query iSCSI parameters: %d.\n", rc);
3609 			return (rc);
3610 		}
3611 		sc->vres.iscsi.start = val[0];
3612 		sc->vres.iscsi.size = val[1] - val[0] + 1;
3613 	}
3614 
3615 	t4_init_sge_params(sc);
3616 
3617 	/*
3618 	 * We've got the params we wanted to query via the firmware.  Now grab
3619 	 * some others directly from the chip.
3620 	 */
3621 	rc = t4_read_chip_settings(sc);
3622 
3623 	return (rc);
3624 }
3625 
3626 static int
3627 set_params__post_init(struct adapter *sc)
3628 {
3629 	uint32_t param, val;
3630 #ifdef TCP_OFFLOAD
3631 	int i, v, shift;
3632 #endif
3633 
3634 	/* ask for encapsulated CPLs */
3635 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
3636 	val = 1;
3637 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3638 
3639 #ifdef TCP_OFFLOAD
3640 	/*
3641 	 * Override the TOE timers with user provided tunables.  This is not the
3642 	 * recommended way to change the timers (the firmware config file is) so
3643 	 * these tunables are not documented.
3644 	 *
3645 	 * All the timer tunables are in microseconds.
3646 	 */
3647 	if (t4_toe_keepalive_idle != 0) {
3648 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
3649 		v &= M_KEEPALIVEIDLE;
3650 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
3651 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
3652 	}
3653 	if (t4_toe_keepalive_interval != 0) {
3654 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
3655 		v &= M_KEEPALIVEINTVL;
3656 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
3657 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
3658 	}
3659 	if (t4_toe_keepalive_count != 0) {
3660 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
3661 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
3662 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
3663 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
3664 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
3665 	}
3666 	if (t4_toe_rexmt_min != 0) {
3667 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
3668 		v &= M_RXTMIN;
3669 		t4_set_reg_field(sc, A_TP_RXT_MIN,
3670 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
3671 	}
3672 	if (t4_toe_rexmt_max != 0) {
3673 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
3674 		v &= M_RXTMAX;
3675 		t4_set_reg_field(sc, A_TP_RXT_MAX,
3676 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
3677 	}
3678 	if (t4_toe_rexmt_count != 0) {
3679 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
3680 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
3681 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
3682 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
3683 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
3684 	}
3685 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
3686 		if (t4_toe_rexmt_backoff[i] != -1) {
3687 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
3688 			shift = (i & 3) << 3;
3689 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
3690 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
3691 		}
3692 	}
3693 #endif
3694 	return (0);
3695 }
3696 
3697 #undef FW_PARAM_PFVF
3698 #undef FW_PARAM_DEV
3699 
3700 static void
3701 t4_set_desc(struct adapter *sc)
3702 {
3703 	char buf[128];
3704 	struct adapter_params *p = &sc->params;
3705 
3706 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
3707 
3708 	device_set_desc_copy(sc->dev, buf);
3709 }
3710 
3711 static void
3712 build_medialist(struct port_info *pi, struct ifmedia *media)
3713 {
3714 	int m;
3715 
3716 	PORT_LOCK_ASSERT_OWNED(pi);
3717 
3718 	ifmedia_removeall(media);
3719 
3720 	/*
3721 	 * XXX: Would it be better to ifmedia_add all 4 combinations of pause
3722 	 * settings for every speed instead of just txpause|rxpause?  ifconfig
3723 	 * media display looks much better if autoselect is the only case where
3724 	 * ifm_current is different from ifm_active.  If the user picks anything
3725 	 * except txpause|rxpause the display is ugly.
3726 	 */
3727 	m = IFM_ETHER | IFM_FDX | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE;
3728 
3729 	switch(pi->port_type) {
3730 	case FW_PORT_TYPE_BT_XFI:
3731 	case FW_PORT_TYPE_BT_XAUI:
3732 		ifmedia_add(media, m | IFM_10G_T, 0, NULL);
3733 		/* fall through */
3734 
3735 	case FW_PORT_TYPE_BT_SGMII:
3736 		ifmedia_add(media, m | IFM_1000_T, 0, NULL);
3737 		ifmedia_add(media, m | IFM_100_TX, 0, NULL);
3738 		ifmedia_add(media, IFM_ETHER | IFM_AUTO, 0, NULL);
3739 		ifmedia_set(media, IFM_ETHER | IFM_AUTO);
3740 		break;
3741 
3742 	case FW_PORT_TYPE_CX4:
3743 		ifmedia_add(media, m | IFM_10G_CX4, 0, NULL);
3744 		ifmedia_set(media, m | IFM_10G_CX4);
3745 		break;
3746 
3747 	case FW_PORT_TYPE_QSFP_10G:
3748 	case FW_PORT_TYPE_SFP:
3749 	case FW_PORT_TYPE_FIBER_XFI:
3750 	case FW_PORT_TYPE_FIBER_XAUI:
3751 		switch (pi->mod_type) {
3752 
3753 		case FW_PORT_MOD_TYPE_LR:
3754 			ifmedia_add(media, m | IFM_10G_LR, 0, NULL);
3755 			ifmedia_set(media, m | IFM_10G_LR);
3756 			break;
3757 
3758 		case FW_PORT_MOD_TYPE_SR:
3759 			ifmedia_add(media, m | IFM_10G_SR, 0, NULL);
3760 			ifmedia_set(media, m | IFM_10G_SR);
3761 			break;
3762 
3763 		case FW_PORT_MOD_TYPE_LRM:
3764 			ifmedia_add(media, m | IFM_10G_LRM, 0, NULL);
3765 			ifmedia_set(media, m | IFM_10G_LRM);
3766 			break;
3767 
3768 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3769 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3770 			ifmedia_add(media, m | IFM_10G_TWINAX, 0, NULL);
3771 			ifmedia_set(media, m | IFM_10G_TWINAX);
3772 			break;
3773 
3774 		case FW_PORT_MOD_TYPE_NONE:
3775 			m &= ~IFM_FDX;
3776 			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3777 			ifmedia_set(media, m | IFM_NONE);
3778 			break;
3779 
3780 		case FW_PORT_MOD_TYPE_NA:
3781 		case FW_PORT_MOD_TYPE_ER:
3782 		default:
3783 			device_printf(pi->dev,
3784 			    "unknown port_type (%d), mod_type (%d)\n",
3785 			    pi->port_type, pi->mod_type);
3786 			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3787 			ifmedia_set(media, m | IFM_UNKNOWN);
3788 			break;
3789 		}
3790 		break;
3791 
3792 	case FW_PORT_TYPE_CR_QSFP:
3793 	case FW_PORT_TYPE_SFP28:
3794 	case FW_PORT_TYPE_KR_SFP28:
3795 		switch (pi->mod_type) {
3796 
3797 		case FW_PORT_MOD_TYPE_SR:
3798 			ifmedia_add(media, m | IFM_25G_SR, 0, NULL);
3799 			ifmedia_set(media, m | IFM_25G_SR);
3800 			break;
3801 
3802 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3803 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3804 			ifmedia_add(media, m | IFM_25G_CR, 0, NULL);
3805 			ifmedia_set(media, m | IFM_25G_CR);
3806 			break;
3807 
3808 		case FW_PORT_MOD_TYPE_NONE:
3809 			m &= ~IFM_FDX;
3810 			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3811 			ifmedia_set(media, m | IFM_NONE);
3812 			break;
3813 
3814 		default:
3815 			device_printf(pi->dev,
3816 			    "unknown port_type (%d), mod_type (%d)\n",
3817 			    pi->port_type, pi->mod_type);
3818 			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3819 			ifmedia_set(media, m | IFM_UNKNOWN);
3820 			break;
3821 		}
3822 		break;
3823 
3824 	case FW_PORT_TYPE_QSFP:
3825 		switch (pi->mod_type) {
3826 
3827 		case FW_PORT_MOD_TYPE_LR:
3828 			ifmedia_add(media, m | IFM_40G_LR4, 0, NULL);
3829 			ifmedia_set(media, m | IFM_40G_LR4);
3830 			break;
3831 
3832 		case FW_PORT_MOD_TYPE_SR:
3833 			ifmedia_add(media, m | IFM_40G_SR4, 0, NULL);
3834 			ifmedia_set(media, m | IFM_40G_SR4);
3835 			break;
3836 
3837 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3838 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3839 			ifmedia_add(media, m | IFM_40G_CR4, 0, NULL);
3840 			ifmedia_set(media, m | IFM_40G_CR4);
3841 			break;
3842 
3843 		case FW_PORT_MOD_TYPE_NONE:
3844 			m &= ~IFM_FDX;
3845 			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3846 			ifmedia_set(media, m | IFM_NONE);
3847 			break;
3848 
3849 		default:
3850 			device_printf(pi->dev,
3851 			    "unknown port_type (%d), mod_type (%d)\n",
3852 			    pi->port_type, pi->mod_type);
3853 			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3854 			ifmedia_set(media, m | IFM_UNKNOWN);
3855 			break;
3856 		}
3857 		break;
3858 
3859 	case FW_PORT_TYPE_KR4_100G:
3860 	case FW_PORT_TYPE_CR4_QSFP:
3861 		switch (pi->mod_type) {
3862 
3863 		case FW_PORT_MOD_TYPE_LR:
3864 			ifmedia_add(media, m | IFM_100G_LR4, 0, NULL);
3865 			ifmedia_set(media, m | IFM_100G_LR4);
3866 			break;
3867 
3868 		case FW_PORT_MOD_TYPE_SR:
3869 			ifmedia_add(media, m | IFM_100G_SR4, 0, NULL);
3870 			ifmedia_set(media, m | IFM_100G_SR4);
3871 			break;
3872 
3873 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3874 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3875 			ifmedia_add(media, m | IFM_100G_CR4, 0, NULL);
3876 			ifmedia_set(media, m | IFM_100G_CR4);
3877 			break;
3878 
3879 		case FW_PORT_MOD_TYPE_NONE:
3880 			m &= ~IFM_FDX;
3881 			ifmedia_add(media, m | IFM_NONE, 0, NULL);
3882 			ifmedia_set(media, m | IFM_NONE);
3883 			break;
3884 
3885 		default:
3886 			device_printf(pi->dev,
3887 			    "unknown port_type (%d), mod_type (%d)\n",
3888 			    pi->port_type, pi->mod_type);
3889 			ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3890 			ifmedia_set(media, m | IFM_UNKNOWN);
3891 			break;
3892 		}
3893 		break;
3894 
3895 	default:
3896 		device_printf(pi->dev,
3897 		    "unknown port_type (%d), mod_type (%d)\n", pi->port_type,
3898 		    pi->mod_type);
3899 		ifmedia_add(media, m | IFM_UNKNOWN, 0, NULL);
3900 		ifmedia_set(media, m | IFM_UNKNOWN);
3901 		break;
3902 	}
3903 }
3904 
3905 /*
3906  * Update all the requested_* fields in the link config and then send a mailbox
3907  * command to apply the settings.
3908  */
3909 static void
3910 init_l1cfg(struct port_info *pi)
3911 {
3912 	struct adapter *sc = pi->adapter;
3913 	struct link_config *lc = &pi->link_cfg;
3914 	int rc;
3915 
3916 	ASSERT_SYNCHRONIZED_OP(sc);
3917 
3918 	if (t4_autoneg != 0 && lc->supported & FW_PORT_CAP_ANEG) {
3919 		lc->requested_aneg = AUTONEG_ENABLE;
3920 		lc->requested_speed = 0;
3921 	} else {
3922 		lc->requested_aneg = AUTONEG_DISABLE;
3923 		lc->requested_speed = port_top_speed(pi);	/* in Gbps */
3924 	}
3925 
3926 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX);
3927 
3928 	if (t4_fec != -1) {
3929 		lc->requested_fec = t4_fec & (FEC_RS | FEC_BASER_RS |
3930 		    FEC_RESERVED);
3931 	} else {
3932 		/* Use the suggested value provided by the firmware in acaps */
3933 		if (lc->advertising & FW_PORT_CAP_FEC_RS)
3934 			lc->requested_fec = FEC_RS;
3935 		else if (lc->advertising & FW_PORT_CAP_FEC_BASER_RS)
3936 			lc->requested_fec = FEC_BASER_RS;
3937 		else if (lc->advertising & FW_PORT_CAP_FEC_RESERVED)
3938 			lc->requested_fec = FEC_RESERVED;
3939 		else
3940 			lc->requested_fec = 0;
3941 	}
3942 
3943 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
3944 	if (rc != 0) {
3945 		device_printf(pi->dev, "l1cfg failed: %d\n", rc);
3946 	} else {
3947 		lc->fc = lc->requested_fc;
3948 		lc->fec = lc->requested_fec;
3949 	}
3950 }
3951 
3952 #define FW_MAC_EXACT_CHUNK	7
3953 
3954 /*
3955  * Program the port's XGMAC based on parameters in ifnet.  The caller also
3956  * indicates which parameters should be programmed (the rest are left alone).
3957  */
3958 int
3959 update_mac_settings(struct ifnet *ifp, int flags)
3960 {
3961 	int rc = 0;
3962 	struct vi_info *vi = ifp->if_softc;
3963 	struct port_info *pi = vi->pi;
3964 	struct adapter *sc = pi->adapter;
3965 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
3966 
3967 	ASSERT_SYNCHRONIZED_OP(sc);
3968 	KASSERT(flags, ("%s: not told what to update.", __func__));
3969 
3970 	if (flags & XGMAC_MTU)
3971 		mtu = ifp->if_mtu;
3972 
3973 	if (flags & XGMAC_PROMISC)
3974 		promisc = ifp->if_flags & IFF_PROMISC ? 1 : 0;
3975 
3976 	if (flags & XGMAC_ALLMULTI)
3977 		allmulti = ifp->if_flags & IFF_ALLMULTI ? 1 : 0;
3978 
3979 	if (flags & XGMAC_VLANEX)
3980 		vlanex = ifp->if_capenable & IFCAP_VLAN_HWTAGGING ? 1 : 0;
3981 
3982 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
3983 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
3984 		    allmulti, 1, vlanex, false);
3985 		if (rc) {
3986 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
3987 			    rc);
3988 			return (rc);
3989 		}
3990 	}
3991 
3992 	if (flags & XGMAC_UCADDR) {
3993 		uint8_t ucaddr[ETHER_ADDR_LEN];
3994 
3995 		bcopy(IF_LLADDR(ifp), ucaddr, sizeof(ucaddr));
3996 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
3997 		    ucaddr, true, true);
3998 		if (rc < 0) {
3999 			rc = -rc;
4000 			if_printf(ifp, "change_mac failed: %d\n", rc);
4001 			return (rc);
4002 		} else {
4003 			vi->xact_addr_filt = rc;
4004 			rc = 0;
4005 		}
4006 	}
4007 
4008 	if (flags & XGMAC_MCADDRS) {
4009 		const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
4010 		int del = 1;
4011 		uint64_t hash = 0;
4012 		struct ifmultiaddr *ifma;
4013 		int i = 0, j;
4014 
4015 		if_maddr_rlock(ifp);
4016 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
4017 			if (ifma->ifma_addr->sa_family != AF_LINK)
4018 				continue;
4019 			mcaddr[i] =
4020 			    LLADDR((struct sockaddr_dl *)ifma->ifma_addr);
4021 			MPASS(ETHER_IS_MULTICAST(mcaddr[i]));
4022 			i++;
4023 
4024 			if (i == FW_MAC_EXACT_CHUNK) {
4025 				rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
4026 				    del, i, mcaddr, NULL, &hash, 0);
4027 				if (rc < 0) {
4028 					rc = -rc;
4029 					for (j = 0; j < i; j++) {
4030 						if_printf(ifp,
4031 						    "failed to add mc address"
4032 						    " %02x:%02x:%02x:"
4033 						    "%02x:%02x:%02x rc=%d\n",
4034 						    mcaddr[j][0], mcaddr[j][1],
4035 						    mcaddr[j][2], mcaddr[j][3],
4036 						    mcaddr[j][4], mcaddr[j][5],
4037 						    rc);
4038 					}
4039 					goto mcfail;
4040 				}
4041 				del = 0;
4042 				i = 0;
4043 			}
4044 		}
4045 		if (i > 0) {
4046 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, del, i,
4047 			    mcaddr, NULL, &hash, 0);
4048 			if (rc < 0) {
4049 				rc = -rc;
4050 				for (j = 0; j < i; j++) {
4051 					if_printf(ifp,
4052 					    "failed to add mc address"
4053 					    " %02x:%02x:%02x:"
4054 					    "%02x:%02x:%02x rc=%d\n",
4055 					    mcaddr[j][0], mcaddr[j][1],
4056 					    mcaddr[j][2], mcaddr[j][3],
4057 					    mcaddr[j][4], mcaddr[j][5],
4058 					    rc);
4059 				}
4060 				goto mcfail;
4061 			}
4062 		}
4063 
4064 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, hash, 0);
4065 		if (rc != 0)
4066 			if_printf(ifp, "failed to set mc address hash: %d", rc);
4067 mcfail:
4068 		if_maddr_runlock(ifp);
4069 	}
4070 
4071 	return (rc);
4072 }
4073 
4074 /*
4075  * {begin|end}_synchronized_op must be called from the same thread.
4076  */
4077 int
4078 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
4079     char *wmesg)
4080 {
4081 	int rc, pri;
4082 
4083 #ifdef WITNESS
4084 	/* the caller thinks it's ok to sleep, but is it really? */
4085 	if (flags & SLEEP_OK)
4086 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
4087 		    "begin_synchronized_op");
4088 #endif
4089 
4090 	if (INTR_OK)
4091 		pri = PCATCH;
4092 	else
4093 		pri = 0;
4094 
4095 	ADAPTER_LOCK(sc);
4096 	for (;;) {
4097 
4098 		if (vi && IS_DOOMED(vi)) {
4099 			rc = ENXIO;
4100 			goto done;
4101 		}
4102 
4103 		if (!IS_BUSY(sc)) {
4104 			rc = 0;
4105 			break;
4106 		}
4107 
4108 		if (!(flags & SLEEP_OK)) {
4109 			rc = EBUSY;
4110 			goto done;
4111 		}
4112 
4113 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
4114 			rc = EINTR;
4115 			goto done;
4116 		}
4117 	}
4118 
4119 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
4120 	SET_BUSY(sc);
4121 #ifdef INVARIANTS
4122 	sc->last_op = wmesg;
4123 	sc->last_op_thr = curthread;
4124 	sc->last_op_flags = flags;
4125 #endif
4126 
4127 done:
4128 	if (!(flags & HOLD_LOCK) || rc)
4129 		ADAPTER_UNLOCK(sc);
4130 
4131 	return (rc);
4132 }
4133 
4134 /*
4135  * Tell if_ioctl and if_init that the VI is going away.  This is
4136  * special variant of begin_synchronized_op and must be paired with a
4137  * call to end_synchronized_op.
4138  */
4139 void
4140 doom_vi(struct adapter *sc, struct vi_info *vi)
4141 {
4142 
4143 	ADAPTER_LOCK(sc);
4144 	SET_DOOMED(vi);
4145 	wakeup(&sc->flags);
4146 	while (IS_BUSY(sc))
4147 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
4148 	SET_BUSY(sc);
4149 #ifdef INVARIANTS
4150 	sc->last_op = "t4detach";
4151 	sc->last_op_thr = curthread;
4152 	sc->last_op_flags = 0;
4153 #endif
4154 	ADAPTER_UNLOCK(sc);
4155 }
4156 
4157 /*
4158  * {begin|end}_synchronized_op must be called from the same thread.
4159  */
4160 void
4161 end_synchronized_op(struct adapter *sc, int flags)
4162 {
4163 
4164 	if (flags & LOCK_HELD)
4165 		ADAPTER_LOCK_ASSERT_OWNED(sc);
4166 	else
4167 		ADAPTER_LOCK(sc);
4168 
4169 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
4170 	CLR_BUSY(sc);
4171 	wakeup(&sc->flags);
4172 	ADAPTER_UNLOCK(sc);
4173 }
4174 
4175 static int
4176 cxgbe_init_synchronized(struct vi_info *vi)
4177 {
4178 	struct port_info *pi = vi->pi;
4179 	struct adapter *sc = pi->adapter;
4180 	struct ifnet *ifp = vi->ifp;
4181 	int rc = 0, i;
4182 	struct sge_txq *txq;
4183 
4184 	ASSERT_SYNCHRONIZED_OP(sc);
4185 
4186 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4187 		return (0);	/* already running */
4188 
4189 	if (!(sc->flags & FULL_INIT_DONE) &&
4190 	    ((rc = adapter_full_init(sc)) != 0))
4191 		return (rc);	/* error message displayed already */
4192 
4193 	if (!(vi->flags & VI_INIT_DONE) &&
4194 	    ((rc = vi_full_init(vi)) != 0))
4195 		return (rc); /* error message displayed already */
4196 
4197 	rc = update_mac_settings(ifp, XGMAC_ALL);
4198 	if (rc)
4199 		goto done;	/* error message displayed already */
4200 
4201 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
4202 	if (rc != 0) {
4203 		if_printf(ifp, "enable_vi failed: %d\n", rc);
4204 		goto done;
4205 	}
4206 
4207 	/*
4208 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
4209 	 * if this changes.
4210 	 */
4211 
4212 	for_each_txq(vi, i, txq) {
4213 		TXQ_LOCK(txq);
4214 		txq->eq.flags |= EQ_ENABLED;
4215 		TXQ_UNLOCK(txq);
4216 	}
4217 
4218 	/*
4219 	 * The first iq of the first port to come up is used for tracing.
4220 	 */
4221 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
4222 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
4223 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
4224 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
4225 		    V_QUEUENUMBER(sc->traceq));
4226 		pi->flags |= HAS_TRACEQ;
4227 	}
4228 
4229 	/* all ok */
4230 	PORT_LOCK(pi);
4231 	if (pi->up_vis++ == 0) {
4232 		t4_update_port_info(pi);
4233 		build_medialist(pi, &pi->media);
4234 		init_l1cfg(pi);
4235 	}
4236 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
4237 
4238 	if (pi->nvi > 1 || sc->flags & IS_VF)
4239 		callout_reset(&vi->tick, hz, vi_tick, vi);
4240 	else
4241 		callout_reset(&pi->tick, hz, cxgbe_tick, pi);
4242 	PORT_UNLOCK(pi);
4243 done:
4244 	if (rc != 0)
4245 		cxgbe_uninit_synchronized(vi);
4246 
4247 	return (rc);
4248 }
4249 
4250 /*
4251  * Idempotent.
4252  */
4253 static int
4254 cxgbe_uninit_synchronized(struct vi_info *vi)
4255 {
4256 	struct port_info *pi = vi->pi;
4257 	struct adapter *sc = pi->adapter;
4258 	struct ifnet *ifp = vi->ifp;
4259 	int rc, i;
4260 	struct sge_txq *txq;
4261 
4262 	ASSERT_SYNCHRONIZED_OP(sc);
4263 
4264 	if (!(vi->flags & VI_INIT_DONE)) {
4265 		KASSERT(!(ifp->if_drv_flags & IFF_DRV_RUNNING),
4266 		    ("uninited VI is running"));
4267 		return (0);
4268 	}
4269 
4270 	/*
4271 	 * Disable the VI so that all its data in either direction is discarded
4272 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
4273 	 * tick) intact as the TP can deliver negative advice or data that it's
4274 	 * holding in its RAM (for an offloaded connection) even after the VI is
4275 	 * disabled.
4276 	 */
4277 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
4278 	if (rc) {
4279 		if_printf(ifp, "disable_vi failed: %d\n", rc);
4280 		return (rc);
4281 	}
4282 
4283 	for_each_txq(vi, i, txq) {
4284 		TXQ_LOCK(txq);
4285 		txq->eq.flags &= ~EQ_ENABLED;
4286 		TXQ_UNLOCK(txq);
4287 	}
4288 
4289 	PORT_LOCK(pi);
4290 	if (pi->nvi > 1 || sc->flags & IS_VF)
4291 		callout_stop(&vi->tick);
4292 	else
4293 		callout_stop(&pi->tick);
4294 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
4295 		PORT_UNLOCK(pi);
4296 		return (0);
4297 	}
4298 	ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
4299 	pi->up_vis--;
4300 	if (pi->up_vis > 0) {
4301 		PORT_UNLOCK(pi);
4302 		return (0);
4303 	}
4304 	PORT_UNLOCK(pi);
4305 
4306 	pi->link_cfg.link_ok = 0;
4307 	pi->link_cfg.speed = 0;
4308 	pi->link_cfg.link_down_rc = 255;
4309 	t4_os_link_changed(pi);
4310 	pi->old_link_cfg = pi->link_cfg;
4311 
4312 	return (0);
4313 }
4314 
4315 /*
4316  * It is ok for this function to fail midway and return right away.  t4_detach
4317  * will walk the entire sc->irq list and clean up whatever is valid.
4318  */
4319 int
4320 t4_setup_intr_handlers(struct adapter *sc)
4321 {
4322 	int rc, rid, p, q, v;
4323 	char s[8];
4324 	struct irq *irq;
4325 	struct port_info *pi;
4326 	struct vi_info *vi;
4327 	struct sge *sge = &sc->sge;
4328 	struct sge_rxq *rxq;
4329 #ifdef TCP_OFFLOAD
4330 	struct sge_ofld_rxq *ofld_rxq;
4331 #endif
4332 #ifdef DEV_NETMAP
4333 	struct sge_nm_rxq *nm_rxq;
4334 #endif
4335 #ifdef RSS
4336 	int nbuckets = rss_getnumbuckets();
4337 #endif
4338 
4339 	/*
4340 	 * Setup interrupts.
4341 	 */
4342 	irq = &sc->irq[0];
4343 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
4344 	if (sc->intr_count == 1)
4345 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
4346 
4347 	/* Multiple interrupts. */
4348 	if (sc->flags & IS_VF)
4349 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
4350 		    ("%s: too few intr.", __func__));
4351 	else
4352 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
4353 		    ("%s: too few intr.", __func__));
4354 
4355 	/* The first one is always error intr on PFs */
4356 	if (!(sc->flags & IS_VF)) {
4357 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
4358 		if (rc != 0)
4359 			return (rc);
4360 		irq++;
4361 		rid++;
4362 	}
4363 
4364 	/* The second one is always the firmware event queue (first on VFs) */
4365 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
4366 	if (rc != 0)
4367 		return (rc);
4368 	irq++;
4369 	rid++;
4370 
4371 	for_each_port(sc, p) {
4372 		pi = sc->port[p];
4373 		for_each_vi(pi, v, vi) {
4374 			vi->first_intr = rid - 1;
4375 
4376 			if (vi->nnmrxq > 0) {
4377 				int n = max(vi->nrxq, vi->nnmrxq);
4378 
4379 				MPASS(vi->flags & INTR_RXQ);
4380 
4381 				rxq = &sge->rxq[vi->first_rxq];
4382 #ifdef DEV_NETMAP
4383 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
4384 #endif
4385 				for (q = 0; q < n; q++) {
4386 					snprintf(s, sizeof(s), "%x%c%x", p,
4387 					    'a' + v, q);
4388 					if (q < vi->nrxq)
4389 						irq->rxq = rxq++;
4390 #ifdef DEV_NETMAP
4391 					if (q < vi->nnmrxq)
4392 						irq->nm_rxq = nm_rxq++;
4393 #endif
4394 					rc = t4_alloc_irq(sc, irq, rid,
4395 					    t4_vi_intr, irq, s);
4396 					if (rc != 0)
4397 						return (rc);
4398 					irq++;
4399 					rid++;
4400 					vi->nintr++;
4401 				}
4402 			} else if (vi->flags & INTR_RXQ) {
4403 				for_each_rxq(vi, q, rxq) {
4404 					snprintf(s, sizeof(s), "%x%c%x", p,
4405 					    'a' + v, q);
4406 					rc = t4_alloc_irq(sc, irq, rid,
4407 					    t4_intr, rxq, s);
4408 					if (rc != 0)
4409 						return (rc);
4410 #ifdef RSS
4411 					bus_bind_intr(sc->dev, irq->res,
4412 					    rss_getcpu(q % nbuckets));
4413 #endif
4414 					irq++;
4415 					rid++;
4416 					vi->nintr++;
4417 				}
4418 			}
4419 #ifdef TCP_OFFLOAD
4420 			if (vi->flags & INTR_OFLD_RXQ) {
4421 				for_each_ofld_rxq(vi, q, ofld_rxq) {
4422 					snprintf(s, sizeof(s), "%x%c%x", p,
4423 					    'A' + v, q);
4424 					rc = t4_alloc_irq(sc, irq, rid,
4425 					    t4_intr, ofld_rxq, s);
4426 					if (rc != 0)
4427 						return (rc);
4428 					irq++;
4429 					rid++;
4430 					vi->nintr++;
4431 				}
4432 			}
4433 #endif
4434 		}
4435 	}
4436 	MPASS(irq == &sc->irq[sc->intr_count]);
4437 
4438 	return (0);
4439 }
4440 
4441 int
4442 adapter_full_init(struct adapter *sc)
4443 {
4444 	int rc, i;
4445 #ifdef RSS
4446 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4447 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
4448 #endif
4449 
4450 	ASSERT_SYNCHRONIZED_OP(sc);
4451 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4452 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
4453 	    ("%s: FULL_INIT_DONE already", __func__));
4454 
4455 	/*
4456 	 * queues that belong to the adapter (not any particular port).
4457 	 */
4458 	rc = t4_setup_adapter_queues(sc);
4459 	if (rc != 0)
4460 		goto done;
4461 
4462 	for (i = 0; i < nitems(sc->tq); i++) {
4463 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
4464 		    taskqueue_thread_enqueue, &sc->tq[i]);
4465 		if (sc->tq[i] == NULL) {
4466 			device_printf(sc->dev,
4467 			    "failed to allocate task queue %d\n", i);
4468 			rc = ENOMEM;
4469 			goto done;
4470 		}
4471 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
4472 		    device_get_nameunit(sc->dev), i);
4473 	}
4474 #ifdef RSS
4475 	MPASS(RSS_KEYSIZE == 40);
4476 	rss_getkey((void *)&raw_rss_key[0]);
4477 	for (i = 0; i < nitems(rss_key); i++) {
4478 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
4479 	}
4480 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
4481 #endif
4482 
4483 	if (!(sc->flags & IS_VF))
4484 		t4_intr_enable(sc);
4485 	sc->flags |= FULL_INIT_DONE;
4486 done:
4487 	if (rc != 0)
4488 		adapter_full_uninit(sc);
4489 
4490 	return (rc);
4491 }
4492 
4493 int
4494 adapter_full_uninit(struct adapter *sc)
4495 {
4496 	int i;
4497 
4498 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
4499 
4500 	t4_teardown_adapter_queues(sc);
4501 
4502 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
4503 		taskqueue_free(sc->tq[i]);
4504 		sc->tq[i] = NULL;
4505 	}
4506 
4507 	sc->flags &= ~FULL_INIT_DONE;
4508 
4509 	return (0);
4510 }
4511 
4512 #ifdef RSS
4513 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
4514     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
4515     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
4516     RSS_HASHTYPE_RSS_UDP_IPV6)
4517 
4518 /* Translates kernel hash types to hardware. */
4519 static int
4520 hashconfig_to_hashen(int hashconfig)
4521 {
4522 	int hashen = 0;
4523 
4524 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
4525 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
4526 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
4527 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
4528 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
4529 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4530 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4531 	}
4532 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
4533 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
4534 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4535 	}
4536 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
4537 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
4538 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
4539 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
4540 
4541 	return (hashen);
4542 }
4543 
4544 /* Translates hardware hash types to kernel. */
4545 static int
4546 hashen_to_hashconfig(int hashen)
4547 {
4548 	int hashconfig = 0;
4549 
4550 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
4551 		/*
4552 		 * If UDP hashing was enabled it must have been enabled for
4553 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
4554 		 * enabling any 4-tuple hash is nonsense configuration.
4555 		 */
4556 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4557 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
4558 
4559 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4560 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
4561 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4562 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
4563 	}
4564 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
4565 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
4566 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
4567 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
4568 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
4569 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
4570 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
4571 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
4572 
4573 	return (hashconfig);
4574 }
4575 #endif
4576 
4577 int
4578 vi_full_init(struct vi_info *vi)
4579 {
4580 	struct adapter *sc = vi->pi->adapter;
4581 	struct ifnet *ifp = vi->ifp;
4582 	uint16_t *rss;
4583 	struct sge_rxq *rxq;
4584 	int rc, i, j, hashen;
4585 #ifdef RSS
4586 	int nbuckets = rss_getnumbuckets();
4587 	int hashconfig = rss_gethashconfig();
4588 	int extra;
4589 #endif
4590 
4591 	ASSERT_SYNCHRONIZED_OP(sc);
4592 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
4593 	    ("%s: VI_INIT_DONE already", __func__));
4594 
4595 	sysctl_ctx_init(&vi->ctx);
4596 	vi->flags |= VI_SYSCTL_CTX;
4597 
4598 	/*
4599 	 * Allocate tx/rx/fl queues for this VI.
4600 	 */
4601 	rc = t4_setup_vi_queues(vi);
4602 	if (rc != 0)
4603 		goto done;	/* error message displayed already */
4604 
4605 	/*
4606 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
4607 	 */
4608 	if (vi->nrxq > vi->rss_size) {
4609 		if_printf(ifp, "nrxq (%d) > hw RSS table size (%d); "
4610 		    "some queues will never receive traffic.\n", vi->nrxq,
4611 		    vi->rss_size);
4612 	} else if (vi->rss_size % vi->nrxq) {
4613 		if_printf(ifp, "nrxq (%d), hw RSS table size (%d); "
4614 		    "expect uneven traffic distribution.\n", vi->nrxq,
4615 		    vi->rss_size);
4616 	}
4617 #ifdef RSS
4618 	if (vi->nrxq != nbuckets) {
4619 		if_printf(ifp, "nrxq (%d) != kernel RSS buckets (%d);"
4620 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
4621 	}
4622 #endif
4623 	rss = malloc(vi->rss_size * sizeof (*rss), M_CXGBE, M_ZERO | M_WAITOK);
4624 	for (i = 0; i < vi->rss_size;) {
4625 #ifdef RSS
4626 		j = rss_get_indirection_to_bucket(i);
4627 		j %= vi->nrxq;
4628 		rxq = &sc->sge.rxq[vi->first_rxq + j];
4629 		rss[i++] = rxq->iq.abs_id;
4630 #else
4631 		for_each_rxq(vi, j, rxq) {
4632 			rss[i++] = rxq->iq.abs_id;
4633 			if (i == vi->rss_size)
4634 				break;
4635 		}
4636 #endif
4637 	}
4638 
4639 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size, rss,
4640 	    vi->rss_size);
4641 	if (rc != 0) {
4642 		if_printf(ifp, "rss_config failed: %d\n", rc);
4643 		goto done;
4644 	}
4645 
4646 #ifdef RSS
4647 	hashen = hashconfig_to_hashen(hashconfig);
4648 
4649 	/*
4650 	 * We may have had to enable some hashes even though the global config
4651 	 * wants them disabled.  This is a potential problem that must be
4652 	 * reported to the user.
4653 	 */
4654 	extra = hashen_to_hashconfig(hashen) ^ hashconfig;
4655 
4656 	/*
4657 	 * If we consider only the supported hash types, then the enabled hashes
4658 	 * are a superset of the requested hashes.  In other words, there cannot
4659 	 * be any supported hash that was requested but not enabled, but there
4660 	 * can be hashes that were not requested but had to be enabled.
4661 	 */
4662 	extra &= SUPPORTED_RSS_HASHTYPES;
4663 	MPASS((extra & hashconfig) == 0);
4664 
4665 	if (extra) {
4666 		if_printf(ifp,
4667 		    "global RSS config (0x%x) cannot be accommodated.\n",
4668 		    hashconfig);
4669 	}
4670 	if (extra & RSS_HASHTYPE_RSS_IPV4)
4671 		if_printf(ifp, "IPv4 2-tuple hashing forced on.\n");
4672 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
4673 		if_printf(ifp, "TCP/IPv4 4-tuple hashing forced on.\n");
4674 	if (extra & RSS_HASHTYPE_RSS_IPV6)
4675 		if_printf(ifp, "IPv6 2-tuple hashing forced on.\n");
4676 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
4677 		if_printf(ifp, "TCP/IPv6 4-tuple hashing forced on.\n");
4678 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
4679 		if_printf(ifp, "UDP/IPv4 4-tuple hashing forced on.\n");
4680 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
4681 		if_printf(ifp, "UDP/IPv6 4-tuple hashing forced on.\n");
4682 #else
4683 	hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
4684 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
4685 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
4686 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
4687 #endif
4688 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, hashen, rss[0], 0, 0);
4689 	if (rc != 0) {
4690 		if_printf(ifp, "rss hash/defaultq config failed: %d\n", rc);
4691 		goto done;
4692 	}
4693 
4694 	vi->rss = rss;
4695 	vi->flags |= VI_INIT_DONE;
4696 done:
4697 	if (rc != 0)
4698 		vi_full_uninit(vi);
4699 
4700 	return (rc);
4701 }
4702 
4703 /*
4704  * Idempotent.
4705  */
4706 int
4707 vi_full_uninit(struct vi_info *vi)
4708 {
4709 	struct port_info *pi = vi->pi;
4710 	struct adapter *sc = pi->adapter;
4711 	int i;
4712 	struct sge_rxq *rxq;
4713 	struct sge_txq *txq;
4714 #ifdef TCP_OFFLOAD
4715 	struct sge_ofld_rxq *ofld_rxq;
4716 	struct sge_wrq *ofld_txq;
4717 #endif
4718 
4719 	if (vi->flags & VI_INIT_DONE) {
4720 
4721 		/* Need to quiesce queues.  */
4722 
4723 		/* XXX: Only for the first VI? */
4724 		if (IS_MAIN_VI(vi) && !(sc->flags & IS_VF))
4725 			quiesce_wrq(sc, &sc->sge.ctrlq[pi->port_id]);
4726 
4727 		for_each_txq(vi, i, txq) {
4728 			quiesce_txq(sc, txq);
4729 		}
4730 
4731 #ifdef TCP_OFFLOAD
4732 		for_each_ofld_txq(vi, i, ofld_txq) {
4733 			quiesce_wrq(sc, ofld_txq);
4734 		}
4735 #endif
4736 
4737 		for_each_rxq(vi, i, rxq) {
4738 			quiesce_iq(sc, &rxq->iq);
4739 			quiesce_fl(sc, &rxq->fl);
4740 		}
4741 
4742 #ifdef TCP_OFFLOAD
4743 		for_each_ofld_rxq(vi, i, ofld_rxq) {
4744 			quiesce_iq(sc, &ofld_rxq->iq);
4745 			quiesce_fl(sc, &ofld_rxq->fl);
4746 		}
4747 #endif
4748 		free(vi->rss, M_CXGBE);
4749 		free(vi->nm_rss, M_CXGBE);
4750 	}
4751 
4752 	t4_teardown_vi_queues(vi);
4753 	vi->flags &= ~VI_INIT_DONE;
4754 
4755 	return (0);
4756 }
4757 
4758 static void
4759 quiesce_txq(struct adapter *sc, struct sge_txq *txq)
4760 {
4761 	struct sge_eq *eq = &txq->eq;
4762 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
4763 
4764 	(void) sc;	/* unused */
4765 
4766 #ifdef INVARIANTS
4767 	TXQ_LOCK(txq);
4768 	MPASS((eq->flags & EQ_ENABLED) == 0);
4769 	TXQ_UNLOCK(txq);
4770 #endif
4771 
4772 	/* Wait for the mp_ring to empty. */
4773 	while (!mp_ring_is_idle(txq->r)) {
4774 		mp_ring_check_drainage(txq->r, 0);
4775 		pause("rquiesce", 1);
4776 	}
4777 
4778 	/* Then wait for the hardware to finish. */
4779 	while (spg->cidx != htobe16(eq->pidx))
4780 		pause("equiesce", 1);
4781 
4782 	/* Finally, wait for the driver to reclaim all descriptors. */
4783 	while (eq->cidx != eq->pidx)
4784 		pause("dquiesce", 1);
4785 }
4786 
4787 static void
4788 quiesce_wrq(struct adapter *sc, struct sge_wrq *wrq)
4789 {
4790 
4791 	/* XXXTX */
4792 }
4793 
4794 static void
4795 quiesce_iq(struct adapter *sc, struct sge_iq *iq)
4796 {
4797 	(void) sc;	/* unused */
4798 
4799 	/* Synchronize with the interrupt handler */
4800 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
4801 		pause("iqfree", 1);
4802 }
4803 
4804 static void
4805 quiesce_fl(struct adapter *sc, struct sge_fl *fl)
4806 {
4807 	mtx_lock(&sc->sfl_lock);
4808 	FL_LOCK(fl);
4809 	fl->flags |= FL_DOOMED;
4810 	FL_UNLOCK(fl);
4811 	callout_stop(&sc->sfl_callout);
4812 	mtx_unlock(&sc->sfl_lock);
4813 
4814 	KASSERT((fl->flags & FL_STARVING) == 0,
4815 	    ("%s: still starving", __func__));
4816 }
4817 
4818 static int
4819 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
4820     driver_intr_t *handler, void *arg, char *name)
4821 {
4822 	int rc;
4823 
4824 	irq->rid = rid;
4825 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
4826 	    RF_SHAREABLE | RF_ACTIVE);
4827 	if (irq->res == NULL) {
4828 		device_printf(sc->dev,
4829 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
4830 		return (ENOMEM);
4831 	}
4832 
4833 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
4834 	    NULL, handler, arg, &irq->tag);
4835 	if (rc != 0) {
4836 		device_printf(sc->dev,
4837 		    "failed to setup interrupt for rid %d, name %s: %d\n",
4838 		    rid, name, rc);
4839 	} else if (name)
4840 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
4841 
4842 	return (rc);
4843 }
4844 
4845 static int
4846 t4_free_irq(struct adapter *sc, struct irq *irq)
4847 {
4848 	if (irq->tag)
4849 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
4850 	if (irq->res)
4851 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
4852 
4853 	bzero(irq, sizeof(*irq));
4854 
4855 	return (0);
4856 }
4857 
4858 static void
4859 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
4860 {
4861 
4862 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
4863 	t4_get_regs(sc, buf, regs->len);
4864 }
4865 
4866 #define	A_PL_INDIR_CMD	0x1f8
4867 
4868 #define	S_PL_AUTOINC	31
4869 #define	M_PL_AUTOINC	0x1U
4870 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
4871 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
4872 
4873 #define	S_PL_VFID	20
4874 #define	M_PL_VFID	0xffU
4875 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
4876 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
4877 
4878 #define	S_PL_ADDR	0
4879 #define	M_PL_ADDR	0xfffffU
4880 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
4881 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
4882 
4883 #define	A_PL_INDIR_DATA	0x1fc
4884 
4885 static uint64_t
4886 read_vf_stat(struct adapter *sc, unsigned int viid, int reg)
4887 {
4888 	u32 stats[2];
4889 
4890 	mtx_assert(&sc->reg_lock, MA_OWNED);
4891 	if (sc->flags & IS_VF) {
4892 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
4893 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
4894 	} else {
4895 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4896 		    V_PL_VFID(G_FW_VIID_VIN(viid)) |
4897 		    V_PL_ADDR(VF_MPS_REG(reg)));
4898 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
4899 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
4900 	}
4901 	return (((uint64_t)stats[1]) << 32 | stats[0]);
4902 }
4903 
4904 static void
4905 t4_get_vi_stats(struct adapter *sc, unsigned int viid,
4906     struct fw_vi_stats_vf *stats)
4907 {
4908 
4909 #define GET_STAT(name) \
4910 	read_vf_stat(sc, viid, A_MPS_VF_STAT_##name##_L)
4911 
4912 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
4913 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
4914 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
4915 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
4916 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
4917 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
4918 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
4919 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
4920 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
4921 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
4922 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
4923 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
4924 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
4925 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
4926 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
4927 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
4928 
4929 #undef GET_STAT
4930 }
4931 
4932 static void
4933 t4_clr_vi_stats(struct adapter *sc, unsigned int viid)
4934 {
4935 	int reg;
4936 
4937 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
4938 	    V_PL_VFID(G_FW_VIID_VIN(viid)) |
4939 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
4940 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
4941 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
4942 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
4943 }
4944 
4945 static void
4946 vi_refresh_stats(struct adapter *sc, struct vi_info *vi)
4947 {
4948 	struct timeval tv;
4949 	const struct timeval interval = {0, 250000};	/* 250ms */
4950 
4951 	if (!(vi->flags & VI_INIT_DONE))
4952 		return;
4953 
4954 	getmicrotime(&tv);
4955 	timevalsub(&tv, &interval);
4956 	if (timevalcmp(&tv, &vi->last_refreshed, <))
4957 		return;
4958 
4959 	mtx_lock(&sc->reg_lock);
4960 	t4_get_vi_stats(sc, vi->viid, &vi->stats);
4961 	getmicrotime(&vi->last_refreshed);
4962 	mtx_unlock(&sc->reg_lock);
4963 }
4964 
4965 static void
4966 cxgbe_refresh_stats(struct adapter *sc, struct port_info *pi)
4967 {
4968 	u_int i, v, tnl_cong_drops, bg_map;
4969 	struct timeval tv;
4970 	const struct timeval interval = {0, 250000};	/* 250ms */
4971 
4972 	getmicrotime(&tv);
4973 	timevalsub(&tv, &interval);
4974 	if (timevalcmp(&tv, &pi->last_refreshed, <))
4975 		return;
4976 
4977 	tnl_cong_drops = 0;
4978 	t4_get_port_stats(sc, pi->tx_chan, &pi->stats);
4979 	bg_map = pi->mps_bg_map;
4980 	while (bg_map) {
4981 		i = ffs(bg_map) - 1;
4982 		mtx_lock(&sc->reg_lock);
4983 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
4984 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
4985 		mtx_unlock(&sc->reg_lock);
4986 		tnl_cong_drops += v;
4987 		bg_map &= ~(1 << i);
4988 	}
4989 	pi->tnl_cong_drops = tnl_cong_drops;
4990 	getmicrotime(&pi->last_refreshed);
4991 }
4992 
4993 static void
4994 cxgbe_tick(void *arg)
4995 {
4996 	struct port_info *pi = arg;
4997 	struct adapter *sc = pi->adapter;
4998 
4999 	PORT_LOCK_ASSERT_OWNED(pi);
5000 	cxgbe_refresh_stats(sc, pi);
5001 
5002 	callout_schedule(&pi->tick, hz);
5003 }
5004 
5005 void
5006 vi_tick(void *arg)
5007 {
5008 	struct vi_info *vi = arg;
5009 	struct adapter *sc = vi->pi->adapter;
5010 
5011 	vi_refresh_stats(sc, vi);
5012 
5013 	callout_schedule(&vi->tick, hz);
5014 }
5015 
5016 static void
5017 cxgbe_vlan_config(void *arg, struct ifnet *ifp, uint16_t vid)
5018 {
5019 	struct ifnet *vlan;
5020 
5021 	if (arg != ifp || ifp->if_type != IFT_ETHER)
5022 		return;
5023 
5024 	vlan = VLAN_DEVAT(ifp, vid);
5025 	VLAN_SETCOOKIE(vlan, ifp);
5026 }
5027 
5028 /*
5029  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
5030  */
5031 static char *caps_decoder[] = {
5032 	"\20\001IPMI\002NCSI",				/* 0: NBM */
5033 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
5034 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
5035 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
5036 	    "\006HASHFILTER\007ETHOFLD",
5037 	"\20\001TOE",					/* 4: TOE */
5038 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
5039 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
5040 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
5041 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
5042 	    "\007T10DIF"
5043 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
5044 	"\20\001LOOKASIDE\002TLSKEYS",			/* 7: Crypto */
5045 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
5046 		    "\004PO_INITIATOR\005PO_TARGET",
5047 };
5048 
5049 void
5050 t4_sysctls(struct adapter *sc)
5051 {
5052 	struct sysctl_ctx_list *ctx;
5053 	struct sysctl_oid *oid;
5054 	struct sysctl_oid_list *children, *c0;
5055 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
5056 
5057 	ctx = device_get_sysctl_ctx(sc->dev);
5058 
5059 	/*
5060 	 * dev.t4nex.X.
5061 	 */
5062 	oid = device_get_sysctl_tree(sc->dev);
5063 	c0 = children = SYSCTL_CHILDREN(oid);
5064 
5065 	sc->sc_do_rxcopy = 1;
5066 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
5067 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
5068 
5069 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
5070 	    sc->params.nports, "# of ports");
5071 
5072 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
5073 	    CTLTYPE_STRING | CTLFLAG_RD, doorbells, sc->doorbells,
5074 	    sysctl_bitfield, "A", "available doorbells");
5075 
5076 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
5077 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
5078 
5079 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
5080 	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.timer_val,
5081 	    sizeof(sc->params.sge.timer_val), sysctl_int_array, "A",
5082 	    "interrupt holdoff timer values (us)");
5083 
5084 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
5085 	    CTLTYPE_STRING | CTLFLAG_RD, sc->params.sge.counter_val,
5086 	    sizeof(sc->params.sge.counter_val), sysctl_int_array, "A",
5087 	    "interrupt holdoff packet counter values");
5088 
5089 	t4_sge_sysctls(sc, ctx, children);
5090 
5091 	sc->lro_timeout = 100;
5092 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
5093 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
5094 
5095 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
5096 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
5097 
5098 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
5099 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
5100 
5101 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
5102 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
5103 
5104 	if (sc->flags & IS_VF)
5105 		return;
5106 
5107 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
5108 	    NULL, chip_rev(sc), "chip hardware revision");
5109 
5110 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
5111 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
5112 
5113 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
5114 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
5115 
5116 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
5117 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
5118 
5119 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
5120 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
5121 
5122 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
5123 	    sc->er_version, 0, "expansion ROM version");
5124 
5125 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
5126 	    sc->bs_version, 0, "bootstrap firmware version");
5127 
5128 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
5129 	    NULL, sc->params.scfg_vers, "serial config version");
5130 
5131 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
5132 	    NULL, sc->params.vpd_vers, "VPD version");
5133 
5134 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
5135 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
5136 
5137 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
5138 	    sc->cfcsum, "config file checksum");
5139 
5140 #define SYSCTL_CAP(name, n, text) \
5141 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
5142 	    CTLTYPE_STRING | CTLFLAG_RD, caps_decoder[n], sc->name, \
5143 	    sysctl_bitfield, "A", "available " text " capabilities")
5144 
5145 	SYSCTL_CAP(nbmcaps, 0, "NBM");
5146 	SYSCTL_CAP(linkcaps, 1, "link");
5147 	SYSCTL_CAP(switchcaps, 2, "switch");
5148 	SYSCTL_CAP(niccaps, 3, "NIC");
5149 	SYSCTL_CAP(toecaps, 4, "TCP offload");
5150 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
5151 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
5152 	SYSCTL_CAP(cryptocaps, 7, "crypto");
5153 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
5154 #undef SYSCTL_CAP
5155 
5156 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
5157 	    NULL, sc->tids.nftids, "number of filters");
5158 
5159 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature", CTLTYPE_INT |
5160 	    CTLFLAG_RD, sc, 0, sysctl_temperature, "I",
5161 	    "chip temperature (in Celsius)");
5162 
5163 #ifdef SBUF_DRAIN
5164 	/*
5165 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
5166 	 */
5167 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
5168 	    CTLFLAG_RD | CTLFLAG_SKIP, NULL,
5169 	    "logs and miscellaneous information");
5170 	children = SYSCTL_CHILDREN(oid);
5171 
5172 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
5173 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5174 	    sysctl_cctrl, "A", "congestion control");
5175 
5176 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
5177 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5178 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
5179 
5180 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
5181 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1,
5182 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
5183 
5184 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
5185 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2,
5186 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
5187 
5188 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
5189 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3,
5190 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
5191 
5192 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
5193 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4,
5194 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
5195 
5196 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
5197 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5,
5198 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
5199 
5200 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
5201 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5202 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_cim_la : sysctl_cim_la_t6,
5203 	    "A", "CIM logic analyzer");
5204 
5205 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
5206 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5207 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
5208 
5209 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
5210 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0 + CIM_NUM_IBQ,
5211 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
5212 
5213 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
5214 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 1 + CIM_NUM_IBQ,
5215 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
5216 
5217 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
5218 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 2 + CIM_NUM_IBQ,
5219 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
5220 
5221 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
5222 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 3 + CIM_NUM_IBQ,
5223 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
5224 
5225 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
5226 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 4 + CIM_NUM_IBQ,
5227 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
5228 
5229 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
5230 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 5 + CIM_NUM_IBQ,
5231 	    sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
5232 
5233 	if (chip_id(sc) > CHELSIO_T4) {
5234 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
5235 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 6 + CIM_NUM_IBQ,
5236 		    sysctl_cim_ibq_obq, "A", "CIM OBQ 6 (SGE0-RX)");
5237 
5238 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
5239 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 7 + CIM_NUM_IBQ,
5240 		    sysctl_cim_ibq_obq, "A", "CIM OBQ 7 (SGE1-RX)");
5241 	}
5242 
5243 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
5244 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5245 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
5246 
5247 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
5248 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5249 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
5250 
5251 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
5252 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5253 	    sysctl_cpl_stats, "A", "CPL statistics");
5254 
5255 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
5256 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5257 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
5258 
5259 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
5260 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5261 	    sysctl_devlog, "A", "firmware's device log");
5262 
5263 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
5264 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5265 	    sysctl_fcoe_stats, "A", "FCoE statistics");
5266 
5267 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
5268 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5269 	    sysctl_hw_sched, "A", "hardware scheduler ");
5270 
5271 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
5272 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5273 	    sysctl_l2t, "A", "hardware L2 table");
5274 
5275 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
5276 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5277 	    sysctl_lb_stats, "A", "loopback statistics");
5278 
5279 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
5280 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5281 	    sysctl_meminfo, "A", "memory regions");
5282 
5283 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
5284 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5285 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
5286 	    "A", "MPS TCAM entries");
5287 
5288 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
5289 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5290 	    sysctl_path_mtus, "A", "path MTUs");
5291 
5292 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
5293 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5294 	    sysctl_pm_stats, "A", "PM statistics");
5295 
5296 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
5297 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5298 	    sysctl_rdma_stats, "A", "RDMA statistics");
5299 
5300 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
5301 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5302 	    sysctl_tcp_stats, "A", "TCP statistics");
5303 
5304 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
5305 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5306 	    sysctl_tids, "A", "TID information");
5307 
5308 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
5309 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5310 	    sysctl_tp_err_stats, "A", "TP error statistics");
5311 
5312 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
5313 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_tp_la_mask, "I",
5314 	    "TP logic analyzer event capture mask");
5315 
5316 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
5317 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5318 	    sysctl_tp_la, "A", "TP logic analyzer");
5319 
5320 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
5321 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5322 	    sysctl_tx_rate, "A", "Tx rate");
5323 
5324 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
5325 	    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5326 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
5327 
5328 	if (chip_id(sc) >= CHELSIO_T5) {
5329 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
5330 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0,
5331 		    sysctl_wcwr_stats, "A", "write combined work requests");
5332 	}
5333 #endif
5334 
5335 #ifdef TCP_OFFLOAD
5336 	if (is_offload(sc)) {
5337 		int i;
5338 		char s[4];
5339 
5340 		/*
5341 		 * dev.t4nex.X.toe.
5342 		 */
5343 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe", CTLFLAG_RD,
5344 		    NULL, "TOE parameters");
5345 		children = SYSCTL_CHILDREN(oid);
5346 
5347 		sc->tt.cong_algorithm = -1;
5348 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
5349 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
5350 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
5351 		    "3 = highspeed)");
5352 
5353 		sc->tt.sndbuf = 256 * 1024;
5354 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
5355 		    &sc->tt.sndbuf, 0, "max hardware send buffer size");
5356 
5357 		sc->tt.ddp = 0;
5358 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp", CTLFLAG_RW,
5359 		    &sc->tt.ddp, 0, "DDP allowed");
5360 
5361 		sc->tt.rx_coalesce = 1;
5362 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
5363 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
5364 
5365 		sc->tt.tx_align = 1;
5366 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
5367 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
5368 
5369 		sc->tt.tx_zcopy = 0;
5370 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
5371 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
5372 		    "Enable zero-copy aio_write(2)");
5373 
5374 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
5375 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 0, sysctl_tp_tick, "A",
5376 		    "TP timer tick (us)");
5377 
5378 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
5379 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 1, sysctl_tp_tick, "A",
5380 		    "TCP timestamp tick (us)");
5381 
5382 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
5383 		    CTLTYPE_STRING | CTLFLAG_RD, sc, 2, sysctl_tp_tick, "A",
5384 		    "DACK tick (us)");
5385 
5386 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
5387 		    CTLTYPE_UINT | CTLFLAG_RD, sc, 0, sysctl_tp_dack_timer,
5388 		    "IU", "DACK timer (us)");
5389 
5390 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
5391 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MIN,
5392 		    sysctl_tp_timer, "LU", "Minimum retransmit interval (us)");
5393 
5394 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
5395 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_RXT_MAX,
5396 		    sysctl_tp_timer, "LU", "Maximum retransmit interval (us)");
5397 
5398 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
5399 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MIN,
5400 		    sysctl_tp_timer, "LU", "Persist timer min (us)");
5401 
5402 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
5403 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_PERS_MAX,
5404 		    sysctl_tp_timer, "LU", "Persist timer max (us)");
5405 
5406 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
5407 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_IDLE,
5408 		    sysctl_tp_timer, "LU", "Keepalive idle timer (us)");
5409 
5410 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
5411 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_KEEP_INTVL,
5412 		    sysctl_tp_timer, "LU", "Keepalive interval timer (us)");
5413 
5414 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
5415 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_INIT_SRTT,
5416 		    sysctl_tp_timer, "LU", "Initial SRTT (us)");
5417 
5418 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
5419 		    CTLTYPE_ULONG | CTLFLAG_RD, sc, A_TP_FINWAIT2_TIMER,
5420 		    sysctl_tp_timer, "LU", "FINWAIT2 timer (us)");
5421 
5422 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
5423 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_SYNSHIFTMAX,
5424 		    sysctl_tp_shift_cnt, "IU",
5425 		    "Number of SYN retransmissions before abort");
5426 
5427 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
5428 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_RXTSHIFTMAXR2,
5429 		    sysctl_tp_shift_cnt, "IU",
5430 		    "Number of retransmissions before abort");
5431 
5432 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
5433 		    CTLTYPE_UINT | CTLFLAG_RD, sc, S_KEEPALIVEMAXR2,
5434 		    sysctl_tp_shift_cnt, "IU",
5435 		    "Number of keepalive probes before abort");
5436 
5437 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
5438 		    CTLFLAG_RD, NULL, "TOE retransmit backoffs");
5439 		children = SYSCTL_CHILDREN(oid);
5440 		for (i = 0; i < 16; i++) {
5441 			snprintf(s, sizeof(s), "%u", i);
5442 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
5443 			    CTLTYPE_UINT | CTLFLAG_RD, sc, i, sysctl_tp_backoff,
5444 			    "IU", "TOE retransmit backoff");
5445 		}
5446 	}
5447 #endif
5448 }
5449 
5450 void
5451 vi_sysctls(struct vi_info *vi)
5452 {
5453 	struct sysctl_ctx_list *ctx;
5454 	struct sysctl_oid *oid;
5455 	struct sysctl_oid_list *children;
5456 
5457 	ctx = device_get_sysctl_ctx(vi->dev);
5458 
5459 	/*
5460 	 * dev.v?(cxgbe|cxl).X.
5461 	 */
5462 	oid = device_get_sysctl_tree(vi->dev);
5463 	children = SYSCTL_CHILDREN(oid);
5464 
5465 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
5466 	    vi->viid, "VI identifer");
5467 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
5468 	    &vi->nrxq, 0, "# of rx queues");
5469 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
5470 	    &vi->ntxq, 0, "# of tx queues");
5471 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
5472 	    &vi->first_rxq, 0, "index of first rx queue");
5473 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
5474 	    &vi->first_txq, 0, "index of first tx queue");
5475 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
5476 	    vi->rss_size, "size of RSS indirection table");
5477 
5478 	if (IS_MAIN_VI(vi)) {
5479 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
5480 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_noflowq, "IU",
5481 		    "Reserve queue 0 for non-flowid packets");
5482 	}
5483 
5484 #ifdef TCP_OFFLOAD
5485 	if (vi->nofldrxq != 0) {
5486 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
5487 		    &vi->nofldrxq, 0,
5488 		    "# of rx queues for offloaded TCP connections");
5489 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
5490 		    &vi->nofldtxq, 0,
5491 		    "# of tx queues for offloaded TCP connections");
5492 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
5493 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
5494 		    "index of first TOE rx queue");
5495 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
5496 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
5497 		    "index of first TOE tx queue");
5498 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
5499 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0,
5500 		    sysctl_holdoff_tmr_idx_ofld, "I",
5501 		    "holdoff timer index for TOE queues");
5502 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
5503 		    CTLTYPE_INT | CTLFLAG_RW, vi, 0,
5504 		    sysctl_holdoff_pktc_idx_ofld, "I",
5505 		    "holdoff packet counter index for TOE queues");
5506 	}
5507 #endif
5508 #ifdef DEV_NETMAP
5509 	if (vi->nnmrxq != 0) {
5510 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
5511 		    &vi->nnmrxq, 0, "# of netmap rx queues");
5512 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
5513 		    &vi->nnmtxq, 0, "# of netmap tx queues");
5514 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
5515 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
5516 		    "index of first netmap rx queue");
5517 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
5518 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
5519 		    "index of first netmap tx queue");
5520 	}
5521 #endif
5522 
5523 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
5524 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_tmr_idx, "I",
5525 	    "holdoff timer index");
5526 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
5527 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_holdoff_pktc_idx, "I",
5528 	    "holdoff packet counter index");
5529 
5530 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
5531 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_rxq, "I",
5532 	    "rx queue size");
5533 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
5534 	    CTLTYPE_INT | CTLFLAG_RW, vi, 0, sysctl_qsize_txq, "I",
5535 	    "tx queue size");
5536 }
5537 
5538 static void
5539 cxgbe_sysctls(struct port_info *pi)
5540 {
5541 	struct sysctl_ctx_list *ctx;
5542 	struct sysctl_oid *oid;
5543 	struct sysctl_oid_list *children, *children2;
5544 	struct adapter *sc = pi->adapter;
5545 	int i;
5546 	char name[16];
5547 
5548 	ctx = device_get_sysctl_ctx(pi->dev);
5549 
5550 	/*
5551 	 * dev.cxgbe.X.
5552 	 */
5553 	oid = device_get_sysctl_tree(pi->dev);
5554 	children = SYSCTL_CHILDREN(oid);
5555 
5556 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc", CTLTYPE_STRING |
5557 	   CTLFLAG_RD, pi, 0, sysctl_linkdnrc, "A", "reason why link is down");
5558 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
5559 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
5560 		    CTLTYPE_INT | CTLFLAG_RD, pi, 0, sysctl_btphy, "I",
5561 		    "PHY temperature (in Celsius)");
5562 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
5563 		    CTLTYPE_INT | CTLFLAG_RD, pi, 1, sysctl_btphy, "I",
5564 		    "PHY firmware version");
5565 	}
5566 
5567 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
5568 	    CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_pause_settings, "A",
5569 	    "PAUSE settings (bit 0 = rx_pause, bit 1 = tx_pause)");
5570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fec",
5571 	    CTLTYPE_STRING | CTLFLAG_RW, pi, 0, sysctl_fec, "A",
5572 	    "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
5573 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
5574 	    CTLTYPE_INT | CTLFLAG_RW, pi, 0, sysctl_autoneg, "I",
5575 	    "autonegotiation (-1 = not supported)");
5576 
5577 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
5578 	    port_top_speed(pi), "max speed (in Gbps)");
5579 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
5580 	    pi->mps_bg_map, "MPS buffer group map");
5581 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
5582 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
5583 
5584 	if (sc->flags & IS_VF)
5585 		return;
5586 
5587 	/*
5588 	 * dev.(cxgbe|cxl).X.tc.
5589 	 */
5590 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc", CTLFLAG_RD, NULL,
5591 	    "Tx scheduler traffic classes (cl_rl)");
5592 	for (i = 0; i < sc->chip_params->nsched_cls; i++) {
5593 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
5594 
5595 		snprintf(name, sizeof(name), "%d", i);
5596 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
5597 		    SYSCTL_CHILDREN(oid), OID_AUTO, name, CTLFLAG_RD, NULL,
5598 		    "traffic class"));
5599 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "flags", CTLFLAG_RD,
5600 		    &tc->flags, 0, "flags");
5601 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
5602 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
5603 #ifdef SBUF_DRAIN
5604 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
5605 		    CTLTYPE_STRING | CTLFLAG_RD, sc, (pi->port_id << 16) | i,
5606 		    sysctl_tc_params, "A", "traffic class parameters");
5607 #endif
5608 	}
5609 
5610 	/*
5611 	 * dev.cxgbe.X.stats.
5612 	 */
5613 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats", CTLFLAG_RD,
5614 	    NULL, "port statistics");
5615 	children = SYSCTL_CHILDREN(oid);
5616 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
5617 	    &pi->tx_parse_error, 0,
5618 	    "# of tx packets with invalid length or # of segments");
5619 
5620 #define SYSCTL_ADD_T4_REG64(pi, name, desc, reg) \
5621 	SYSCTL_ADD_OID(ctx, children, OID_AUTO, name, \
5622 	    CTLTYPE_U64 | CTLFLAG_RD, sc, reg, \
5623 	    sysctl_handle_t4_reg64, "QU", desc)
5624 
5625 	SYSCTL_ADD_T4_REG64(pi, "tx_octets", "# of octets in good frames",
5626 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BYTES_L));
5627 	SYSCTL_ADD_T4_REG64(pi, "tx_frames", "total # of good frames",
5628 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_FRAMES_L));
5629 	SYSCTL_ADD_T4_REG64(pi, "tx_bcast_frames", "# of broadcast frames",
5630 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_BCAST_L));
5631 	SYSCTL_ADD_T4_REG64(pi, "tx_mcast_frames", "# of multicast frames",
5632 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_MCAST_L));
5633 	SYSCTL_ADD_T4_REG64(pi, "tx_ucast_frames", "# of unicast frames",
5634 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_UCAST_L));
5635 	SYSCTL_ADD_T4_REG64(pi, "tx_error_frames", "# of error frames",
5636 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_ERROR_L));
5637 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_64",
5638 	    "# of tx frames in this range",
5639 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_64B_L));
5640 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_65_127",
5641 	    "# of tx frames in this range",
5642 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_65B_127B_L));
5643 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_128_255",
5644 	    "# of tx frames in this range",
5645 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_128B_255B_L));
5646 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_256_511",
5647 	    "# of tx frames in this range",
5648 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_256B_511B_L));
5649 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_512_1023",
5650 	    "# of tx frames in this range",
5651 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_512B_1023B_L));
5652 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1024_1518",
5653 	    "# of tx frames in this range",
5654 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1024B_1518B_L));
5655 	SYSCTL_ADD_T4_REG64(pi, "tx_frames_1519_max",
5656 	    "# of tx frames in this range",
5657 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_1519B_MAX_L));
5658 	SYSCTL_ADD_T4_REG64(pi, "tx_drop", "# of dropped tx frames",
5659 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_DROP_L));
5660 	SYSCTL_ADD_T4_REG64(pi, "tx_pause", "# of pause frames transmitted",
5661 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PAUSE_L));
5662 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp0", "# of PPP prio 0 frames transmitted",
5663 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP0_L));
5664 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp1", "# of PPP prio 1 frames transmitted",
5665 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP1_L));
5666 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp2", "# of PPP prio 2 frames transmitted",
5667 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP2_L));
5668 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp3", "# of PPP prio 3 frames transmitted",
5669 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP3_L));
5670 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp4", "# of PPP prio 4 frames transmitted",
5671 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP4_L));
5672 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp5", "# of PPP prio 5 frames transmitted",
5673 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP5_L));
5674 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp6", "# of PPP prio 6 frames transmitted",
5675 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP6_L));
5676 	SYSCTL_ADD_T4_REG64(pi, "tx_ppp7", "# of PPP prio 7 frames transmitted",
5677 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_TX_PORT_PPP7_L));
5678 
5679 	SYSCTL_ADD_T4_REG64(pi, "rx_octets", "# of octets in good frames",
5680 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BYTES_L));
5681 	SYSCTL_ADD_T4_REG64(pi, "rx_frames", "total # of good frames",
5682 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_FRAMES_L));
5683 	SYSCTL_ADD_T4_REG64(pi, "rx_bcast_frames", "# of broadcast frames",
5684 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_BCAST_L));
5685 	SYSCTL_ADD_T4_REG64(pi, "rx_mcast_frames", "# of multicast frames",
5686 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MCAST_L));
5687 	SYSCTL_ADD_T4_REG64(pi, "rx_ucast_frames", "# of unicast frames",
5688 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_UCAST_L));
5689 	SYSCTL_ADD_T4_REG64(pi, "rx_too_long", "# of frames exceeding MTU",
5690 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_ERROR_L));
5691 	SYSCTL_ADD_T4_REG64(pi, "rx_jabber", "# of jabber frames",
5692 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_MTU_CRC_ERROR_L));
5693 	SYSCTL_ADD_T4_REG64(pi, "rx_fcs_err",
5694 	    "# of frames received with bad FCS",
5695 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L));
5696 	SYSCTL_ADD_T4_REG64(pi, "rx_len_err",
5697 	    "# of frames received with length error",
5698 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LEN_ERROR_L));
5699 	SYSCTL_ADD_T4_REG64(pi, "rx_symbol_err", "symbol errors",
5700 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_SYM_ERROR_L));
5701 	SYSCTL_ADD_T4_REG64(pi, "rx_runt", "# of short frames received",
5702 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_LESS_64B_L));
5703 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_64",
5704 	    "# of rx frames in this range",
5705 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_64B_L));
5706 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_65_127",
5707 	    "# of rx frames in this range",
5708 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_65B_127B_L));
5709 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_128_255",
5710 	    "# of rx frames in this range",
5711 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_128B_255B_L));
5712 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_256_511",
5713 	    "# of rx frames in this range",
5714 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_256B_511B_L));
5715 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_512_1023",
5716 	    "# of rx frames in this range",
5717 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_512B_1023B_L));
5718 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1024_1518",
5719 	    "# of rx frames in this range",
5720 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1024B_1518B_L));
5721 	SYSCTL_ADD_T4_REG64(pi, "rx_frames_1519_max",
5722 	    "# of rx frames in this range",
5723 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_1519B_MAX_L));
5724 	SYSCTL_ADD_T4_REG64(pi, "rx_pause", "# of pause frames received",
5725 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PAUSE_L));
5726 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp0", "# of PPP prio 0 frames received",
5727 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP0_L));
5728 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp1", "# of PPP prio 1 frames received",
5729 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP1_L));
5730 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp2", "# of PPP prio 2 frames received",
5731 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP2_L));
5732 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp3", "# of PPP prio 3 frames received",
5733 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP3_L));
5734 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp4", "# of PPP prio 4 frames received",
5735 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP4_L));
5736 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp5", "# of PPP prio 5 frames received",
5737 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP5_L));
5738 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp6", "# of PPP prio 6 frames received",
5739 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP6_L));
5740 	SYSCTL_ADD_T4_REG64(pi, "rx_ppp7", "# of PPP prio 7 frames received",
5741 	    PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_RX_PORT_PPP7_L));
5742 
5743 #undef SYSCTL_ADD_T4_REG64
5744 
5745 #define SYSCTL_ADD_T4_PORTSTAT(name, desc) \
5746 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
5747 	    &pi->stats.name, desc)
5748 
5749 	/* We get these from port_stats and they may be stale by up to 1s */
5750 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow0,
5751 	    "# drops due to buffer-group 0 overflows");
5752 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow1,
5753 	    "# drops due to buffer-group 1 overflows");
5754 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow2,
5755 	    "# drops due to buffer-group 2 overflows");
5756 	SYSCTL_ADD_T4_PORTSTAT(rx_ovflow3,
5757 	    "# drops due to buffer-group 3 overflows");
5758 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc0,
5759 	    "# of buffer-group 0 truncated packets");
5760 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc1,
5761 	    "# of buffer-group 1 truncated packets");
5762 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc2,
5763 	    "# of buffer-group 2 truncated packets");
5764 	SYSCTL_ADD_T4_PORTSTAT(rx_trunc3,
5765 	    "# of buffer-group 3 truncated packets");
5766 
5767 #undef SYSCTL_ADD_T4_PORTSTAT
5768 }
5769 
5770 static int
5771 sysctl_int_array(SYSCTL_HANDLER_ARGS)
5772 {
5773 	int rc, *i, space = 0;
5774 	struct sbuf sb;
5775 
5776 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
5777 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
5778 		if (space)
5779 			sbuf_printf(&sb, " ");
5780 		sbuf_printf(&sb, "%d", *i);
5781 		space = 1;
5782 	}
5783 	rc = sbuf_finish(&sb);
5784 	sbuf_delete(&sb);
5785 	return (rc);
5786 }
5787 
5788 static int
5789 sysctl_bitfield(SYSCTL_HANDLER_ARGS)
5790 {
5791 	int rc;
5792 	struct sbuf *sb;
5793 
5794 	rc = sysctl_wire_old_buffer(req, 0);
5795 	if (rc != 0)
5796 		return(rc);
5797 
5798 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5799 	if (sb == NULL)
5800 		return (ENOMEM);
5801 
5802 	sbuf_printf(sb, "%b", (int)arg2, (char *)arg1);
5803 	rc = sbuf_finish(sb);
5804 	sbuf_delete(sb);
5805 
5806 	return (rc);
5807 }
5808 
5809 static int
5810 sysctl_btphy(SYSCTL_HANDLER_ARGS)
5811 {
5812 	struct port_info *pi = arg1;
5813 	int op = arg2;
5814 	struct adapter *sc = pi->adapter;
5815 	u_int v;
5816 	int rc;
5817 
5818 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
5819 	if (rc)
5820 		return (rc);
5821 	/* XXX: magic numbers */
5822 	rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e, op ? 0x20 : 0xc820,
5823 	    &v);
5824 	end_synchronized_op(sc, 0);
5825 	if (rc)
5826 		return (rc);
5827 	if (op == 0)
5828 		v /= 256;
5829 
5830 	rc = sysctl_handle_int(oidp, &v, 0, req);
5831 	return (rc);
5832 }
5833 
5834 static int
5835 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
5836 {
5837 	struct vi_info *vi = arg1;
5838 	int rc, val;
5839 
5840 	val = vi->rsrv_noflowq;
5841 	rc = sysctl_handle_int(oidp, &val, 0, req);
5842 	if (rc != 0 || req->newptr == NULL)
5843 		return (rc);
5844 
5845 	if ((val >= 1) && (vi->ntxq > 1))
5846 		vi->rsrv_noflowq = 1;
5847 	else
5848 		vi->rsrv_noflowq = 0;
5849 
5850 	return (rc);
5851 }
5852 
5853 static int
5854 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
5855 {
5856 	struct vi_info *vi = arg1;
5857 	struct adapter *sc = vi->pi->adapter;
5858 	int idx, rc, i;
5859 	struct sge_rxq *rxq;
5860 	uint8_t v;
5861 
5862 	idx = vi->tmr_idx;
5863 
5864 	rc = sysctl_handle_int(oidp, &idx, 0, req);
5865 	if (rc != 0 || req->newptr == NULL)
5866 		return (rc);
5867 
5868 	if (idx < 0 || idx >= SGE_NTIMERS)
5869 		return (EINVAL);
5870 
5871 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5872 	    "t4tmr");
5873 	if (rc)
5874 		return (rc);
5875 
5876 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
5877 	for_each_rxq(vi, i, rxq) {
5878 #ifdef atomic_store_rel_8
5879 		atomic_store_rel_8(&rxq->iq.intr_params, v);
5880 #else
5881 		rxq->iq.intr_params = v;
5882 #endif
5883 	}
5884 	vi->tmr_idx = idx;
5885 
5886 	end_synchronized_op(sc, LOCK_HELD);
5887 	return (0);
5888 }
5889 
5890 static int
5891 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
5892 {
5893 	struct vi_info *vi = arg1;
5894 	struct adapter *sc = vi->pi->adapter;
5895 	int idx, rc;
5896 
5897 	idx = vi->pktc_idx;
5898 
5899 	rc = sysctl_handle_int(oidp, &idx, 0, req);
5900 	if (rc != 0 || req->newptr == NULL)
5901 		return (rc);
5902 
5903 	if (idx < -1 || idx >= SGE_NCOUNTERS)
5904 		return (EINVAL);
5905 
5906 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5907 	    "t4pktc");
5908 	if (rc)
5909 		return (rc);
5910 
5911 	if (vi->flags & VI_INIT_DONE)
5912 		rc = EBUSY; /* cannot be changed once the queues are created */
5913 	else
5914 		vi->pktc_idx = idx;
5915 
5916 	end_synchronized_op(sc, LOCK_HELD);
5917 	return (rc);
5918 }
5919 
5920 static int
5921 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
5922 {
5923 	struct vi_info *vi = arg1;
5924 	struct adapter *sc = vi->pi->adapter;
5925 	int qsize, rc;
5926 
5927 	qsize = vi->qsize_rxq;
5928 
5929 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
5930 	if (rc != 0 || req->newptr == NULL)
5931 		return (rc);
5932 
5933 	if (qsize < 128 || (qsize & 7))
5934 		return (EINVAL);
5935 
5936 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5937 	    "t4rxqs");
5938 	if (rc)
5939 		return (rc);
5940 
5941 	if (vi->flags & VI_INIT_DONE)
5942 		rc = EBUSY; /* cannot be changed once the queues are created */
5943 	else
5944 		vi->qsize_rxq = qsize;
5945 
5946 	end_synchronized_op(sc, LOCK_HELD);
5947 	return (rc);
5948 }
5949 
5950 static int
5951 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
5952 {
5953 	struct vi_info *vi = arg1;
5954 	struct adapter *sc = vi->pi->adapter;
5955 	int qsize, rc;
5956 
5957 	qsize = vi->qsize_txq;
5958 
5959 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
5960 	if (rc != 0 || req->newptr == NULL)
5961 		return (rc);
5962 
5963 	if (qsize < 128 || qsize > 65536)
5964 		return (EINVAL);
5965 
5966 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
5967 	    "t4txqs");
5968 	if (rc)
5969 		return (rc);
5970 
5971 	if (vi->flags & VI_INIT_DONE)
5972 		rc = EBUSY; /* cannot be changed once the queues are created */
5973 	else
5974 		vi->qsize_txq = qsize;
5975 
5976 	end_synchronized_op(sc, LOCK_HELD);
5977 	return (rc);
5978 }
5979 
5980 static int
5981 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
5982 {
5983 	struct port_info *pi = arg1;
5984 	struct adapter *sc = pi->adapter;
5985 	struct link_config *lc = &pi->link_cfg;
5986 	int rc;
5987 
5988 	if (req->newptr == NULL) {
5989 		struct sbuf *sb;
5990 		static char *bits = "\20\1PAUSE_RX\2PAUSE_TX";
5991 
5992 		rc = sysctl_wire_old_buffer(req, 0);
5993 		if (rc != 0)
5994 			return(rc);
5995 
5996 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
5997 		if (sb == NULL)
5998 			return (ENOMEM);
5999 
6000 		sbuf_printf(sb, "%b", lc->fc & (PAUSE_TX | PAUSE_RX), bits);
6001 		rc = sbuf_finish(sb);
6002 		sbuf_delete(sb);
6003 	} else {
6004 		char s[2];
6005 		int n;
6006 
6007 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX));
6008 		s[1] = 0;
6009 
6010 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6011 		if (rc != 0)
6012 			return(rc);
6013 
6014 		if (s[1] != 0)
6015 			return (EINVAL);
6016 		if (s[0] < '0' || s[0] > '9')
6017 			return (EINVAL);	/* not a number */
6018 		n = s[0] - '0';
6019 		if (n & ~(PAUSE_TX | PAUSE_RX))
6020 			return (EINVAL);	/* some other bit is set too */
6021 
6022 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6023 		    "t4PAUSE");
6024 		if (rc)
6025 			return (rc);
6026 		if ((lc->requested_fc & (PAUSE_TX | PAUSE_RX)) != n) {
6027 			lc->requested_fc &= ~(PAUSE_TX | PAUSE_RX);
6028 			lc->requested_fc |= n;
6029 			rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6030 			if (rc == 0) {
6031 				lc->fc = lc->requested_fc;
6032 			}
6033 		}
6034 		end_synchronized_op(sc, 0);
6035 	}
6036 
6037 	return (rc);
6038 }
6039 
6040 static int
6041 sysctl_fec(SYSCTL_HANDLER_ARGS)
6042 {
6043 	struct port_info *pi = arg1;
6044 	struct adapter *sc = pi->adapter;
6045 	struct link_config *lc = &pi->link_cfg;
6046 	int rc;
6047 
6048 	if (req->newptr == NULL) {
6049 		struct sbuf *sb;
6050 		static char *bits = "\20\1RS\2BASER_RS\3RESERVED";
6051 
6052 		rc = sysctl_wire_old_buffer(req, 0);
6053 		if (rc != 0)
6054 			return(rc);
6055 
6056 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
6057 		if (sb == NULL)
6058 			return (ENOMEM);
6059 
6060 		sbuf_printf(sb, "%b", lc->fec & M_FW_PORT_CAP_FEC, bits);
6061 		rc = sbuf_finish(sb);
6062 		sbuf_delete(sb);
6063 	} else {
6064 		char s[2];
6065 		int n;
6066 
6067 		s[0] = '0' + (lc->requested_fec & M_FW_PORT_CAP_FEC);
6068 		s[1] = 0;
6069 
6070 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
6071 		if (rc != 0)
6072 			return(rc);
6073 
6074 		if (s[1] != 0)
6075 			return (EINVAL);
6076 		if (s[0] < '0' || s[0] > '9')
6077 			return (EINVAL);	/* not a number */
6078 		n = s[0] - '0';
6079 		if (n & ~M_FW_PORT_CAP_FEC)
6080 			return (EINVAL);	/* some other bit is set too */
6081 
6082 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6083 		    "t4fec");
6084 		if (rc)
6085 			return (rc);
6086 		if ((lc->requested_fec & M_FW_PORT_CAP_FEC) != n) {
6087 			lc->requested_fec = n &
6088 			    G_FW_PORT_CAP_FEC(lc->supported);
6089 			rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6090 			if (rc == 0) {
6091 				lc->fec = lc->requested_fec;
6092 			}
6093 		}
6094 		end_synchronized_op(sc, 0);
6095 	}
6096 
6097 	return (rc);
6098 }
6099 
6100 static int
6101 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
6102 {
6103 	struct port_info *pi = arg1;
6104 	struct adapter *sc = pi->adapter;
6105 	struct link_config *lc = &pi->link_cfg;
6106 	int rc, val, old;
6107 
6108 	if (lc->supported & FW_PORT_CAP_ANEG)
6109 		val = lc->requested_aneg == AUTONEG_ENABLE ? 1 : 0;
6110 	else
6111 		val = -1;
6112 	rc = sysctl_handle_int(oidp, &val, 0, req);
6113 	if (rc != 0 || req->newptr == NULL)
6114 		return (rc);
6115 	if ((lc->supported & FW_PORT_CAP_ANEG) == 0)
6116 		return (ENOTSUP);
6117 
6118 	if (val == 0)
6119 		val = AUTONEG_DISABLE;
6120 	else if (val == 1)
6121 		val = AUTONEG_ENABLE;
6122 	else
6123 		return (EINVAL);
6124 	if (lc->requested_aneg == val)
6125 		return (0);	/* no change */
6126 
6127 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
6128 	    "t4aneg");
6129 	if (rc)
6130 		return (rc);
6131 	old = lc->requested_aneg;
6132 	lc->requested_aneg = val;
6133 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6134 	if (rc != 0)
6135 		lc->requested_aneg = old;
6136 	end_synchronized_op(sc, 0);
6137 	return (rc);
6138 }
6139 
6140 static int
6141 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
6142 {
6143 	struct adapter *sc = arg1;
6144 	int reg = arg2;
6145 	uint64_t val;
6146 
6147 	val = t4_read_reg64(sc, reg);
6148 
6149 	return (sysctl_handle_64(oidp, &val, 0, req));
6150 }
6151 
6152 static int
6153 sysctl_temperature(SYSCTL_HANDLER_ARGS)
6154 {
6155 	struct adapter *sc = arg1;
6156 	int rc, t;
6157 	uint32_t param, val;
6158 
6159 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
6160 	if (rc)
6161 		return (rc);
6162 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
6163 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
6164 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
6165 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
6166 	end_synchronized_op(sc, 0);
6167 	if (rc)
6168 		return (rc);
6169 
6170 	/* unknown is returned as 0 but we display -1 in that case */
6171 	t = val == 0 ? -1 : val;
6172 
6173 	rc = sysctl_handle_int(oidp, &t, 0, req);
6174 	return (rc);
6175 }
6176 
6177 #ifdef SBUF_DRAIN
6178 static int
6179 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
6180 {
6181 	struct adapter *sc = arg1;
6182 	struct sbuf *sb;
6183 	int rc, i;
6184 	uint16_t incr[NMTUS][NCCTRL_WIN];
6185 	static const char *dec_fac[] = {
6186 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
6187 		"0.9375"
6188 	};
6189 
6190 	rc = sysctl_wire_old_buffer(req, 0);
6191 	if (rc != 0)
6192 		return (rc);
6193 
6194 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6195 	if (sb == NULL)
6196 		return (ENOMEM);
6197 
6198 	t4_read_cong_tbl(sc, incr);
6199 
6200 	for (i = 0; i < NCCTRL_WIN; ++i) {
6201 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
6202 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
6203 		    incr[5][i], incr[6][i], incr[7][i]);
6204 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
6205 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
6206 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
6207 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
6208 	}
6209 
6210 	rc = sbuf_finish(sb);
6211 	sbuf_delete(sb);
6212 
6213 	return (rc);
6214 }
6215 
6216 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
6217 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
6218 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
6219 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
6220 };
6221 
6222 static int
6223 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
6224 {
6225 	struct adapter *sc = arg1;
6226 	struct sbuf *sb;
6227 	int rc, i, n, qid = arg2;
6228 	uint32_t *buf, *p;
6229 	char *qtype;
6230 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
6231 
6232 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
6233 	    ("%s: bad qid %d\n", __func__, qid));
6234 
6235 	if (qid < CIM_NUM_IBQ) {
6236 		/* inbound queue */
6237 		qtype = "IBQ";
6238 		n = 4 * CIM_IBQ_SIZE;
6239 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
6240 		rc = t4_read_cim_ibq(sc, qid, buf, n);
6241 	} else {
6242 		/* outbound queue */
6243 		qtype = "OBQ";
6244 		qid -= CIM_NUM_IBQ;
6245 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
6246 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
6247 		rc = t4_read_cim_obq(sc, qid, buf, n);
6248 	}
6249 
6250 	if (rc < 0) {
6251 		rc = -rc;
6252 		goto done;
6253 	}
6254 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
6255 
6256 	rc = sysctl_wire_old_buffer(req, 0);
6257 	if (rc != 0)
6258 		goto done;
6259 
6260 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
6261 	if (sb == NULL) {
6262 		rc = ENOMEM;
6263 		goto done;
6264 	}
6265 
6266 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
6267 	for (i = 0, p = buf; i < n; i += 16, p += 4)
6268 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
6269 		    p[2], p[3]);
6270 
6271 	rc = sbuf_finish(sb);
6272 	sbuf_delete(sb);
6273 done:
6274 	free(buf, M_CXGBE);
6275 	return (rc);
6276 }
6277 
6278 static int
6279 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
6280 {
6281 	struct adapter *sc = arg1;
6282 	u_int cfg;
6283 	struct sbuf *sb;
6284 	uint32_t *buf, *p;
6285 	int rc;
6286 
6287 	MPASS(chip_id(sc) <= CHELSIO_T5);
6288 
6289 	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
6290 	if (rc != 0)
6291 		return (rc);
6292 
6293 	rc = sysctl_wire_old_buffer(req, 0);
6294 	if (rc != 0)
6295 		return (rc);
6296 
6297 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6298 	if (sb == NULL)
6299 		return (ENOMEM);
6300 
6301 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
6302 	    M_ZERO | M_WAITOK);
6303 
6304 	rc = -t4_cim_read_la(sc, buf, NULL);
6305 	if (rc != 0)
6306 		goto done;
6307 
6308 	sbuf_printf(sb, "Status   Data      PC%s",
6309 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
6310 	    "     LS0Stat  LS0Addr             LS0Data");
6311 
6312 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
6313 		if (cfg & F_UPDBGLACAPTPCONLY) {
6314 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
6315 			    p[6], p[7]);
6316 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
6317 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
6318 			    p[4] & 0xff, p[5] >> 8);
6319 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
6320 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
6321 			    p[1] & 0xf, p[2] >> 4);
6322 		} else {
6323 			sbuf_printf(sb,
6324 			    "\n  %02x   %x%07x %x%07x %08x %08x "
6325 			    "%08x%08x%08x%08x",
6326 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
6327 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
6328 			    p[6], p[7]);
6329 		}
6330 	}
6331 
6332 	rc = sbuf_finish(sb);
6333 	sbuf_delete(sb);
6334 done:
6335 	free(buf, M_CXGBE);
6336 	return (rc);
6337 }
6338 
6339 static int
6340 sysctl_cim_la_t6(SYSCTL_HANDLER_ARGS)
6341 {
6342 	struct adapter *sc = arg1;
6343 	u_int cfg;
6344 	struct sbuf *sb;
6345 	uint32_t *buf, *p;
6346 	int rc;
6347 
6348 	MPASS(chip_id(sc) > CHELSIO_T5);
6349 
6350 	rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
6351 	if (rc != 0)
6352 		return (rc);
6353 
6354 	rc = sysctl_wire_old_buffer(req, 0);
6355 	if (rc != 0)
6356 		return (rc);
6357 
6358 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6359 	if (sb == NULL)
6360 		return (ENOMEM);
6361 
6362 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
6363 	    M_ZERO | M_WAITOK);
6364 
6365 	rc = -t4_cim_read_la(sc, buf, NULL);
6366 	if (rc != 0)
6367 		goto done;
6368 
6369 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
6370 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
6371 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
6372 
6373 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
6374 		if (cfg & F_UPDBGLACAPTPCONLY) {
6375 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
6376 			    p[3] & 0xff, p[2], p[1], p[0]);
6377 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
6378 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
6379 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
6380 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
6381 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
6382 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
6383 			    p[6] >> 16);
6384 		} else {
6385 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
6386 			    "%08x %08x %08x %08x %08x %08x",
6387 			    (p[9] >> 16) & 0xff,
6388 			    p[9] & 0xffff, p[8] >> 16,
6389 			    p[8] & 0xffff, p[7] >> 16,
6390 			    p[7] & 0xffff, p[6] >> 16,
6391 			    p[2], p[1], p[0], p[5], p[4], p[3]);
6392 		}
6393 	}
6394 
6395 	rc = sbuf_finish(sb);
6396 	sbuf_delete(sb);
6397 done:
6398 	free(buf, M_CXGBE);
6399 	return (rc);
6400 }
6401 
6402 static int
6403 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
6404 {
6405 	struct adapter *sc = arg1;
6406 	u_int i;
6407 	struct sbuf *sb;
6408 	uint32_t *buf, *p;
6409 	int rc;
6410 
6411 	rc = sysctl_wire_old_buffer(req, 0);
6412 	if (rc != 0)
6413 		return (rc);
6414 
6415 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6416 	if (sb == NULL)
6417 		return (ENOMEM);
6418 
6419 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
6420 	    M_ZERO | M_WAITOK);
6421 
6422 	t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
6423 	p = buf;
6424 
6425 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
6426 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
6427 		    p[1], p[0]);
6428 	}
6429 
6430 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
6431 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
6432 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
6433 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
6434 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
6435 		    (p[1] >> 2) | ((p[2] & 3) << 30),
6436 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
6437 		    p[0] & 1);
6438 	}
6439 
6440 	rc = sbuf_finish(sb);
6441 	sbuf_delete(sb);
6442 	free(buf, M_CXGBE);
6443 	return (rc);
6444 }
6445 
6446 static int
6447 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
6448 {
6449 	struct adapter *sc = arg1;
6450 	u_int i;
6451 	struct sbuf *sb;
6452 	uint32_t *buf, *p;
6453 	int rc;
6454 
6455 	rc = sysctl_wire_old_buffer(req, 0);
6456 	if (rc != 0)
6457 		return (rc);
6458 
6459 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6460 	if (sb == NULL)
6461 		return (ENOMEM);
6462 
6463 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
6464 	    M_ZERO | M_WAITOK);
6465 
6466 	t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
6467 	p = buf;
6468 
6469 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
6470 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
6471 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
6472 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
6473 		    p[4], p[3], p[2], p[1], p[0]);
6474 	}
6475 
6476 	sbuf_printf(sb, "\n\nCntl ID               Data");
6477 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
6478 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
6479 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
6480 	}
6481 
6482 	rc = sbuf_finish(sb);
6483 	sbuf_delete(sb);
6484 	free(buf, M_CXGBE);
6485 	return (rc);
6486 }
6487 
6488 static int
6489 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
6490 {
6491 	struct adapter *sc = arg1;
6492 	struct sbuf *sb;
6493 	int rc, i;
6494 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
6495 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
6496 	uint16_t thres[CIM_NUM_IBQ];
6497 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
6498 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
6499 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
6500 
6501 	cim_num_obq = sc->chip_params->cim_num_obq;
6502 	if (is_t4(sc)) {
6503 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
6504 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
6505 	} else {
6506 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
6507 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
6508 	}
6509 	nq = CIM_NUM_IBQ + cim_num_obq;
6510 
6511 	rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
6512 	if (rc == 0)
6513 		rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq, obq_wr);
6514 	if (rc != 0)
6515 		return (rc);
6516 
6517 	t4_read_cimq_cfg(sc, base, size, thres);
6518 
6519 	rc = sysctl_wire_old_buffer(req, 0);
6520 	if (rc != 0)
6521 		return (rc);
6522 
6523 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
6524 	if (sb == NULL)
6525 		return (ENOMEM);
6526 
6527 	sbuf_printf(sb,
6528 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
6529 
6530 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
6531 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
6532 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
6533 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
6534 		    G_QUEREMFLITS(p[2]) * 16);
6535 	for ( ; i < nq; i++, p += 4, wr += 2)
6536 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
6537 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
6538 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
6539 		    G_QUEREMFLITS(p[2]) * 16);
6540 
6541 	rc = sbuf_finish(sb);
6542 	sbuf_delete(sb);
6543 
6544 	return (rc);
6545 }
6546 
6547 static int
6548 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
6549 {
6550 	struct adapter *sc = arg1;
6551 	struct sbuf *sb;
6552 	int rc;
6553 	struct tp_cpl_stats stats;
6554 
6555 	rc = sysctl_wire_old_buffer(req, 0);
6556 	if (rc != 0)
6557 		return (rc);
6558 
6559 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6560 	if (sb == NULL)
6561 		return (ENOMEM);
6562 
6563 	mtx_lock(&sc->reg_lock);
6564 	t4_tp_get_cpl_stats(sc, &stats, 0);
6565 	mtx_unlock(&sc->reg_lock);
6566 
6567 	if (sc->chip_params->nchan > 2) {
6568 		sbuf_printf(sb, "                 channel 0  channel 1"
6569 		    "  channel 2  channel 3");
6570 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
6571 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
6572 		sbuf_printf(sb, "\nCPL responses:   %10u %10u %10u %10u",
6573 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
6574 	} else {
6575 		sbuf_printf(sb, "                 channel 0  channel 1");
6576 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
6577 		    stats.req[0], stats.req[1]);
6578 		sbuf_printf(sb, "\nCPL responses:   %10u %10u",
6579 		    stats.rsp[0], stats.rsp[1]);
6580 	}
6581 
6582 	rc = sbuf_finish(sb);
6583 	sbuf_delete(sb);
6584 
6585 	return (rc);
6586 }
6587 
6588 static int
6589 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
6590 {
6591 	struct adapter *sc = arg1;
6592 	struct sbuf *sb;
6593 	int rc;
6594 	struct tp_usm_stats stats;
6595 
6596 	rc = sysctl_wire_old_buffer(req, 0);
6597 	if (rc != 0)
6598 		return(rc);
6599 
6600 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6601 	if (sb == NULL)
6602 		return (ENOMEM);
6603 
6604 	t4_get_usm_stats(sc, &stats, 1);
6605 
6606 	sbuf_printf(sb, "Frames: %u\n", stats.frames);
6607 	sbuf_printf(sb, "Octets: %ju\n", stats.octets);
6608 	sbuf_printf(sb, "Drops:  %u", stats.drops);
6609 
6610 	rc = sbuf_finish(sb);
6611 	sbuf_delete(sb);
6612 
6613 	return (rc);
6614 }
6615 
6616 static const char * const devlog_level_strings[] = {
6617 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
6618 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
6619 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
6620 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
6621 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
6622 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
6623 };
6624 
6625 static const char * const devlog_facility_strings[] = {
6626 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
6627 	[FW_DEVLOG_FACILITY_CF]		= "CF",
6628 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
6629 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
6630 	[FW_DEVLOG_FACILITY_RES]	= "RES",
6631 	[FW_DEVLOG_FACILITY_HW]		= "HW",
6632 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
6633 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
6634 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
6635 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
6636 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
6637 	[FW_DEVLOG_FACILITY_VI]		= "VI",
6638 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
6639 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
6640 	[FW_DEVLOG_FACILITY_TM]		= "TM",
6641 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
6642 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
6643 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
6644 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
6645 	[FW_DEVLOG_FACILITY_RI]		= "RI",
6646 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
6647 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
6648 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
6649 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
6650 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
6651 };
6652 
6653 static int
6654 sysctl_devlog(SYSCTL_HANDLER_ARGS)
6655 {
6656 	struct adapter *sc = arg1;
6657 	struct devlog_params *dparams = &sc->params.devlog;
6658 	struct fw_devlog_e *buf, *e;
6659 	int i, j, rc, nentries, first = 0;
6660 	struct sbuf *sb;
6661 	uint64_t ftstamp = UINT64_MAX;
6662 
6663 	if (dparams->addr == 0)
6664 		return (ENXIO);
6665 
6666 	buf = malloc(dparams->size, M_CXGBE, M_NOWAIT);
6667 	if (buf == NULL)
6668 		return (ENOMEM);
6669 
6670 	rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf, dparams->size);
6671 	if (rc != 0)
6672 		goto done;
6673 
6674 	nentries = dparams->size / sizeof(struct fw_devlog_e);
6675 	for (i = 0; i < nentries; i++) {
6676 		e = &buf[i];
6677 
6678 		if (e->timestamp == 0)
6679 			break;	/* end */
6680 
6681 		e->timestamp = be64toh(e->timestamp);
6682 		e->seqno = be32toh(e->seqno);
6683 		for (j = 0; j < 8; j++)
6684 			e->params[j] = be32toh(e->params[j]);
6685 
6686 		if (e->timestamp < ftstamp) {
6687 			ftstamp = e->timestamp;
6688 			first = i;
6689 		}
6690 	}
6691 
6692 	if (buf[first].timestamp == 0)
6693 		goto done;	/* nothing in the log */
6694 
6695 	rc = sysctl_wire_old_buffer(req, 0);
6696 	if (rc != 0)
6697 		goto done;
6698 
6699 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6700 	if (sb == NULL) {
6701 		rc = ENOMEM;
6702 		goto done;
6703 	}
6704 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
6705 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
6706 
6707 	i = first;
6708 	do {
6709 		e = &buf[i];
6710 		if (e->timestamp == 0)
6711 			break;	/* end */
6712 
6713 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
6714 		    e->seqno, e->timestamp,
6715 		    (e->level < nitems(devlog_level_strings) ?
6716 			devlog_level_strings[e->level] : "UNKNOWN"),
6717 		    (e->facility < nitems(devlog_facility_strings) ?
6718 			devlog_facility_strings[e->facility] : "UNKNOWN"));
6719 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
6720 		    e->params[2], e->params[3], e->params[4],
6721 		    e->params[5], e->params[6], e->params[7]);
6722 
6723 		if (++i == nentries)
6724 			i = 0;
6725 	} while (i != first);
6726 
6727 	rc = sbuf_finish(sb);
6728 	sbuf_delete(sb);
6729 done:
6730 	free(buf, M_CXGBE);
6731 	return (rc);
6732 }
6733 
6734 static int
6735 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
6736 {
6737 	struct adapter *sc = arg1;
6738 	struct sbuf *sb;
6739 	int rc;
6740 	struct tp_fcoe_stats stats[MAX_NCHAN];
6741 	int i, nchan = sc->chip_params->nchan;
6742 
6743 	rc = sysctl_wire_old_buffer(req, 0);
6744 	if (rc != 0)
6745 		return (rc);
6746 
6747 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6748 	if (sb == NULL)
6749 		return (ENOMEM);
6750 
6751 	for (i = 0; i < nchan; i++)
6752 		t4_get_fcoe_stats(sc, i, &stats[i], 1);
6753 
6754 	if (nchan > 2) {
6755 		sbuf_printf(sb, "                   channel 0        channel 1"
6756 		    "        channel 2        channel 3");
6757 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
6758 		    stats[0].octets_ddp, stats[1].octets_ddp,
6759 		    stats[2].octets_ddp, stats[3].octets_ddp);
6760 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
6761 		    stats[0].frames_ddp, stats[1].frames_ddp,
6762 		    stats[2].frames_ddp, stats[3].frames_ddp);
6763 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
6764 		    stats[0].frames_drop, stats[1].frames_drop,
6765 		    stats[2].frames_drop, stats[3].frames_drop);
6766 	} else {
6767 		sbuf_printf(sb, "                   channel 0        channel 1");
6768 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
6769 		    stats[0].octets_ddp, stats[1].octets_ddp);
6770 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
6771 		    stats[0].frames_ddp, stats[1].frames_ddp);
6772 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
6773 		    stats[0].frames_drop, stats[1].frames_drop);
6774 	}
6775 
6776 	rc = sbuf_finish(sb);
6777 	sbuf_delete(sb);
6778 
6779 	return (rc);
6780 }
6781 
6782 static int
6783 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
6784 {
6785 	struct adapter *sc = arg1;
6786 	struct sbuf *sb;
6787 	int rc, i;
6788 	unsigned int map, kbps, ipg, mode;
6789 	unsigned int pace_tab[NTX_SCHED];
6790 
6791 	rc = sysctl_wire_old_buffer(req, 0);
6792 	if (rc != 0)
6793 		return (rc);
6794 
6795 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
6796 	if (sb == NULL)
6797 		return (ENOMEM);
6798 
6799 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
6800 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
6801 	t4_read_pace_tbl(sc, pace_tab);
6802 
6803 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
6804 	    "Class IPG (0.1 ns)   Flow IPG (us)");
6805 
6806 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
6807 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
6808 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
6809 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
6810 		if (kbps)
6811 			sbuf_printf(sb, "%9u     ", kbps);
6812 		else
6813 			sbuf_printf(sb, " disabled     ");
6814 
6815 		if (ipg)
6816 			sbuf_printf(sb, "%13u        ", ipg);
6817 		else
6818 			sbuf_printf(sb, "     disabled        ");
6819 
6820 		if (pace_tab[i])
6821 			sbuf_printf(sb, "%10u", pace_tab[i]);
6822 		else
6823 			sbuf_printf(sb, "  disabled");
6824 	}
6825 
6826 	rc = sbuf_finish(sb);
6827 	sbuf_delete(sb);
6828 
6829 	return (rc);
6830 }
6831 
6832 static int
6833 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
6834 {
6835 	struct adapter *sc = arg1;
6836 	struct sbuf *sb;
6837 	int rc, i, j;
6838 	uint64_t *p0, *p1;
6839 	struct lb_port_stats s[2];
6840 	static const char *stat_name[] = {
6841 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
6842 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
6843 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
6844 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
6845 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
6846 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
6847 		"BG2FramesTrunc:", "BG3FramesTrunc:"
6848 	};
6849 
6850 	rc = sysctl_wire_old_buffer(req, 0);
6851 	if (rc != 0)
6852 		return (rc);
6853 
6854 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6855 	if (sb == NULL)
6856 		return (ENOMEM);
6857 
6858 	memset(s, 0, sizeof(s));
6859 
6860 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
6861 		t4_get_lb_stats(sc, i, &s[0]);
6862 		t4_get_lb_stats(sc, i + 1, &s[1]);
6863 
6864 		p0 = &s[0].octets;
6865 		p1 = &s[1].octets;
6866 		sbuf_printf(sb, "%s                       Loopback %u"
6867 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
6868 
6869 		for (j = 0; j < nitems(stat_name); j++)
6870 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
6871 				   *p0++, *p1++);
6872 	}
6873 
6874 	rc = sbuf_finish(sb);
6875 	sbuf_delete(sb);
6876 
6877 	return (rc);
6878 }
6879 
6880 static int
6881 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
6882 {
6883 	int rc = 0;
6884 	struct port_info *pi = arg1;
6885 	struct link_config *lc = &pi->link_cfg;
6886 	struct sbuf *sb;
6887 
6888 	rc = sysctl_wire_old_buffer(req, 0);
6889 	if (rc != 0)
6890 		return(rc);
6891 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
6892 	if (sb == NULL)
6893 		return (ENOMEM);
6894 
6895 	if (lc->link_ok || lc->link_down_rc == 255)
6896 		sbuf_printf(sb, "n/a");
6897 	else
6898 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
6899 
6900 	rc = sbuf_finish(sb);
6901 	sbuf_delete(sb);
6902 
6903 	return (rc);
6904 }
6905 
6906 struct mem_desc {
6907 	unsigned int base;
6908 	unsigned int limit;
6909 	unsigned int idx;
6910 };
6911 
6912 static int
6913 mem_desc_cmp(const void *a, const void *b)
6914 {
6915 	return ((const struct mem_desc *)a)->base -
6916 	       ((const struct mem_desc *)b)->base;
6917 }
6918 
6919 static void
6920 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
6921     unsigned int to)
6922 {
6923 	unsigned int size;
6924 
6925 	if (from == to)
6926 		return;
6927 
6928 	size = to - from + 1;
6929 	if (size == 0)
6930 		return;
6931 
6932 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
6933 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
6934 }
6935 
6936 static int
6937 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
6938 {
6939 	struct adapter *sc = arg1;
6940 	struct sbuf *sb;
6941 	int rc, i, n;
6942 	uint32_t lo, hi, used, alloc;
6943 	static const char *memory[] = {"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:"};
6944 	static const char *region[] = {
6945 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
6946 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
6947 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
6948 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
6949 		"RQUDP region:", "PBL region:", "TXPBL region:",
6950 		"DBVFIFO region:", "ULPRX state:", "ULPTX state:",
6951 		"On-chip queues:"
6952 	};
6953 	struct mem_desc avail[4];
6954 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
6955 	struct mem_desc *md = mem;
6956 
6957 	rc = sysctl_wire_old_buffer(req, 0);
6958 	if (rc != 0)
6959 		return (rc);
6960 
6961 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
6962 	if (sb == NULL)
6963 		return (ENOMEM);
6964 
6965 	for (i = 0; i < nitems(mem); i++) {
6966 		mem[i].limit = 0;
6967 		mem[i].idx = i;
6968 	}
6969 
6970 	/* Find and sort the populated memory ranges */
6971 	i = 0;
6972 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
6973 	if (lo & F_EDRAM0_ENABLE) {
6974 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
6975 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
6976 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
6977 		avail[i].idx = 0;
6978 		i++;
6979 	}
6980 	if (lo & F_EDRAM1_ENABLE) {
6981 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
6982 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
6983 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
6984 		avail[i].idx = 1;
6985 		i++;
6986 	}
6987 	if (lo & F_EXT_MEM_ENABLE) {
6988 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
6989 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
6990 		avail[i].limit = avail[i].base +
6991 		    (G_EXT_MEM_SIZE(hi) << 20);
6992 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
6993 		i++;
6994 	}
6995 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
6996 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
6997 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
6998 		avail[i].limit = avail[i].base +
6999 		    (G_EXT_MEM1_SIZE(hi) << 20);
7000 		avail[i].idx = 4;
7001 		i++;
7002 	}
7003 	if (!i)                                    /* no memory available */
7004 		return 0;
7005 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
7006 
7007 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
7008 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
7009 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
7010 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
7011 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
7012 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
7013 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
7014 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
7015 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
7016 
7017 	/* the next few have explicit upper bounds */
7018 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
7019 	md->limit = md->base - 1 +
7020 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
7021 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
7022 	md++;
7023 
7024 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
7025 	md->limit = md->base - 1 +
7026 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
7027 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
7028 	md++;
7029 
7030 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7031 		if (chip_id(sc) <= CHELSIO_T5)
7032 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
7033 		else
7034 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
7035 		md->limit = 0;
7036 	} else {
7037 		md->base = 0;
7038 		md->idx = nitems(region);  /* hide it */
7039 	}
7040 	md++;
7041 
7042 #define ulp_region(reg) \
7043 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
7044 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
7045 
7046 	ulp_region(RX_ISCSI);
7047 	ulp_region(RX_TDDP);
7048 	ulp_region(TX_TPT);
7049 	ulp_region(RX_STAG);
7050 	ulp_region(RX_RQ);
7051 	ulp_region(RX_RQUDP);
7052 	ulp_region(RX_PBL);
7053 	ulp_region(TX_PBL);
7054 #undef ulp_region
7055 
7056 	md->base = 0;
7057 	md->idx = nitems(region);
7058 	if (!is_t4(sc)) {
7059 		uint32_t size = 0;
7060 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
7061 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
7062 
7063 		if (is_t5(sc)) {
7064 			if (sge_ctrl & F_VFIFO_ENABLE)
7065 				size = G_DBVFIFO_SIZE(fifo_size);
7066 		} else
7067 			size = G_T6_DBVFIFO_SIZE(fifo_size);
7068 
7069 		if (size) {
7070 			md->base = G_BASEADDR(t4_read_reg(sc,
7071 			    A_SGE_DBVFIFO_BADDR));
7072 			md->limit = md->base + (size << 2) - 1;
7073 		}
7074 	}
7075 	md++;
7076 
7077 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
7078 	md->limit = 0;
7079 	md++;
7080 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
7081 	md->limit = 0;
7082 	md++;
7083 
7084 	md->base = sc->vres.ocq.start;
7085 	if (sc->vres.ocq.size)
7086 		md->limit = md->base + sc->vres.ocq.size - 1;
7087 	else
7088 		md->idx = nitems(region);  /* hide it */
7089 	md++;
7090 
7091 	/* add any address-space holes, there can be up to 3 */
7092 	for (n = 0; n < i - 1; n++)
7093 		if (avail[n].limit < avail[n + 1].base)
7094 			(md++)->base = avail[n].limit;
7095 	if (avail[n].limit)
7096 		(md++)->base = avail[n].limit;
7097 
7098 	n = md - mem;
7099 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
7100 
7101 	for (lo = 0; lo < i; lo++)
7102 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
7103 				avail[lo].limit - 1);
7104 
7105 	sbuf_printf(sb, "\n");
7106 	for (i = 0; i < n; i++) {
7107 		if (mem[i].idx >= nitems(region))
7108 			continue;                        /* skip holes */
7109 		if (!mem[i].limit)
7110 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
7111 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
7112 				mem[i].limit);
7113 	}
7114 
7115 	sbuf_printf(sb, "\n");
7116 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
7117 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
7118 	mem_region_show(sb, "uP RAM:", lo, hi);
7119 
7120 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
7121 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
7122 	mem_region_show(sb, "uP Extmem2:", lo, hi);
7123 
7124 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
7125 	sbuf_printf(sb, "\n%u Rx pages of size %uKiB for %u channels\n",
7126 		   G_PMRXMAXPAGE(lo),
7127 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
7128 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
7129 
7130 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
7131 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
7132 	sbuf_printf(sb, "%u Tx pages of size %u%ciB for %u channels\n",
7133 		   G_PMTXMAXPAGE(lo),
7134 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
7135 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
7136 	sbuf_printf(sb, "%u p-structs\n",
7137 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT));
7138 
7139 	for (i = 0; i < 4; i++) {
7140 		if (chip_id(sc) > CHELSIO_T5)
7141 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
7142 		else
7143 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
7144 		if (is_t5(sc)) {
7145 			used = G_T5_USED(lo);
7146 			alloc = G_T5_ALLOC(lo);
7147 		} else {
7148 			used = G_USED(lo);
7149 			alloc = G_ALLOC(lo);
7150 		}
7151 		/* For T6 these are MAC buffer groups */
7152 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
7153 		    i, used, alloc);
7154 	}
7155 	for (i = 0; i < sc->chip_params->nchan; i++) {
7156 		if (chip_id(sc) > CHELSIO_T5)
7157 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
7158 		else
7159 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
7160 		if (is_t5(sc)) {
7161 			used = G_T5_USED(lo);
7162 			alloc = G_T5_ALLOC(lo);
7163 		} else {
7164 			used = G_USED(lo);
7165 			alloc = G_ALLOC(lo);
7166 		}
7167 		/* For T6 these are MAC buffer groups */
7168 		sbuf_printf(sb,
7169 		    "\nLoopback %d using %u pages out of %u allocated",
7170 		    i, used, alloc);
7171 	}
7172 
7173 	rc = sbuf_finish(sb);
7174 	sbuf_delete(sb);
7175 
7176 	return (rc);
7177 }
7178 
7179 static inline void
7180 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
7181 {
7182 	*mask = x | y;
7183 	y = htobe64(y);
7184 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
7185 }
7186 
7187 static int
7188 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
7189 {
7190 	struct adapter *sc = arg1;
7191 	struct sbuf *sb;
7192 	int rc, i;
7193 
7194 	MPASS(chip_id(sc) <= CHELSIO_T5);
7195 
7196 	rc = sysctl_wire_old_buffer(req, 0);
7197 	if (rc != 0)
7198 		return (rc);
7199 
7200 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7201 	if (sb == NULL)
7202 		return (ENOMEM);
7203 
7204 	sbuf_printf(sb,
7205 	    "Idx  Ethernet address     Mask     Vld Ports PF"
7206 	    "  VF              Replication             P0 P1 P2 P3  ML");
7207 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
7208 		uint64_t tcamx, tcamy, mask;
7209 		uint32_t cls_lo, cls_hi;
7210 		uint8_t addr[ETHER_ADDR_LEN];
7211 
7212 		tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
7213 		tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
7214 		if (tcamx & tcamy)
7215 			continue;
7216 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
7217 		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
7218 		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
7219 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
7220 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
7221 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
7222 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
7223 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
7224 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
7225 
7226 		if (cls_lo & F_REPLICATE) {
7227 			struct fw_ldst_cmd ldst_cmd;
7228 
7229 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
7230 			ldst_cmd.op_to_addrspace =
7231 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
7232 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
7233 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
7234 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
7235 			ldst_cmd.u.mps.rplc.fid_idx =
7236 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
7237 				V_FW_LDST_CMD_IDX(i));
7238 
7239 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7240 			    "t4mps");
7241 			if (rc)
7242 				break;
7243 			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
7244 			    sizeof(ldst_cmd), &ldst_cmd);
7245 			end_synchronized_op(sc, 0);
7246 
7247 			if (rc != 0) {
7248 				sbuf_printf(sb, "%36d", rc);
7249 				rc = 0;
7250 			} else {
7251 				sbuf_printf(sb, " %08x %08x %08x %08x",
7252 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
7253 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
7254 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
7255 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
7256 			}
7257 		} else
7258 			sbuf_printf(sb, "%36s", "");
7259 
7260 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
7261 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
7262 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
7263 	}
7264 
7265 	if (rc)
7266 		(void) sbuf_finish(sb);
7267 	else
7268 		rc = sbuf_finish(sb);
7269 	sbuf_delete(sb);
7270 
7271 	return (rc);
7272 }
7273 
7274 static int
7275 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
7276 {
7277 	struct adapter *sc = arg1;
7278 	struct sbuf *sb;
7279 	int rc, i;
7280 
7281 	MPASS(chip_id(sc) > CHELSIO_T5);
7282 
7283 	rc = sysctl_wire_old_buffer(req, 0);
7284 	if (rc != 0)
7285 		return (rc);
7286 
7287 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7288 	if (sb == NULL)
7289 		return (ENOMEM);
7290 
7291 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
7292 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
7293 	    "                           Replication"
7294 	    "                                    P0 P1 P2 P3  ML\n");
7295 
7296 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
7297 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
7298 		uint16_t ivlan;
7299 		uint64_t tcamx, tcamy, val, mask;
7300 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
7301 		uint8_t addr[ETHER_ADDR_LEN];
7302 
7303 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
7304 		if (i < 256)
7305 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
7306 		else
7307 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
7308 		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
7309 		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
7310 		tcamy = G_DMACH(val) << 32;
7311 		tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
7312 		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
7313 		lookup_type = G_DATALKPTYPE(data2);
7314 		port_num = G_DATAPORTNUM(data2);
7315 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
7316 			/* Inner header VNI */
7317 			vniy = ((data2 & F_DATAVIDH2) << 23) |
7318 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
7319 			dip_hit = data2 & F_DATADIPHIT;
7320 			vlan_vld = 0;
7321 		} else {
7322 			vniy = 0;
7323 			dip_hit = 0;
7324 			vlan_vld = data2 & F_DATAVIDH2;
7325 			ivlan = G_VIDL(val);
7326 		}
7327 
7328 		ctl |= V_CTLXYBITSEL(1);
7329 		t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
7330 		val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
7331 		tcamx = G_DMACH(val) << 32;
7332 		tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
7333 		data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
7334 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
7335 			/* Inner header VNI mask */
7336 			vnix = ((data2 & F_DATAVIDH2) << 23) |
7337 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
7338 		} else
7339 			vnix = 0;
7340 
7341 		if (tcamx & tcamy)
7342 			continue;
7343 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
7344 
7345 		cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
7346 		cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
7347 
7348 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
7349 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
7350 			    "%012jx %06x %06x    -    -   %3c"
7351 			    "      'I'  %4x   %3c   %#x%4u%4d", i, addr[0],
7352 			    addr[1], addr[2], addr[3], addr[4], addr[5],
7353 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
7354 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
7355 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
7356 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
7357 		} else {
7358 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
7359 			    "%012jx    -       -   ", i, addr[0], addr[1],
7360 			    addr[2], addr[3], addr[4], addr[5],
7361 			    (uintmax_t)mask);
7362 
7363 			if (vlan_vld)
7364 				sbuf_printf(sb, "%4u   Y     ", ivlan);
7365 			else
7366 				sbuf_printf(sb, "  -    N     ");
7367 
7368 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
7369 			    lookup_type ? 'I' : 'O', port_num,
7370 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
7371 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
7372 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
7373 		}
7374 
7375 
7376 		if (cls_lo & F_T6_REPLICATE) {
7377 			struct fw_ldst_cmd ldst_cmd;
7378 
7379 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
7380 			ldst_cmd.op_to_addrspace =
7381 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
7382 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
7383 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
7384 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
7385 			ldst_cmd.u.mps.rplc.fid_idx =
7386 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
7387 				V_FW_LDST_CMD_IDX(i));
7388 
7389 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
7390 			    "t6mps");
7391 			if (rc)
7392 				break;
7393 			rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
7394 			    sizeof(ldst_cmd), &ldst_cmd);
7395 			end_synchronized_op(sc, 0);
7396 
7397 			if (rc != 0) {
7398 				sbuf_printf(sb, "%72d", rc);
7399 				rc = 0;
7400 			} else {
7401 				sbuf_printf(sb, " %08x %08x %08x %08x"
7402 				    " %08x %08x %08x %08x",
7403 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
7404 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
7405 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
7406 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
7407 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
7408 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
7409 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
7410 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
7411 			}
7412 		} else
7413 			sbuf_printf(sb, "%72s", "");
7414 
7415 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
7416 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
7417 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
7418 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
7419 	}
7420 
7421 	if (rc)
7422 		(void) sbuf_finish(sb);
7423 	else
7424 		rc = sbuf_finish(sb);
7425 	sbuf_delete(sb);
7426 
7427 	return (rc);
7428 }
7429 
7430 static int
7431 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
7432 {
7433 	struct adapter *sc = arg1;
7434 	struct sbuf *sb;
7435 	int rc;
7436 	uint16_t mtus[NMTUS];
7437 
7438 	rc = sysctl_wire_old_buffer(req, 0);
7439 	if (rc != 0)
7440 		return (rc);
7441 
7442 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7443 	if (sb == NULL)
7444 		return (ENOMEM);
7445 
7446 	t4_read_mtu_tbl(sc, mtus, NULL);
7447 
7448 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
7449 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
7450 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
7451 	    mtus[14], mtus[15]);
7452 
7453 	rc = sbuf_finish(sb);
7454 	sbuf_delete(sb);
7455 
7456 	return (rc);
7457 }
7458 
7459 static int
7460 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
7461 {
7462 	struct adapter *sc = arg1;
7463 	struct sbuf *sb;
7464 	int rc, i;
7465 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
7466 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
7467 	static const char *tx_stats[MAX_PM_NSTATS] = {
7468 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
7469 		"Tx FIFO wait", NULL, "Tx latency"
7470 	};
7471 	static const char *rx_stats[MAX_PM_NSTATS] = {
7472 		"Read:", "Write bypass:", "Write mem:", "Flush:",
7473 		"Rx FIFO wait", NULL, "Rx latency"
7474 	};
7475 
7476 	rc = sysctl_wire_old_buffer(req, 0);
7477 	if (rc != 0)
7478 		return (rc);
7479 
7480 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7481 	if (sb == NULL)
7482 		return (ENOMEM);
7483 
7484 	t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
7485 	t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
7486 
7487 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
7488 	for (i = 0; i < 4; i++) {
7489 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7490 		    tx_cyc[i]);
7491 	}
7492 
7493 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
7494 	for (i = 0; i < 4; i++) {
7495 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7496 		    rx_cyc[i]);
7497 	}
7498 
7499 	if (chip_id(sc) > CHELSIO_T5) {
7500 		sbuf_printf(sb,
7501 		    "\n              Total wait      Total occupancy");
7502 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7503 		    tx_cyc[i]);
7504 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7505 		    rx_cyc[i]);
7506 
7507 		i += 2;
7508 		MPASS(i < nitems(tx_stats));
7509 
7510 		sbuf_printf(sb,
7511 		    "\n                   Reads           Total wait");
7512 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
7513 		    tx_cyc[i]);
7514 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
7515 		    rx_cyc[i]);
7516 	}
7517 
7518 	rc = sbuf_finish(sb);
7519 	sbuf_delete(sb);
7520 
7521 	return (rc);
7522 }
7523 
7524 static int
7525 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
7526 {
7527 	struct adapter *sc = arg1;
7528 	struct sbuf *sb;
7529 	int rc;
7530 	struct tp_rdma_stats stats;
7531 
7532 	rc = sysctl_wire_old_buffer(req, 0);
7533 	if (rc != 0)
7534 		return (rc);
7535 
7536 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7537 	if (sb == NULL)
7538 		return (ENOMEM);
7539 
7540 	mtx_lock(&sc->reg_lock);
7541 	t4_tp_get_rdma_stats(sc, &stats, 0);
7542 	mtx_unlock(&sc->reg_lock);
7543 
7544 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
7545 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
7546 
7547 	rc = sbuf_finish(sb);
7548 	sbuf_delete(sb);
7549 
7550 	return (rc);
7551 }
7552 
7553 static int
7554 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
7555 {
7556 	struct adapter *sc = arg1;
7557 	struct sbuf *sb;
7558 	int rc;
7559 	struct tp_tcp_stats v4, v6;
7560 
7561 	rc = sysctl_wire_old_buffer(req, 0);
7562 	if (rc != 0)
7563 		return (rc);
7564 
7565 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7566 	if (sb == NULL)
7567 		return (ENOMEM);
7568 
7569 	mtx_lock(&sc->reg_lock);
7570 	t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
7571 	mtx_unlock(&sc->reg_lock);
7572 
7573 	sbuf_printf(sb,
7574 	    "                                IP                 IPv6\n");
7575 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
7576 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
7577 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
7578 	    v4.tcp_in_segs, v6.tcp_in_segs);
7579 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
7580 	    v4.tcp_out_segs, v6.tcp_out_segs);
7581 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
7582 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
7583 
7584 	rc = sbuf_finish(sb);
7585 	sbuf_delete(sb);
7586 
7587 	return (rc);
7588 }
7589 
7590 static int
7591 sysctl_tids(SYSCTL_HANDLER_ARGS)
7592 {
7593 	struct adapter *sc = arg1;
7594 	struct sbuf *sb;
7595 	int rc;
7596 	struct tid_info *t = &sc->tids;
7597 
7598 	rc = sysctl_wire_old_buffer(req, 0);
7599 	if (rc != 0)
7600 		return (rc);
7601 
7602 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7603 	if (sb == NULL)
7604 		return (ENOMEM);
7605 
7606 	if (t->natids) {
7607 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
7608 		    t->atids_in_use);
7609 	}
7610 
7611 	if (t->ntids) {
7612 		sbuf_printf(sb, "TID range: ");
7613 		if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
7614 			uint32_t b, hb;
7615 
7616 			if (chip_id(sc) <= CHELSIO_T5) {
7617 				b = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
7618 				hb = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
7619 			} else {
7620 				b = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
7621 				hb = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
7622 			}
7623 
7624 			if (b)
7625 				sbuf_printf(sb, "0-%u, ", b - 1);
7626 			sbuf_printf(sb, "%u-%u", hb, t->ntids - 1);
7627 		} else
7628 			sbuf_printf(sb, "0-%u", t->ntids - 1);
7629 		sbuf_printf(sb, ", in use: %u\n",
7630 		    atomic_load_acq_int(&t->tids_in_use));
7631 	}
7632 
7633 	if (t->nstids) {
7634 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
7635 		    t->stid_base + t->nstids - 1, t->stids_in_use);
7636 	}
7637 
7638 	if (t->nftids) {
7639 		sbuf_printf(sb, "FTID range: %u-%u\n", t->ftid_base,
7640 		    t->ftid_base + t->nftids - 1);
7641 	}
7642 
7643 	if (t->netids) {
7644 		sbuf_printf(sb, "ETID range: %u-%u\n", t->etid_base,
7645 		    t->etid_base + t->netids - 1);
7646 	}
7647 
7648 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users",
7649 	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4),
7650 	    t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6));
7651 
7652 	rc = sbuf_finish(sb);
7653 	sbuf_delete(sb);
7654 
7655 	return (rc);
7656 }
7657 
7658 static int
7659 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
7660 {
7661 	struct adapter *sc = arg1;
7662 	struct sbuf *sb;
7663 	int rc;
7664 	struct tp_err_stats stats;
7665 
7666 	rc = sysctl_wire_old_buffer(req, 0);
7667 	if (rc != 0)
7668 		return (rc);
7669 
7670 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
7671 	if (sb == NULL)
7672 		return (ENOMEM);
7673 
7674 	mtx_lock(&sc->reg_lock);
7675 	t4_tp_get_err_stats(sc, &stats, 0);
7676 	mtx_unlock(&sc->reg_lock);
7677 
7678 	if (sc->chip_params->nchan > 2) {
7679 		sbuf_printf(sb, "                 channel 0  channel 1"
7680 		    "  channel 2  channel 3\n");
7681 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
7682 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
7683 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
7684 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
7685 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
7686 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
7687 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
7688 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
7689 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
7690 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
7691 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
7692 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
7693 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
7694 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
7695 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
7696 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
7697 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
7698 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
7699 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
7700 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
7701 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
7702 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
7703 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
7704 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
7705 	} else {
7706 		sbuf_printf(sb, "                 channel 0  channel 1\n");
7707 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
7708 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
7709 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
7710 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
7711 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
7712 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
7713 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
7714 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
7715 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
7716 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
7717 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
7718 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
7719 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
7720 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
7721 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
7722 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
7723 	}
7724 
7725 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
7726 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
7727 
7728 	rc = sbuf_finish(sb);
7729 	sbuf_delete(sb);
7730 
7731 	return (rc);
7732 }
7733 
7734 static int
7735 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
7736 {
7737 	struct adapter *sc = arg1;
7738 	struct tp_params *tpp = &sc->params.tp;
7739 	u_int mask;
7740 	int rc;
7741 
7742 	mask = tpp->la_mask >> 16;
7743 	rc = sysctl_handle_int(oidp, &mask, 0, req);
7744 	if (rc != 0 || req->newptr == NULL)
7745 		return (rc);
7746 	if (mask > 0xffff)
7747 		return (EINVAL);
7748 	tpp->la_mask = mask << 16;
7749 	t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U, tpp->la_mask);
7750 
7751 	return (0);
7752 }
7753 
7754 struct field_desc {
7755 	const char *name;
7756 	u_int start;
7757 	u_int width;
7758 };
7759 
7760 static void
7761 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
7762 {
7763 	char buf[32];
7764 	int line_size = 0;
7765 
7766 	while (f->name) {
7767 		uint64_t mask = (1ULL << f->width) - 1;
7768 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
7769 		    ((uintmax_t)v >> f->start) & mask);
7770 
7771 		if (line_size + len >= 79) {
7772 			line_size = 8;
7773 			sbuf_printf(sb, "\n        ");
7774 		}
7775 		sbuf_printf(sb, "%s ", buf);
7776 		line_size += len + 1;
7777 		f++;
7778 	}
7779 	sbuf_printf(sb, "\n");
7780 }
7781 
7782 static const struct field_desc tp_la0[] = {
7783 	{ "RcfOpCodeOut", 60, 4 },
7784 	{ "State", 56, 4 },
7785 	{ "WcfState", 52, 4 },
7786 	{ "RcfOpcSrcOut", 50, 2 },
7787 	{ "CRxError", 49, 1 },
7788 	{ "ERxError", 48, 1 },
7789 	{ "SanityFailed", 47, 1 },
7790 	{ "SpuriousMsg", 46, 1 },
7791 	{ "FlushInputMsg", 45, 1 },
7792 	{ "FlushInputCpl", 44, 1 },
7793 	{ "RssUpBit", 43, 1 },
7794 	{ "RssFilterHit", 42, 1 },
7795 	{ "Tid", 32, 10 },
7796 	{ "InitTcb", 31, 1 },
7797 	{ "LineNumber", 24, 7 },
7798 	{ "Emsg", 23, 1 },
7799 	{ "EdataOut", 22, 1 },
7800 	{ "Cmsg", 21, 1 },
7801 	{ "CdataOut", 20, 1 },
7802 	{ "EreadPdu", 19, 1 },
7803 	{ "CreadPdu", 18, 1 },
7804 	{ "TunnelPkt", 17, 1 },
7805 	{ "RcfPeerFin", 16, 1 },
7806 	{ "RcfReasonOut", 12, 4 },
7807 	{ "TxCchannel", 10, 2 },
7808 	{ "RcfTxChannel", 8, 2 },
7809 	{ "RxEchannel", 6, 2 },
7810 	{ "RcfRxChannel", 5, 1 },
7811 	{ "RcfDataOutSrdy", 4, 1 },
7812 	{ "RxDvld", 3, 1 },
7813 	{ "RxOoDvld", 2, 1 },
7814 	{ "RxCongestion", 1, 1 },
7815 	{ "TxCongestion", 0, 1 },
7816 	{ NULL }
7817 };
7818 
7819 static const struct field_desc tp_la1[] = {
7820 	{ "CplCmdIn", 56, 8 },
7821 	{ "CplCmdOut", 48, 8 },
7822 	{ "ESynOut", 47, 1 },
7823 	{ "EAckOut", 46, 1 },
7824 	{ "EFinOut", 45, 1 },
7825 	{ "ERstOut", 44, 1 },
7826 	{ "SynIn", 43, 1 },
7827 	{ "AckIn", 42, 1 },
7828 	{ "FinIn", 41, 1 },
7829 	{ "RstIn", 40, 1 },
7830 	{ "DataIn", 39, 1 },
7831 	{ "DataInVld", 38, 1 },
7832 	{ "PadIn", 37, 1 },
7833 	{ "RxBufEmpty", 36, 1 },
7834 	{ "RxDdp", 35, 1 },
7835 	{ "RxFbCongestion", 34, 1 },
7836 	{ "TxFbCongestion", 33, 1 },
7837 	{ "TxPktSumSrdy", 32, 1 },
7838 	{ "RcfUlpType", 28, 4 },
7839 	{ "Eread", 27, 1 },
7840 	{ "Ebypass", 26, 1 },
7841 	{ "Esave", 25, 1 },
7842 	{ "Static0", 24, 1 },
7843 	{ "Cread", 23, 1 },
7844 	{ "Cbypass", 22, 1 },
7845 	{ "Csave", 21, 1 },
7846 	{ "CPktOut", 20, 1 },
7847 	{ "RxPagePoolFull", 18, 2 },
7848 	{ "RxLpbkPkt", 17, 1 },
7849 	{ "TxLpbkPkt", 16, 1 },
7850 	{ "RxVfValid", 15, 1 },
7851 	{ "SynLearned", 14, 1 },
7852 	{ "SetDelEntry", 13, 1 },
7853 	{ "SetInvEntry", 12, 1 },
7854 	{ "CpcmdDvld", 11, 1 },
7855 	{ "CpcmdSave", 10, 1 },
7856 	{ "RxPstructsFull", 8, 2 },
7857 	{ "EpcmdDvld", 7, 1 },
7858 	{ "EpcmdFlush", 6, 1 },
7859 	{ "EpcmdTrimPrefix", 5, 1 },
7860 	{ "EpcmdTrimPostfix", 4, 1 },
7861 	{ "ERssIp4Pkt", 3, 1 },
7862 	{ "ERssIp6Pkt", 2, 1 },
7863 	{ "ERssTcpUdpPkt", 1, 1 },
7864 	{ "ERssFceFipPkt", 0, 1 },
7865 	{ NULL }
7866 };
7867 
7868 static const struct field_desc tp_la2[] = {
7869 	{ "CplCmdIn", 56, 8 },
7870 	{ "MpsVfVld", 55, 1 },
7871 	{ "MpsPf", 52, 3 },
7872 	{ "MpsVf", 44, 8 },
7873 	{ "SynIn", 43, 1 },
7874 	{ "AckIn", 42, 1 },
7875 	{ "FinIn", 41, 1 },
7876 	{ "RstIn", 40, 1 },
7877 	{ "DataIn", 39, 1 },
7878 	{ "DataInVld", 38, 1 },
7879 	{ "PadIn", 37, 1 },
7880 	{ "RxBufEmpty", 36, 1 },
7881 	{ "RxDdp", 35, 1 },
7882 	{ "RxFbCongestion", 34, 1 },
7883 	{ "TxFbCongestion", 33, 1 },
7884 	{ "TxPktSumSrdy", 32, 1 },
7885 	{ "RcfUlpType", 28, 4 },
7886 	{ "Eread", 27, 1 },
7887 	{ "Ebypass", 26, 1 },
7888 	{ "Esave", 25, 1 },
7889 	{ "Static0", 24, 1 },
7890 	{ "Cread", 23, 1 },
7891 	{ "Cbypass", 22, 1 },
7892 	{ "Csave", 21, 1 },
7893 	{ "CPktOut", 20, 1 },
7894 	{ "RxPagePoolFull", 18, 2 },
7895 	{ "RxLpbkPkt", 17, 1 },
7896 	{ "TxLpbkPkt", 16, 1 },
7897 	{ "RxVfValid", 15, 1 },
7898 	{ "SynLearned", 14, 1 },
7899 	{ "SetDelEntry", 13, 1 },
7900 	{ "SetInvEntry", 12, 1 },
7901 	{ "CpcmdDvld", 11, 1 },
7902 	{ "CpcmdSave", 10, 1 },
7903 	{ "RxPstructsFull", 8, 2 },
7904 	{ "EpcmdDvld", 7, 1 },
7905 	{ "EpcmdFlush", 6, 1 },
7906 	{ "EpcmdTrimPrefix", 5, 1 },
7907 	{ "EpcmdTrimPostfix", 4, 1 },
7908 	{ "ERssIp4Pkt", 3, 1 },
7909 	{ "ERssIp6Pkt", 2, 1 },
7910 	{ "ERssTcpUdpPkt", 1, 1 },
7911 	{ "ERssFceFipPkt", 0, 1 },
7912 	{ NULL }
7913 };
7914 
7915 static void
7916 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
7917 {
7918 
7919 	field_desc_show(sb, *p, tp_la0);
7920 }
7921 
7922 static void
7923 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
7924 {
7925 
7926 	if (idx)
7927 		sbuf_printf(sb, "\n");
7928 	field_desc_show(sb, p[0], tp_la0);
7929 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7930 		field_desc_show(sb, p[1], tp_la0);
7931 }
7932 
7933 static void
7934 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
7935 {
7936 
7937 	if (idx)
7938 		sbuf_printf(sb, "\n");
7939 	field_desc_show(sb, p[0], tp_la0);
7940 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
7941 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
7942 }
7943 
7944 static int
7945 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
7946 {
7947 	struct adapter *sc = arg1;
7948 	struct sbuf *sb;
7949 	uint64_t *buf, *p;
7950 	int rc;
7951 	u_int i, inc;
7952 	void (*show_func)(struct sbuf *, uint64_t *, int);
7953 
7954 	rc = sysctl_wire_old_buffer(req, 0);
7955 	if (rc != 0)
7956 		return (rc);
7957 
7958 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
7959 	if (sb == NULL)
7960 		return (ENOMEM);
7961 
7962 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
7963 
7964 	t4_tp_read_la(sc, buf, NULL);
7965 	p = buf;
7966 
7967 	switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
7968 	case 2:
7969 		inc = 2;
7970 		show_func = tp_la_show2;
7971 		break;
7972 	case 3:
7973 		inc = 2;
7974 		show_func = tp_la_show3;
7975 		break;
7976 	default:
7977 		inc = 1;
7978 		show_func = tp_la_show;
7979 	}
7980 
7981 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
7982 		(*show_func)(sb, p, i);
7983 
7984 	rc = sbuf_finish(sb);
7985 	sbuf_delete(sb);
7986 	free(buf, M_CXGBE);
7987 	return (rc);
7988 }
7989 
7990 static int
7991 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
7992 {
7993 	struct adapter *sc = arg1;
7994 	struct sbuf *sb;
7995 	int rc;
7996 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
7997 
7998 	rc = sysctl_wire_old_buffer(req, 0);
7999 	if (rc != 0)
8000 		return (rc);
8001 
8002 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
8003 	if (sb == NULL)
8004 		return (ENOMEM);
8005 
8006 	t4_get_chan_txrate(sc, nrate, orate);
8007 
8008 	if (sc->chip_params->nchan > 2) {
8009 		sbuf_printf(sb, "              channel 0   channel 1"
8010 		    "   channel 2   channel 3\n");
8011 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
8012 		    nrate[0], nrate[1], nrate[2], nrate[3]);
8013 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
8014 		    orate[0], orate[1], orate[2], orate[3]);
8015 	} else {
8016 		sbuf_printf(sb, "              channel 0   channel 1\n");
8017 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
8018 		    nrate[0], nrate[1]);
8019 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
8020 		    orate[0], orate[1]);
8021 	}
8022 
8023 	rc = sbuf_finish(sb);
8024 	sbuf_delete(sb);
8025 
8026 	return (rc);
8027 }
8028 
8029 static int
8030 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
8031 {
8032 	struct adapter *sc = arg1;
8033 	struct sbuf *sb;
8034 	uint32_t *buf, *p;
8035 	int rc, i;
8036 
8037 	rc = sysctl_wire_old_buffer(req, 0);
8038 	if (rc != 0)
8039 		return (rc);
8040 
8041 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8042 	if (sb == NULL)
8043 		return (ENOMEM);
8044 
8045 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
8046 	    M_ZERO | M_WAITOK);
8047 
8048 	t4_ulprx_read_la(sc, buf);
8049 	p = buf;
8050 
8051 	sbuf_printf(sb, "      Pcmd        Type   Message"
8052 	    "                Data");
8053 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
8054 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
8055 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
8056 	}
8057 
8058 	rc = sbuf_finish(sb);
8059 	sbuf_delete(sb);
8060 	free(buf, M_CXGBE);
8061 	return (rc);
8062 }
8063 
8064 static int
8065 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
8066 {
8067 	struct adapter *sc = arg1;
8068 	struct sbuf *sb;
8069 	int rc, v;
8070 
8071 	MPASS(chip_id(sc) >= CHELSIO_T5);
8072 
8073 	rc = sysctl_wire_old_buffer(req, 0);
8074 	if (rc != 0)
8075 		return (rc);
8076 
8077 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8078 	if (sb == NULL)
8079 		return (ENOMEM);
8080 
8081 	v = t4_read_reg(sc, A_SGE_STAT_CFG);
8082 	if (G_STATSOURCE_T5(v) == 7) {
8083 		int mode;
8084 
8085 		mode = is_t5(sc) ? G_STATMODE(v) : G_T6_STATMODE(v);
8086 		if (mode == 0) {
8087 			sbuf_printf(sb, "total %d, incomplete %d",
8088 			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
8089 			    t4_read_reg(sc, A_SGE_STAT_MATCH));
8090 		} else if (mode == 1) {
8091 			sbuf_printf(sb, "total %d, data overflow %d",
8092 			    t4_read_reg(sc, A_SGE_STAT_TOTAL),
8093 			    t4_read_reg(sc, A_SGE_STAT_MATCH));
8094 		} else {
8095 			sbuf_printf(sb, "unknown mode %d", mode);
8096 		}
8097 	}
8098 	rc = sbuf_finish(sb);
8099 	sbuf_delete(sb);
8100 
8101 	return (rc);
8102 }
8103 
8104 static int
8105 sysctl_tc_params(SYSCTL_HANDLER_ARGS)
8106 {
8107 	struct adapter *sc = arg1;
8108 	struct tx_cl_rl_params tc;
8109 	struct sbuf *sb;
8110 	int i, rc, port_id, mbps, gbps;
8111 
8112 	rc = sysctl_wire_old_buffer(req, 0);
8113 	if (rc != 0)
8114 		return (rc);
8115 
8116 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8117 	if (sb == NULL)
8118 		return (ENOMEM);
8119 
8120 	port_id = arg2 >> 16;
8121 	MPASS(port_id < sc->params.nports);
8122 	MPASS(sc->port[port_id] != NULL);
8123 	i = arg2 & 0xffff;
8124 	MPASS(i < sc->chip_params->nsched_cls);
8125 
8126 	mtx_lock(&sc->tc_lock);
8127 	tc = sc->port[port_id]->sched_params->cl_rl[i];
8128 	mtx_unlock(&sc->tc_lock);
8129 
8130 	if (tc.flags & TX_CLRL_ERROR) {
8131 		sbuf_printf(sb, "error");
8132 		goto done;
8133 	}
8134 
8135 	if (tc.ratemode == SCHED_CLASS_RATEMODE_REL) {
8136 		/* XXX: top speed or actual link speed? */
8137 		gbps = port_top_speed(sc->port[port_id]);
8138 		sbuf_printf(sb, " %u%% of %uGbps", tc.maxrate, gbps);
8139 	} else if (tc.ratemode == SCHED_CLASS_RATEMODE_ABS) {
8140 		switch (tc.rateunit) {
8141 		case SCHED_CLASS_RATEUNIT_BITS:
8142 			mbps = tc.maxrate / 1000;
8143 			gbps = tc.maxrate / 1000000;
8144 			if (tc.maxrate == gbps * 1000000)
8145 				sbuf_printf(sb, " %uGbps", gbps);
8146 			else if (tc.maxrate == mbps * 1000)
8147 				sbuf_printf(sb, " %uMbps", mbps);
8148 			else
8149 				sbuf_printf(sb, " %uKbps", tc.maxrate);
8150 			break;
8151 		case SCHED_CLASS_RATEUNIT_PKTS:
8152 			sbuf_printf(sb, " %upps", tc.maxrate);
8153 			break;
8154 		default:
8155 			rc = ENXIO;
8156 			goto done;
8157 		}
8158 	}
8159 
8160 	switch (tc.mode) {
8161 	case SCHED_CLASS_MODE_CLASS:
8162 		sbuf_printf(sb, " aggregate");
8163 		break;
8164 	case SCHED_CLASS_MODE_FLOW:
8165 		sbuf_printf(sb, " per-flow");
8166 		break;
8167 	default:
8168 		rc = ENXIO;
8169 		goto done;
8170 	}
8171 
8172 done:
8173 	if (rc == 0)
8174 		rc = sbuf_finish(sb);
8175 	sbuf_delete(sb);
8176 
8177 	return (rc);
8178 }
8179 #endif
8180 
8181 #ifdef TCP_OFFLOAD
8182 static void
8183 unit_conv(char *buf, size_t len, u_int val, u_int factor)
8184 {
8185 	u_int rem = val % factor;
8186 
8187 	if (rem == 0)
8188 		snprintf(buf, len, "%u", val / factor);
8189 	else {
8190 		while (rem % 10 == 0)
8191 			rem /= 10;
8192 		snprintf(buf, len, "%u.%u", val / factor, rem);
8193 	}
8194 }
8195 
8196 static int
8197 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
8198 {
8199 	struct adapter *sc = arg1;
8200 	char buf[16];
8201 	u_int res, re;
8202 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8203 
8204 	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
8205 	switch (arg2) {
8206 	case 0:
8207 		/* timer_tick */
8208 		re = G_TIMERRESOLUTION(res);
8209 		break;
8210 	case 1:
8211 		/* TCP timestamp tick */
8212 		re = G_TIMESTAMPRESOLUTION(res);
8213 		break;
8214 	case 2:
8215 		/* DACK tick */
8216 		re = G_DELAYEDACKRESOLUTION(res);
8217 		break;
8218 	default:
8219 		return (EDOOFUS);
8220 	}
8221 
8222 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
8223 
8224 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
8225 }
8226 
8227 static int
8228 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
8229 {
8230 	struct adapter *sc = arg1;
8231 	u_int res, dack_re, v;
8232 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8233 
8234 	res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
8235 	dack_re = G_DELAYEDACKRESOLUTION(res);
8236 	v = ((cclk_ps << dack_re) / 1000000) * t4_read_reg(sc, A_TP_DACK_TIMER);
8237 
8238 	return (sysctl_handle_int(oidp, &v, 0, req));
8239 }
8240 
8241 static int
8242 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
8243 {
8244 	struct adapter *sc = arg1;
8245 	int reg = arg2;
8246 	u_int tre;
8247 	u_long tp_tick_us, v;
8248 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
8249 
8250 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
8251 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
8252 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
8253 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
8254 
8255 	tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
8256 	tp_tick_us = (cclk_ps << tre) / 1000000;
8257 
8258 	if (reg == A_TP_INIT_SRTT)
8259 		v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
8260 	else
8261 		v = tp_tick_us * t4_read_reg(sc, reg);
8262 
8263 	return (sysctl_handle_long(oidp, &v, 0, req));
8264 }
8265 
8266 /*
8267  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
8268  * passed to this function.
8269  */
8270 static int
8271 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
8272 {
8273 	struct adapter *sc = arg1;
8274 	int idx = arg2;
8275 	u_int v;
8276 
8277 	MPASS(idx >= 0 && idx <= 24);
8278 
8279 	v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
8280 
8281 	return (sysctl_handle_int(oidp, &v, 0, req));
8282 }
8283 
8284 static int
8285 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
8286 {
8287 	struct adapter *sc = arg1;
8288 	int idx = arg2;
8289 	u_int shift, v, r;
8290 
8291 	MPASS(idx >= 0 && idx < 16);
8292 
8293 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
8294 	shift = (idx & 3) << 3;
8295 	v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
8296 
8297 	return (sysctl_handle_int(oidp, &v, 0, req));
8298 }
8299 
8300 static int
8301 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
8302 {
8303 	struct vi_info *vi = arg1;
8304 	struct adapter *sc = vi->pi->adapter;
8305 	int idx, rc, i;
8306 	struct sge_ofld_rxq *ofld_rxq;
8307 	uint8_t v;
8308 
8309 	idx = vi->ofld_tmr_idx;
8310 
8311 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8312 	if (rc != 0 || req->newptr == NULL)
8313 		return (rc);
8314 
8315 	if (idx < 0 || idx >= SGE_NTIMERS)
8316 		return (EINVAL);
8317 
8318 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8319 	    "t4otmr");
8320 	if (rc)
8321 		return (rc);
8322 
8323 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
8324 	for_each_ofld_rxq(vi, i, ofld_rxq) {
8325 #ifdef atomic_store_rel_8
8326 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
8327 #else
8328 		ofld_rxq->iq.intr_params = v;
8329 #endif
8330 	}
8331 	vi->ofld_tmr_idx = idx;
8332 
8333 	end_synchronized_op(sc, LOCK_HELD);
8334 	return (0);
8335 }
8336 
8337 static int
8338 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
8339 {
8340 	struct vi_info *vi = arg1;
8341 	struct adapter *sc = vi->pi->adapter;
8342 	int idx, rc;
8343 
8344 	idx = vi->ofld_pktc_idx;
8345 
8346 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8347 	if (rc != 0 || req->newptr == NULL)
8348 		return (rc);
8349 
8350 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8351 		return (EINVAL);
8352 
8353 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8354 	    "t4opktc");
8355 	if (rc)
8356 		return (rc);
8357 
8358 	if (vi->flags & VI_INIT_DONE)
8359 		rc = EBUSY; /* cannot be changed once the queues are created */
8360 	else
8361 		vi->ofld_pktc_idx = idx;
8362 
8363 	end_synchronized_op(sc, LOCK_HELD);
8364 	return (rc);
8365 }
8366 #endif
8367 
8368 static uint32_t
8369 fconf_iconf_to_mode(uint32_t fconf, uint32_t iconf)
8370 {
8371 	uint32_t mode;
8372 
8373 	mode = T4_FILTER_IPv4 | T4_FILTER_IPv6 | T4_FILTER_IP_SADDR |
8374 	    T4_FILTER_IP_DADDR | T4_FILTER_IP_SPORT | T4_FILTER_IP_DPORT;
8375 
8376 	if (fconf & F_FRAGMENTATION)
8377 		mode |= T4_FILTER_IP_FRAGMENT;
8378 
8379 	if (fconf & F_MPSHITTYPE)
8380 		mode |= T4_FILTER_MPS_HIT_TYPE;
8381 
8382 	if (fconf & F_MACMATCH)
8383 		mode |= T4_FILTER_MAC_IDX;
8384 
8385 	if (fconf & F_ETHERTYPE)
8386 		mode |= T4_FILTER_ETH_TYPE;
8387 
8388 	if (fconf & F_PROTOCOL)
8389 		mode |= T4_FILTER_IP_PROTO;
8390 
8391 	if (fconf & F_TOS)
8392 		mode |= T4_FILTER_IP_TOS;
8393 
8394 	if (fconf & F_VLAN)
8395 		mode |= T4_FILTER_VLAN;
8396 
8397 	if (fconf & F_VNIC_ID) {
8398 		mode |= T4_FILTER_VNIC;
8399 		if (iconf & F_VNIC)
8400 			mode |= T4_FILTER_IC_VNIC;
8401 	}
8402 
8403 	if (fconf & F_PORT)
8404 		mode |= T4_FILTER_PORT;
8405 
8406 	if (fconf & F_FCOE)
8407 		mode |= T4_FILTER_FCoE;
8408 
8409 	return (mode);
8410 }
8411 
8412 static uint32_t
8413 mode_to_fconf(uint32_t mode)
8414 {
8415 	uint32_t fconf = 0;
8416 
8417 	if (mode & T4_FILTER_IP_FRAGMENT)
8418 		fconf |= F_FRAGMENTATION;
8419 
8420 	if (mode & T4_FILTER_MPS_HIT_TYPE)
8421 		fconf |= F_MPSHITTYPE;
8422 
8423 	if (mode & T4_FILTER_MAC_IDX)
8424 		fconf |= F_MACMATCH;
8425 
8426 	if (mode & T4_FILTER_ETH_TYPE)
8427 		fconf |= F_ETHERTYPE;
8428 
8429 	if (mode & T4_FILTER_IP_PROTO)
8430 		fconf |= F_PROTOCOL;
8431 
8432 	if (mode & T4_FILTER_IP_TOS)
8433 		fconf |= F_TOS;
8434 
8435 	if (mode & T4_FILTER_VLAN)
8436 		fconf |= F_VLAN;
8437 
8438 	if (mode & T4_FILTER_VNIC)
8439 		fconf |= F_VNIC_ID;
8440 
8441 	if (mode & T4_FILTER_PORT)
8442 		fconf |= F_PORT;
8443 
8444 	if (mode & T4_FILTER_FCoE)
8445 		fconf |= F_FCOE;
8446 
8447 	return (fconf);
8448 }
8449 
8450 static uint32_t
8451 mode_to_iconf(uint32_t mode)
8452 {
8453 
8454 	if (mode & T4_FILTER_IC_VNIC)
8455 		return (F_VNIC);
8456 	return (0);
8457 }
8458 
8459 static int check_fspec_against_fconf_iconf(struct adapter *sc,
8460     struct t4_filter_specification *fs)
8461 {
8462 	struct tp_params *tpp = &sc->params.tp;
8463 	uint32_t fconf = 0;
8464 
8465 	if (fs->val.frag || fs->mask.frag)
8466 		fconf |= F_FRAGMENTATION;
8467 
8468 	if (fs->val.matchtype || fs->mask.matchtype)
8469 		fconf |= F_MPSHITTYPE;
8470 
8471 	if (fs->val.macidx || fs->mask.macidx)
8472 		fconf |= F_MACMATCH;
8473 
8474 	if (fs->val.ethtype || fs->mask.ethtype)
8475 		fconf |= F_ETHERTYPE;
8476 
8477 	if (fs->val.proto || fs->mask.proto)
8478 		fconf |= F_PROTOCOL;
8479 
8480 	if (fs->val.tos || fs->mask.tos)
8481 		fconf |= F_TOS;
8482 
8483 	if (fs->val.vlan_vld || fs->mask.vlan_vld)
8484 		fconf |= F_VLAN;
8485 
8486 	if (fs->val.ovlan_vld || fs->mask.ovlan_vld) {
8487 		fconf |= F_VNIC_ID;
8488 		if (tpp->ingress_config & F_VNIC)
8489 			return (EINVAL);
8490 	}
8491 
8492 	if (fs->val.pfvf_vld || fs->mask.pfvf_vld) {
8493 		fconf |= F_VNIC_ID;
8494 		if ((tpp->ingress_config & F_VNIC) == 0)
8495 			return (EINVAL);
8496 	}
8497 
8498 	if (fs->val.iport || fs->mask.iport)
8499 		fconf |= F_PORT;
8500 
8501 	if (fs->val.fcoe || fs->mask.fcoe)
8502 		fconf |= F_FCOE;
8503 
8504 	if ((tpp->vlan_pri_map | fconf) != tpp->vlan_pri_map)
8505 		return (E2BIG);
8506 
8507 	return (0);
8508 }
8509 
8510 static int
8511 get_filter_mode(struct adapter *sc, uint32_t *mode)
8512 {
8513 	struct tp_params *tpp = &sc->params.tp;
8514 
8515 	/*
8516 	 * We trust the cached values of the relevant TP registers.  This means
8517 	 * things work reliably only if writes to those registers are always via
8518 	 * t4_set_filter_mode.
8519 	 */
8520 	*mode = fconf_iconf_to_mode(tpp->vlan_pri_map, tpp->ingress_config);
8521 
8522 	return (0);
8523 }
8524 
8525 static int
8526 set_filter_mode(struct adapter *sc, uint32_t mode)
8527 {
8528 	struct tp_params *tpp = &sc->params.tp;
8529 	uint32_t fconf, iconf;
8530 	int rc;
8531 
8532 	iconf = mode_to_iconf(mode);
8533 	if ((iconf ^ tpp->ingress_config) & F_VNIC) {
8534 		/*
8535 		 * For now we just complain if A_TP_INGRESS_CONFIG is not
8536 		 * already set to the correct value for the requested filter
8537 		 * mode.  It's not clear if it's safe to write to this register
8538 		 * on the fly.  (And we trust the cached value of the register).
8539 		 */
8540 		return (EBUSY);
8541 	}
8542 
8543 	fconf = mode_to_fconf(mode);
8544 
8545 	rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
8546 	    "t4setfm");
8547 	if (rc)
8548 		return (rc);
8549 
8550 	if (sc->tids.ftids_in_use > 0) {
8551 		rc = EBUSY;
8552 		goto done;
8553 	}
8554 
8555 #ifdef TCP_OFFLOAD
8556 	if (uld_active(sc, ULD_TOM)) {
8557 		rc = EBUSY;
8558 		goto done;
8559 	}
8560 #endif
8561 
8562 	rc = -t4_set_filter_mode(sc, fconf, true);
8563 done:
8564 	end_synchronized_op(sc, LOCK_HELD);
8565 	return (rc);
8566 }
8567 
8568 static inline uint64_t
8569 get_filter_hits(struct adapter *sc, uint32_t fid)
8570 {
8571 	uint32_t tcb_addr;
8572 
8573 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE) +
8574 	    (fid + sc->tids.ftid_base) * TCB_SIZE;
8575 
8576 	if (is_t4(sc)) {
8577 		uint64_t hits;
8578 
8579 		read_via_memwin(sc, 0, tcb_addr + 16, (uint32_t *)&hits, 8);
8580 		return (be64toh(hits));
8581 	} else {
8582 		uint32_t hits;
8583 
8584 		read_via_memwin(sc, 0, tcb_addr + 24, &hits, 4);
8585 		return (be32toh(hits));
8586 	}
8587 }
8588 
8589 static int
8590 get_filter(struct adapter *sc, struct t4_filter *t)
8591 {
8592 	int i, rc, nfilters = sc->tids.nftids;
8593 	struct filter_entry *f;
8594 
8595 	rc = begin_synchronized_op(sc, NULL, HOLD_LOCK | SLEEP_OK | INTR_OK,
8596 	    "t4getf");
8597 	if (rc)
8598 		return (rc);
8599 
8600 	if (sc->tids.ftids_in_use == 0 || sc->tids.ftid_tab == NULL ||
8601 	    t->idx >= nfilters) {
8602 		t->idx = 0xffffffff;
8603 		goto done;
8604 	}
8605 
8606 	f = &sc->tids.ftid_tab[t->idx];
8607 	for (i = t->idx; i < nfilters; i++, f++) {
8608 		if (f->valid) {
8609 			t->idx = i;
8610 			t->l2tidx = f->l2t ? f->l2t->idx : 0;
8611 			t->smtidx = f->smtidx;
8612 			if (f->fs.hitcnts)
8613 				t->hits = get_filter_hits(sc, t->idx);
8614 			else
8615 				t->hits = UINT64_MAX;
8616 			t->fs = f->fs;
8617 
8618 			goto done;
8619 		}
8620 	}
8621 
8622 	t->idx = 0xffffffff;
8623 done:
8624 	end_synchronized_op(sc, LOCK_HELD);
8625 	return (0);
8626 }
8627 
8628 static int
8629 set_filter(struct adapter *sc, struct t4_filter *t)
8630 {
8631 	unsigned int nfilters, nports;
8632 	struct filter_entry *f;
8633 	int i, rc;
8634 
8635 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4setf");
8636 	if (rc)
8637 		return (rc);
8638 
8639 	nfilters = sc->tids.nftids;
8640 	nports = sc->params.nports;
8641 
8642 	if (nfilters == 0) {
8643 		rc = ENOTSUP;
8644 		goto done;
8645 	}
8646 
8647 	if (t->idx >= nfilters) {
8648 		rc = EINVAL;
8649 		goto done;
8650 	}
8651 
8652 	/* Validate against the global filter mode and ingress config */
8653 	rc = check_fspec_against_fconf_iconf(sc, &t->fs);
8654 	if (rc != 0)
8655 		goto done;
8656 
8657 	if (t->fs.action == FILTER_SWITCH && t->fs.eport >= nports) {
8658 		rc = EINVAL;
8659 		goto done;
8660 	}
8661 
8662 	if (t->fs.val.iport >= nports) {
8663 		rc = EINVAL;
8664 		goto done;
8665 	}
8666 
8667 	/* Can't specify an iq if not steering to it */
8668 	if (!t->fs.dirsteer && t->fs.iq) {
8669 		rc = EINVAL;
8670 		goto done;
8671 	}
8672 
8673 	/* IPv6 filter idx must be 4 aligned */
8674 	if (t->fs.type == 1 &&
8675 	    ((t->idx & 0x3) || t->idx + 4 >= nfilters)) {
8676 		rc = EINVAL;
8677 		goto done;
8678 	}
8679 
8680 	if (!(sc->flags & FULL_INIT_DONE) &&
8681 	    ((rc = adapter_full_init(sc)) != 0))
8682 		goto done;
8683 
8684 	if (sc->tids.ftid_tab == NULL) {
8685 		KASSERT(sc->tids.ftids_in_use == 0,
8686 		    ("%s: no memory allocated but filters_in_use > 0",
8687 		    __func__));
8688 
8689 		sc->tids.ftid_tab = malloc(sizeof (struct filter_entry) *
8690 		    nfilters, M_CXGBE, M_NOWAIT | M_ZERO);
8691 		if (sc->tids.ftid_tab == NULL) {
8692 			rc = ENOMEM;
8693 			goto done;
8694 		}
8695 		mtx_init(&sc->tids.ftid_lock, "T4 filters", 0, MTX_DEF);
8696 	}
8697 
8698 	for (i = 0; i < 4; i++) {
8699 		f = &sc->tids.ftid_tab[t->idx + i];
8700 
8701 		if (f->pending || f->valid) {
8702 			rc = EBUSY;
8703 			goto done;
8704 		}
8705 		if (f->locked) {
8706 			rc = EPERM;
8707 			goto done;
8708 		}
8709 
8710 		if (t->fs.type == 0)
8711 			break;
8712 	}
8713 
8714 	f = &sc->tids.ftid_tab[t->idx];
8715 	f->fs = t->fs;
8716 
8717 	rc = set_filter_wr(sc, t->idx);
8718 done:
8719 	end_synchronized_op(sc, 0);
8720 
8721 	if (rc == 0) {
8722 		mtx_lock(&sc->tids.ftid_lock);
8723 		for (;;) {
8724 			if (f->pending == 0) {
8725 				rc = f->valid ? 0 : EIO;
8726 				break;
8727 			}
8728 
8729 			if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8730 			    PCATCH, "t4setfw", 0)) {
8731 				rc = EINPROGRESS;
8732 				break;
8733 			}
8734 		}
8735 		mtx_unlock(&sc->tids.ftid_lock);
8736 	}
8737 	return (rc);
8738 }
8739 
8740 static int
8741 del_filter(struct adapter *sc, struct t4_filter *t)
8742 {
8743 	unsigned int nfilters;
8744 	struct filter_entry *f;
8745 	int rc;
8746 
8747 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4delf");
8748 	if (rc)
8749 		return (rc);
8750 
8751 	nfilters = sc->tids.nftids;
8752 
8753 	if (nfilters == 0) {
8754 		rc = ENOTSUP;
8755 		goto done;
8756 	}
8757 
8758 	if (sc->tids.ftid_tab == NULL || sc->tids.ftids_in_use == 0 ||
8759 	    t->idx >= nfilters) {
8760 		rc = EINVAL;
8761 		goto done;
8762 	}
8763 
8764 	if (!(sc->flags & FULL_INIT_DONE)) {
8765 		rc = EAGAIN;
8766 		goto done;
8767 	}
8768 
8769 	f = &sc->tids.ftid_tab[t->idx];
8770 
8771 	if (f->pending) {
8772 		rc = EBUSY;
8773 		goto done;
8774 	}
8775 	if (f->locked) {
8776 		rc = EPERM;
8777 		goto done;
8778 	}
8779 
8780 	if (f->valid) {
8781 		t->fs = f->fs;	/* extra info for the caller */
8782 		rc = del_filter_wr(sc, t->idx);
8783 	}
8784 
8785 done:
8786 	end_synchronized_op(sc, 0);
8787 
8788 	if (rc == 0) {
8789 		mtx_lock(&sc->tids.ftid_lock);
8790 		for (;;) {
8791 			if (f->pending == 0) {
8792 				rc = f->valid ? EIO : 0;
8793 				break;
8794 			}
8795 
8796 			if (mtx_sleep(&sc->tids.ftid_tab, &sc->tids.ftid_lock,
8797 			    PCATCH, "t4delfw", 0)) {
8798 				rc = EINPROGRESS;
8799 				break;
8800 			}
8801 		}
8802 		mtx_unlock(&sc->tids.ftid_lock);
8803 	}
8804 
8805 	return (rc);
8806 }
8807 
8808 static void
8809 clear_filter(struct filter_entry *f)
8810 {
8811 	if (f->l2t)
8812 		t4_l2t_release(f->l2t);
8813 
8814 	bzero(f, sizeof (*f));
8815 }
8816 
8817 static int
8818 set_filter_wr(struct adapter *sc, int fidx)
8819 {
8820 	struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8821 	struct fw_filter_wr *fwr;
8822 	unsigned int ftid, vnic_vld, vnic_vld_mask;
8823 	struct wrq_cookie cookie;
8824 
8825 	ASSERT_SYNCHRONIZED_OP(sc);
8826 
8827 	if (f->fs.newdmac || f->fs.newvlan) {
8828 		/* This filter needs an L2T entry; allocate one. */
8829 		f->l2t = t4_l2t_alloc_switching(sc->l2t);
8830 		if (f->l2t == NULL)
8831 			return (EAGAIN);
8832 		if (t4_l2t_set_switching(sc, f->l2t, f->fs.vlan, f->fs.eport,
8833 		    f->fs.dmac)) {
8834 			t4_l2t_release(f->l2t);
8835 			f->l2t = NULL;
8836 			return (ENOMEM);
8837 		}
8838 	}
8839 
8840 	/* Already validated against fconf, iconf */
8841 	MPASS((f->fs.val.pfvf_vld & f->fs.val.ovlan_vld) == 0);
8842 	MPASS((f->fs.mask.pfvf_vld & f->fs.mask.ovlan_vld) == 0);
8843 	if (f->fs.val.pfvf_vld || f->fs.val.ovlan_vld)
8844 		vnic_vld = 1;
8845 	else
8846 		vnic_vld = 0;
8847 	if (f->fs.mask.pfvf_vld || f->fs.mask.ovlan_vld)
8848 		vnic_vld_mask = 1;
8849 	else
8850 		vnic_vld_mask = 0;
8851 
8852 	ftid = sc->tids.ftid_base + fidx;
8853 
8854 	fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8855 	if (fwr == NULL)
8856 		return (ENOMEM);
8857 	bzero(fwr, sizeof(*fwr));
8858 
8859 	fwr->op_pkd = htobe32(V_FW_WR_OP(FW_FILTER_WR));
8860 	fwr->len16_pkd = htobe32(FW_LEN16(*fwr));
8861 	fwr->tid_to_iq =
8862 	    htobe32(V_FW_FILTER_WR_TID(ftid) |
8863 		V_FW_FILTER_WR_RQTYPE(f->fs.type) |
8864 		V_FW_FILTER_WR_NOREPLY(0) |
8865 		V_FW_FILTER_WR_IQ(f->fs.iq));
8866 	fwr->del_filter_to_l2tix =
8867 	    htobe32(V_FW_FILTER_WR_RPTTID(f->fs.rpttid) |
8868 		V_FW_FILTER_WR_DROP(f->fs.action == FILTER_DROP) |
8869 		V_FW_FILTER_WR_DIRSTEER(f->fs.dirsteer) |
8870 		V_FW_FILTER_WR_MASKHASH(f->fs.maskhash) |
8871 		V_FW_FILTER_WR_DIRSTEERHASH(f->fs.dirsteerhash) |
8872 		V_FW_FILTER_WR_LPBK(f->fs.action == FILTER_SWITCH) |
8873 		V_FW_FILTER_WR_DMAC(f->fs.newdmac) |
8874 		V_FW_FILTER_WR_SMAC(f->fs.newsmac) |
8875 		V_FW_FILTER_WR_INSVLAN(f->fs.newvlan == VLAN_INSERT ||
8876 		    f->fs.newvlan == VLAN_REWRITE) |
8877 		V_FW_FILTER_WR_RMVLAN(f->fs.newvlan == VLAN_REMOVE ||
8878 		    f->fs.newvlan == VLAN_REWRITE) |
8879 		V_FW_FILTER_WR_HITCNTS(f->fs.hitcnts) |
8880 		V_FW_FILTER_WR_TXCHAN(f->fs.eport) |
8881 		V_FW_FILTER_WR_PRIO(f->fs.prio) |
8882 		V_FW_FILTER_WR_L2TIX(f->l2t ? f->l2t->idx : 0));
8883 	fwr->ethtype = htobe16(f->fs.val.ethtype);
8884 	fwr->ethtypem = htobe16(f->fs.mask.ethtype);
8885 	fwr->frag_to_ovlan_vldm =
8886 	    (V_FW_FILTER_WR_FRAG(f->fs.val.frag) |
8887 		V_FW_FILTER_WR_FRAGM(f->fs.mask.frag) |
8888 		V_FW_FILTER_WR_IVLAN_VLD(f->fs.val.vlan_vld) |
8889 		V_FW_FILTER_WR_OVLAN_VLD(vnic_vld) |
8890 		V_FW_FILTER_WR_IVLAN_VLDM(f->fs.mask.vlan_vld) |
8891 		V_FW_FILTER_WR_OVLAN_VLDM(vnic_vld_mask));
8892 	fwr->smac_sel = 0;
8893 	fwr->rx_chan_rx_rpl_iq = htobe16(V_FW_FILTER_WR_RX_CHAN(0) |
8894 	    V_FW_FILTER_WR_RX_RPL_IQ(sc->sge.fwq.abs_id));
8895 	fwr->maci_to_matchtypem =
8896 	    htobe32(V_FW_FILTER_WR_MACI(f->fs.val.macidx) |
8897 		V_FW_FILTER_WR_MACIM(f->fs.mask.macidx) |
8898 		V_FW_FILTER_WR_FCOE(f->fs.val.fcoe) |
8899 		V_FW_FILTER_WR_FCOEM(f->fs.mask.fcoe) |
8900 		V_FW_FILTER_WR_PORT(f->fs.val.iport) |
8901 		V_FW_FILTER_WR_PORTM(f->fs.mask.iport) |
8902 		V_FW_FILTER_WR_MATCHTYPE(f->fs.val.matchtype) |
8903 		V_FW_FILTER_WR_MATCHTYPEM(f->fs.mask.matchtype));
8904 	fwr->ptcl = f->fs.val.proto;
8905 	fwr->ptclm = f->fs.mask.proto;
8906 	fwr->ttyp = f->fs.val.tos;
8907 	fwr->ttypm = f->fs.mask.tos;
8908 	fwr->ivlan = htobe16(f->fs.val.vlan);
8909 	fwr->ivlanm = htobe16(f->fs.mask.vlan);
8910 	fwr->ovlan = htobe16(f->fs.val.vnic);
8911 	fwr->ovlanm = htobe16(f->fs.mask.vnic);
8912 	bcopy(f->fs.val.dip, fwr->lip, sizeof (fwr->lip));
8913 	bcopy(f->fs.mask.dip, fwr->lipm, sizeof (fwr->lipm));
8914 	bcopy(f->fs.val.sip, fwr->fip, sizeof (fwr->fip));
8915 	bcopy(f->fs.mask.sip, fwr->fipm, sizeof (fwr->fipm));
8916 	fwr->lp = htobe16(f->fs.val.dport);
8917 	fwr->lpm = htobe16(f->fs.mask.dport);
8918 	fwr->fp = htobe16(f->fs.val.sport);
8919 	fwr->fpm = htobe16(f->fs.mask.sport);
8920 	if (f->fs.newsmac)
8921 		bcopy(f->fs.smac, fwr->sma, sizeof (fwr->sma));
8922 
8923 	f->pending = 1;
8924 	sc->tids.ftids_in_use++;
8925 
8926 	commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8927 	return (0);
8928 }
8929 
8930 static int
8931 del_filter_wr(struct adapter *sc, int fidx)
8932 {
8933 	struct filter_entry *f = &sc->tids.ftid_tab[fidx];
8934 	struct fw_filter_wr *fwr;
8935 	unsigned int ftid;
8936 	struct wrq_cookie cookie;
8937 
8938 	ftid = sc->tids.ftid_base + fidx;
8939 
8940 	fwr = start_wrq_wr(&sc->sge.mgmtq, howmany(sizeof(*fwr), 16), &cookie);
8941 	if (fwr == NULL)
8942 		return (ENOMEM);
8943 	bzero(fwr, sizeof (*fwr));
8944 
8945 	t4_mk_filtdelwr(ftid, fwr, sc->sge.fwq.abs_id);
8946 
8947 	f->pending = 1;
8948 	commit_wrq_wr(&sc->sge.mgmtq, fwr, &cookie);
8949 	return (0);
8950 }
8951 
8952 int
8953 t4_filter_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8954 {
8955 	struct adapter *sc = iq->adapter;
8956 	const struct cpl_set_tcb_rpl *rpl = (const void *)(rss + 1);
8957 	unsigned int idx = GET_TID(rpl);
8958 	unsigned int rc;
8959 	struct filter_entry *f;
8960 
8961 	KASSERT(m == NULL, ("%s: payload with opcode %02x", __func__,
8962 	    rss->opcode));
8963 	MPASS(iq == &sc->sge.fwq);
8964 	MPASS(is_ftid(sc, idx));
8965 
8966 	idx -= sc->tids.ftid_base;
8967 	f = &sc->tids.ftid_tab[idx];
8968 	rc = G_COOKIE(rpl->cookie);
8969 
8970 	mtx_lock(&sc->tids.ftid_lock);
8971 	if (rc == FW_FILTER_WR_FLT_ADDED) {
8972 		KASSERT(f->pending, ("%s: filter[%u] isn't pending.",
8973 		    __func__, idx));
8974 		f->smtidx = (be64toh(rpl->oldval) >> 24) & 0xff;
8975 		f->pending = 0;  /* asynchronous setup completed */
8976 		f->valid = 1;
8977 	} else {
8978 		if (rc != FW_FILTER_WR_FLT_DELETED) {
8979 			/* Add or delete failed, display an error */
8980 			log(LOG_ERR,
8981 			    "filter %u setup failed with error %u\n",
8982 			    idx, rc);
8983 		}
8984 
8985 		clear_filter(f);
8986 		sc->tids.ftids_in_use--;
8987 	}
8988 	wakeup(&sc->tids.ftid_tab);
8989 	mtx_unlock(&sc->tids.ftid_lock);
8990 
8991 	return (0);
8992 }
8993 
8994 static int
8995 set_tcb_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
8996 {
8997 
8998 	MPASS(iq->set_tcb_rpl != NULL);
8999 	return (iq->set_tcb_rpl(iq, rss, m));
9000 }
9001 
9002 static int
9003 l2t_write_rpl(struct sge_iq *iq, const struct rss_header *rss, struct mbuf *m)
9004 {
9005 
9006 	MPASS(iq->l2t_write_rpl != NULL);
9007 	return (iq->l2t_write_rpl(iq, rss, m));
9008 }
9009 
9010 static int
9011 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
9012 {
9013 	int rc;
9014 
9015 	if (cntxt->cid > M_CTXTQID)
9016 		return (EINVAL);
9017 
9018 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
9019 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
9020 		return (EINVAL);
9021 
9022 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
9023 	if (rc)
9024 		return (rc);
9025 
9026 	if (sc->flags & FW_OK) {
9027 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
9028 		    &cntxt->data[0]);
9029 		if (rc == 0)
9030 			goto done;
9031 	}
9032 
9033 	/*
9034 	 * Read via firmware failed or wasn't even attempted.  Read directly via
9035 	 * the backdoor.
9036 	 */
9037 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
9038 done:
9039 	end_synchronized_op(sc, 0);
9040 	return (rc);
9041 }
9042 
9043 static int
9044 load_fw(struct adapter *sc, struct t4_data *fw)
9045 {
9046 	int rc;
9047 	uint8_t *fw_data;
9048 
9049 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
9050 	if (rc)
9051 		return (rc);
9052 
9053 	/*
9054 	 * The firmware, with the sole exception of the memory parity error
9055 	 * handler, runs from memory and not flash.  It is almost always safe to
9056 	 * install a new firmware on a running system.  Just set bit 1 in
9057 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
9058 	 */
9059 	if (sc->flags & FULL_INIT_DONE &&
9060 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
9061 		rc = EBUSY;
9062 		goto done;
9063 	}
9064 
9065 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
9066 	if (fw_data == NULL) {
9067 		rc = ENOMEM;
9068 		goto done;
9069 	}
9070 
9071 	rc = copyin(fw->data, fw_data, fw->len);
9072 	if (rc == 0)
9073 		rc = -t4_load_fw(sc, fw_data, fw->len);
9074 
9075 	free(fw_data, M_CXGBE);
9076 done:
9077 	end_synchronized_op(sc, 0);
9078 	return (rc);
9079 }
9080 
9081 static int
9082 load_cfg(struct adapter *sc, struct t4_data *cfg)
9083 {
9084 	int rc;
9085 	uint8_t *cfg_data = NULL;
9086 
9087 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9088 	if (rc)
9089 		return (rc);
9090 
9091 	if (cfg->len == 0) {
9092 		/* clear */
9093 		rc = -t4_load_cfg(sc, NULL, 0);
9094 		goto done;
9095 	}
9096 
9097 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
9098 	if (cfg_data == NULL) {
9099 		rc = ENOMEM;
9100 		goto done;
9101 	}
9102 
9103 	rc = copyin(cfg->data, cfg_data, cfg->len);
9104 	if (rc == 0)
9105 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
9106 
9107 	free(cfg_data, M_CXGBE);
9108 done:
9109 	end_synchronized_op(sc, 0);
9110 	return (rc);
9111 }
9112 
9113 static int
9114 load_boot(struct adapter *sc, struct t4_bootrom *br)
9115 {
9116 	int rc;
9117 	uint8_t *br_data = NULL;
9118 	u_int offset;
9119 
9120 	if (br->len > 1024 * 1024)
9121 		return (EFBIG);
9122 
9123 	if (br->pf_offset == 0) {
9124 		/* pfidx */
9125 		if (br->pfidx_addr > 7)
9126 			return (EINVAL);
9127 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
9128 		    A_PCIE_PF_EXPROM_OFST)));
9129 	} else if (br->pf_offset == 1) {
9130 		/* offset */
9131 		offset = G_OFFSET(br->pfidx_addr);
9132 	} else {
9133 		return (EINVAL);
9134 	}
9135 
9136 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
9137 	if (rc)
9138 		return (rc);
9139 
9140 	if (br->len == 0) {
9141 		/* clear */
9142 		rc = -t4_load_boot(sc, NULL, offset, 0);
9143 		goto done;
9144 	}
9145 
9146 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
9147 	if (br_data == NULL) {
9148 		rc = ENOMEM;
9149 		goto done;
9150 	}
9151 
9152 	rc = copyin(br->data, br_data, br->len);
9153 	if (rc == 0)
9154 		rc = -t4_load_boot(sc, br_data, offset, br->len);
9155 
9156 	free(br_data, M_CXGBE);
9157 done:
9158 	end_synchronized_op(sc, 0);
9159 	return (rc);
9160 }
9161 
9162 static int
9163 load_bootcfg(struct adapter *sc, struct t4_data *bc)
9164 {
9165 	int rc;
9166 	uint8_t *bc_data = NULL;
9167 
9168 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
9169 	if (rc)
9170 		return (rc);
9171 
9172 	if (bc->len == 0) {
9173 		/* clear */
9174 		rc = -t4_load_bootcfg(sc, NULL, 0);
9175 		goto done;
9176 	}
9177 
9178 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
9179 	if (bc_data == NULL) {
9180 		rc = ENOMEM;
9181 		goto done;
9182 	}
9183 
9184 	rc = copyin(bc->data, bc_data, bc->len);
9185 	if (rc == 0)
9186 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
9187 
9188 	free(bc_data, M_CXGBE);
9189 done:
9190 	end_synchronized_op(sc, 0);
9191 	return (rc);
9192 }
9193 
9194 static int
9195 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
9196 {
9197 	int rc;
9198 	struct cudbg_init *cudbg;
9199 	void *handle, *buf;
9200 
9201 	/* buf is large, don't block if no memory is available */
9202 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
9203 	if (buf == NULL)
9204 		return (ENOMEM);
9205 
9206 	handle = cudbg_alloc_handle();
9207 	if (handle == NULL) {
9208 		rc = ENOMEM;
9209 		goto done;
9210 	}
9211 
9212 	cudbg = cudbg_get_init(handle);
9213 	cudbg->adap = sc;
9214 	cudbg->print = (cudbg_print_cb)printf;
9215 
9216 #ifndef notyet
9217 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
9218 	    __func__, dump->wr_flash, dump->len, dump->data);
9219 #endif
9220 
9221 	if (dump->wr_flash)
9222 		cudbg->use_flash = 1;
9223 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
9224 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
9225 
9226 	rc = cudbg_collect(handle, buf, &dump->len);
9227 	if (rc != 0)
9228 		goto done;
9229 
9230 	rc = copyout(buf, dump->data, dump->len);
9231 done:
9232 	cudbg_free_handle(handle);
9233 	free(buf, M_CXGBE);
9234 	return (rc);
9235 }
9236 
9237 #define MAX_READ_BUF_SIZE (128 * 1024)
9238 static int
9239 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
9240 {
9241 	uint32_t addr, remaining, n;
9242 	uint32_t *buf;
9243 	int rc;
9244 	uint8_t *dst;
9245 
9246 	rc = validate_mem_range(sc, mr->addr, mr->len);
9247 	if (rc != 0)
9248 		return (rc);
9249 
9250 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
9251 	addr = mr->addr;
9252 	remaining = mr->len;
9253 	dst = (void *)mr->data;
9254 
9255 	while (remaining) {
9256 		n = min(remaining, MAX_READ_BUF_SIZE);
9257 		read_via_memwin(sc, 2, addr, buf, n);
9258 
9259 		rc = copyout(buf, dst, n);
9260 		if (rc != 0)
9261 			break;
9262 
9263 		dst += n;
9264 		remaining -= n;
9265 		addr += n;
9266 	}
9267 
9268 	free(buf, M_CXGBE);
9269 	return (rc);
9270 }
9271 #undef MAX_READ_BUF_SIZE
9272 
9273 static int
9274 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
9275 {
9276 	int rc;
9277 
9278 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
9279 		return (EINVAL);
9280 
9281 	if (i2cd->len > sizeof(i2cd->data))
9282 		return (EFBIG);
9283 
9284 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
9285 	if (rc)
9286 		return (rc);
9287 	rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
9288 	    i2cd->offset, i2cd->len, &i2cd->data[0]);
9289 	end_synchronized_op(sc, 0);
9290 
9291 	return (rc);
9292 }
9293 
9294 int
9295 t4_os_find_pci_capability(struct adapter *sc, int cap)
9296 {
9297 	int i;
9298 
9299 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
9300 }
9301 
9302 int
9303 t4_os_pci_save_state(struct adapter *sc)
9304 {
9305 	device_t dev;
9306 	struct pci_devinfo *dinfo;
9307 
9308 	dev = sc->dev;
9309 	dinfo = device_get_ivars(dev);
9310 
9311 	pci_cfg_save(dev, dinfo, 0);
9312 	return (0);
9313 }
9314 
9315 int
9316 t4_os_pci_restore_state(struct adapter *sc)
9317 {
9318 	device_t dev;
9319 	struct pci_devinfo *dinfo;
9320 
9321 	dev = sc->dev;
9322 	dinfo = device_get_ivars(dev);
9323 
9324 	pci_cfg_restore(dev, dinfo);
9325 	return (0);
9326 }
9327 
9328 void
9329 t4_os_portmod_changed(struct port_info *pi)
9330 {
9331 	struct adapter *sc = pi->adapter;
9332 	struct vi_info *vi;
9333 	struct ifnet *ifp;
9334 	static const char *mod_str[] = {
9335 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
9336 	};
9337 
9338 	PORT_LOCK(pi);
9339 	build_medialist(pi, &pi->media);
9340 	PORT_UNLOCK(pi);
9341 	vi = &pi->vi[0];
9342 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
9343 		init_l1cfg(pi);
9344 		end_synchronized_op(sc, LOCK_HELD);
9345 	}
9346 
9347 	ifp = vi->ifp;
9348 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
9349 		if_printf(ifp, "transceiver unplugged.\n");
9350 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
9351 		if_printf(ifp, "unknown transceiver inserted.\n");
9352 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
9353 		if_printf(ifp, "unsupported transceiver inserted.\n");
9354 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
9355 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
9356 		    port_top_speed(pi), mod_str[pi->mod_type]);
9357 	} else {
9358 		if_printf(ifp, "transceiver (type %d) inserted.\n",
9359 		    pi->mod_type);
9360 	}
9361 }
9362 
9363 void
9364 t4_os_link_changed(struct port_info *pi)
9365 {
9366 	struct vi_info *vi;
9367 	struct ifnet *ifp;
9368 	struct link_config *lc;
9369 	int v;
9370 
9371 	for_each_vi(pi, v, vi) {
9372 		ifp = vi->ifp;
9373 		if (ifp == NULL)
9374 			continue;
9375 
9376 		lc = &pi->link_cfg;
9377 		if (lc->link_ok) {
9378 			ifp->if_baudrate = IF_Mbps(lc->speed);
9379 			if_link_state_change(ifp, LINK_STATE_UP);
9380 		} else {
9381 			if_link_state_change(ifp, LINK_STATE_DOWN);
9382 		}
9383 	}
9384 }
9385 
9386 void
9387 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
9388 {
9389 	struct adapter *sc;
9390 
9391 	sx_slock(&t4_list_lock);
9392 	SLIST_FOREACH(sc, &t4_list, link) {
9393 		/*
9394 		 * func should not make any assumptions about what state sc is
9395 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
9396 		 */
9397 		func(sc, arg);
9398 	}
9399 	sx_sunlock(&t4_list_lock);
9400 }
9401 
9402 static int
9403 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
9404     struct thread *td)
9405 {
9406 	int rc;
9407 	struct adapter *sc = dev->si_drv1;
9408 
9409 	rc = priv_check(td, PRIV_DRIVER);
9410 	if (rc != 0)
9411 		return (rc);
9412 
9413 	switch (cmd) {
9414 	case CHELSIO_T4_GETREG: {
9415 		struct t4_reg *edata = (struct t4_reg *)data;
9416 
9417 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9418 			return (EFAULT);
9419 
9420 		if (edata->size == 4)
9421 			edata->val = t4_read_reg(sc, edata->addr);
9422 		else if (edata->size == 8)
9423 			edata->val = t4_read_reg64(sc, edata->addr);
9424 		else
9425 			return (EINVAL);
9426 
9427 		break;
9428 	}
9429 	case CHELSIO_T4_SETREG: {
9430 		struct t4_reg *edata = (struct t4_reg *)data;
9431 
9432 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
9433 			return (EFAULT);
9434 
9435 		if (edata->size == 4) {
9436 			if (edata->val & 0xffffffff00000000)
9437 				return (EINVAL);
9438 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
9439 		} else if (edata->size == 8)
9440 			t4_write_reg64(sc, edata->addr, edata->val);
9441 		else
9442 			return (EINVAL);
9443 		break;
9444 	}
9445 	case CHELSIO_T4_REGDUMP: {
9446 		struct t4_regdump *regs = (struct t4_regdump *)data;
9447 		int reglen = t4_get_regs_len(sc);
9448 		uint8_t *buf;
9449 
9450 		if (regs->len < reglen) {
9451 			regs->len = reglen; /* hint to the caller */
9452 			return (ENOBUFS);
9453 		}
9454 
9455 		regs->len = reglen;
9456 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
9457 		get_regs(sc, regs, buf);
9458 		rc = copyout(buf, regs->data, reglen);
9459 		free(buf, M_CXGBE);
9460 		break;
9461 	}
9462 	case CHELSIO_T4_GET_FILTER_MODE:
9463 		rc = get_filter_mode(sc, (uint32_t *)data);
9464 		break;
9465 	case CHELSIO_T4_SET_FILTER_MODE:
9466 		rc = set_filter_mode(sc, *(uint32_t *)data);
9467 		break;
9468 	case CHELSIO_T4_GET_FILTER:
9469 		rc = get_filter(sc, (struct t4_filter *)data);
9470 		break;
9471 	case CHELSIO_T4_SET_FILTER:
9472 		rc = set_filter(sc, (struct t4_filter *)data);
9473 		break;
9474 	case CHELSIO_T4_DEL_FILTER:
9475 		rc = del_filter(sc, (struct t4_filter *)data);
9476 		break;
9477 	case CHELSIO_T4_GET_SGE_CONTEXT:
9478 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
9479 		break;
9480 	case CHELSIO_T4_LOAD_FW:
9481 		rc = load_fw(sc, (struct t4_data *)data);
9482 		break;
9483 	case CHELSIO_T4_GET_MEM:
9484 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
9485 		break;
9486 	case CHELSIO_T4_GET_I2C:
9487 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
9488 		break;
9489 	case CHELSIO_T4_CLEAR_STATS: {
9490 		int i, v;
9491 		u_int port_id = *(uint32_t *)data;
9492 		struct port_info *pi;
9493 		struct vi_info *vi;
9494 
9495 		if (port_id >= sc->params.nports)
9496 			return (EINVAL);
9497 		pi = sc->port[port_id];
9498 		if (pi == NULL)
9499 			return (EIO);
9500 
9501 		/* MAC stats */
9502 		t4_clr_port_stats(sc, pi->tx_chan);
9503 		pi->tx_parse_error = 0;
9504 		mtx_lock(&sc->reg_lock);
9505 		for_each_vi(pi, v, vi) {
9506 			if (vi->flags & VI_INIT_DONE)
9507 				t4_clr_vi_stats(sc, vi->viid);
9508 		}
9509 		mtx_unlock(&sc->reg_lock);
9510 
9511 		/*
9512 		 * Since this command accepts a port, clear stats for
9513 		 * all VIs on this port.
9514 		 */
9515 		for_each_vi(pi, v, vi) {
9516 			if (vi->flags & VI_INIT_DONE) {
9517 				struct sge_rxq *rxq;
9518 				struct sge_txq *txq;
9519 				struct sge_wrq *wrq;
9520 
9521 				for_each_rxq(vi, i, rxq) {
9522 #if defined(INET) || defined(INET6)
9523 					rxq->lro.lro_queued = 0;
9524 					rxq->lro.lro_flushed = 0;
9525 #endif
9526 					rxq->rxcsum = 0;
9527 					rxq->vlan_extraction = 0;
9528 				}
9529 
9530 				for_each_txq(vi, i, txq) {
9531 					txq->txcsum = 0;
9532 					txq->tso_wrs = 0;
9533 					txq->vlan_insertion = 0;
9534 					txq->imm_wrs = 0;
9535 					txq->sgl_wrs = 0;
9536 					txq->txpkt_wrs = 0;
9537 					txq->txpkts0_wrs = 0;
9538 					txq->txpkts1_wrs = 0;
9539 					txq->txpkts0_pkts = 0;
9540 					txq->txpkts1_pkts = 0;
9541 					mp_ring_reset_stats(txq->r);
9542 				}
9543 
9544 #ifdef TCP_OFFLOAD
9545 				/* nothing to clear for each ofld_rxq */
9546 
9547 				for_each_ofld_txq(vi, i, wrq) {
9548 					wrq->tx_wrs_direct = 0;
9549 					wrq->tx_wrs_copied = 0;
9550 				}
9551 #endif
9552 
9553 				if (IS_MAIN_VI(vi)) {
9554 					wrq = &sc->sge.ctrlq[pi->port_id];
9555 					wrq->tx_wrs_direct = 0;
9556 					wrq->tx_wrs_copied = 0;
9557 				}
9558 			}
9559 		}
9560 		break;
9561 	}
9562 	case CHELSIO_T4_SCHED_CLASS:
9563 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
9564 		break;
9565 	case CHELSIO_T4_SCHED_QUEUE:
9566 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
9567 		break;
9568 	case CHELSIO_T4_GET_TRACER:
9569 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
9570 		break;
9571 	case CHELSIO_T4_SET_TRACER:
9572 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
9573 		break;
9574 	case CHELSIO_T4_LOAD_CFG:
9575 		rc = load_cfg(sc, (struct t4_data *)data);
9576 		break;
9577 	case CHELSIO_T4_LOAD_BOOT:
9578 		rc = load_boot(sc, (struct t4_bootrom *)data);
9579 		break;
9580 	case CHELSIO_T4_LOAD_BOOTCFG:
9581 		rc = load_bootcfg(sc, (struct t4_data *)data);
9582 		break;
9583 	case CHELSIO_T4_CUDBG_DUMP:
9584 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
9585 		break;
9586 	default:
9587 		rc = ENOTTY;
9588 	}
9589 
9590 	return (rc);
9591 }
9592 
9593 void
9594 t4_db_full(struct adapter *sc)
9595 {
9596 
9597 	CXGBE_UNIMPLEMENTED(__func__);
9598 }
9599 
9600 void
9601 t4_db_dropped(struct adapter *sc)
9602 {
9603 
9604 	CXGBE_UNIMPLEMENTED(__func__);
9605 }
9606 
9607 #ifdef TCP_OFFLOAD
9608 static int
9609 toe_capability(struct vi_info *vi, int enable)
9610 {
9611 	int rc;
9612 	struct port_info *pi = vi->pi;
9613 	struct adapter *sc = pi->adapter;
9614 
9615 	ASSERT_SYNCHRONIZED_OP(sc);
9616 
9617 	if (!is_offload(sc))
9618 		return (ENODEV);
9619 
9620 	if (enable) {
9621 		if ((vi->ifp->if_capenable & IFCAP_TOE) != 0) {
9622 			/* TOE is already enabled. */
9623 			return (0);
9624 		}
9625 
9626 		/*
9627 		 * We need the port's queues around so that we're able to send
9628 		 * and receive CPLs to/from the TOE even if the ifnet for this
9629 		 * port has never been UP'd administratively.
9630 		 */
9631 		if (!(vi->flags & VI_INIT_DONE)) {
9632 			rc = vi_full_init(vi);
9633 			if (rc)
9634 				return (rc);
9635 		}
9636 		if (!(pi->vi[0].flags & VI_INIT_DONE)) {
9637 			rc = vi_full_init(&pi->vi[0]);
9638 			if (rc)
9639 				return (rc);
9640 		}
9641 
9642 		if (isset(&sc->offload_map, pi->port_id)) {
9643 			/* TOE is enabled on another VI of this port. */
9644 			pi->uld_vis++;
9645 			return (0);
9646 		}
9647 
9648 		if (!uld_active(sc, ULD_TOM)) {
9649 			rc = t4_activate_uld(sc, ULD_TOM);
9650 			if (rc == EAGAIN) {
9651 				log(LOG_WARNING,
9652 				    "You must kldload t4_tom.ko before trying "
9653 				    "to enable TOE on a cxgbe interface.\n");
9654 			}
9655 			if (rc != 0)
9656 				return (rc);
9657 			KASSERT(sc->tom_softc != NULL,
9658 			    ("%s: TOM activated but softc NULL", __func__));
9659 			KASSERT(uld_active(sc, ULD_TOM),
9660 			    ("%s: TOM activated but flag not set", __func__));
9661 		}
9662 
9663 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
9664 		if (!uld_active(sc, ULD_IWARP))
9665 			(void) t4_activate_uld(sc, ULD_IWARP);
9666 		if (!uld_active(sc, ULD_ISCSI))
9667 			(void) t4_activate_uld(sc, ULD_ISCSI);
9668 
9669 		pi->uld_vis++;
9670 		setbit(&sc->offload_map, pi->port_id);
9671 	} else {
9672 		pi->uld_vis--;
9673 
9674 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
9675 			return (0);
9676 
9677 		KASSERT(uld_active(sc, ULD_TOM),
9678 		    ("%s: TOM never initialized?", __func__));
9679 		clrbit(&sc->offload_map, pi->port_id);
9680 	}
9681 
9682 	return (0);
9683 }
9684 
9685 /*
9686  * Add an upper layer driver to the global list.
9687  */
9688 int
9689 t4_register_uld(struct uld_info *ui)
9690 {
9691 	int rc = 0;
9692 	struct uld_info *u;
9693 
9694 	sx_xlock(&t4_uld_list_lock);
9695 	SLIST_FOREACH(u, &t4_uld_list, link) {
9696 	    if (u->uld_id == ui->uld_id) {
9697 		    rc = EEXIST;
9698 		    goto done;
9699 	    }
9700 	}
9701 
9702 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
9703 	ui->refcount = 0;
9704 done:
9705 	sx_xunlock(&t4_uld_list_lock);
9706 	return (rc);
9707 }
9708 
9709 int
9710 t4_unregister_uld(struct uld_info *ui)
9711 {
9712 	int rc = EINVAL;
9713 	struct uld_info *u;
9714 
9715 	sx_xlock(&t4_uld_list_lock);
9716 
9717 	SLIST_FOREACH(u, &t4_uld_list, link) {
9718 	    if (u == ui) {
9719 		    if (ui->refcount > 0) {
9720 			    rc = EBUSY;
9721 			    goto done;
9722 		    }
9723 
9724 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
9725 		    rc = 0;
9726 		    goto done;
9727 	    }
9728 	}
9729 done:
9730 	sx_xunlock(&t4_uld_list_lock);
9731 	return (rc);
9732 }
9733 
9734 int
9735 t4_activate_uld(struct adapter *sc, int id)
9736 {
9737 	int rc;
9738 	struct uld_info *ui;
9739 
9740 	ASSERT_SYNCHRONIZED_OP(sc);
9741 
9742 	if (id < 0 || id > ULD_MAX)
9743 		return (EINVAL);
9744 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
9745 
9746 	sx_slock(&t4_uld_list_lock);
9747 
9748 	SLIST_FOREACH(ui, &t4_uld_list, link) {
9749 		if (ui->uld_id == id) {
9750 			if (!(sc->flags & FULL_INIT_DONE)) {
9751 				rc = adapter_full_init(sc);
9752 				if (rc != 0)
9753 					break;
9754 			}
9755 
9756 			rc = ui->activate(sc);
9757 			if (rc == 0) {
9758 				setbit(&sc->active_ulds, id);
9759 				ui->refcount++;
9760 			}
9761 			break;
9762 		}
9763 	}
9764 
9765 	sx_sunlock(&t4_uld_list_lock);
9766 
9767 	return (rc);
9768 }
9769 
9770 int
9771 t4_deactivate_uld(struct adapter *sc, int id)
9772 {
9773 	int rc;
9774 	struct uld_info *ui;
9775 
9776 	ASSERT_SYNCHRONIZED_OP(sc);
9777 
9778 	if (id < 0 || id > ULD_MAX)
9779 		return (EINVAL);
9780 	rc = ENXIO;
9781 
9782 	sx_slock(&t4_uld_list_lock);
9783 
9784 	SLIST_FOREACH(ui, &t4_uld_list, link) {
9785 		if (ui->uld_id == id) {
9786 			rc = ui->deactivate(sc);
9787 			if (rc == 0) {
9788 				clrbit(&sc->active_ulds, id);
9789 				ui->refcount--;
9790 			}
9791 			break;
9792 		}
9793 	}
9794 
9795 	sx_sunlock(&t4_uld_list_lock);
9796 
9797 	return (rc);
9798 }
9799 
9800 int
9801 uld_active(struct adapter *sc, int uld_id)
9802 {
9803 
9804 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
9805 
9806 	return (isset(&sc->active_ulds, uld_id));
9807 }
9808 #endif
9809 
9810 /*
9811  * t  = ptr to tunable.
9812  * nc = number of CPUs.
9813  * c  = compiled in default for that tunable.
9814  */
9815 static void
9816 calculate_nqueues(int *t, int nc, const int c)
9817 {
9818 	int nq;
9819 
9820 	if (*t > 0)
9821 		return;
9822 	nq = *t < 0 ? -*t : c;
9823 	*t = min(nc, nq);
9824 }
9825 
9826 /*
9827  * Come up with reasonable defaults for some of the tunables, provided they're
9828  * not set by the user (in which case we'll use the values as is).
9829  */
9830 static void
9831 tweak_tunables(void)
9832 {
9833 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
9834 
9835 	if (t4_ntxq < 1) {
9836 #ifdef RSS
9837 		t4_ntxq = rss_getnumbuckets();
9838 #else
9839 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
9840 #endif
9841 	}
9842 
9843 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
9844 
9845 	if (t4_nrxq < 1) {
9846 #ifdef RSS
9847 		t4_nrxq = rss_getnumbuckets();
9848 #else
9849 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
9850 #endif
9851 	}
9852 
9853 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
9854 
9855 #ifdef TCP_OFFLOAD
9856 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
9857 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
9858 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
9859 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
9860 
9861 	if (t4_toecaps_allowed == -1)
9862 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
9863 
9864 	if (t4_rdmacaps_allowed == -1) {
9865 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
9866 		    FW_CAPS_CONFIG_RDMA_RDMAC;
9867 	}
9868 
9869 	if (t4_iscsicaps_allowed == -1) {
9870 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
9871 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
9872 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
9873 	}
9874 
9875 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
9876 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
9877 
9878 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
9879 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
9880 #else
9881 	if (t4_toecaps_allowed == -1)
9882 		t4_toecaps_allowed = 0;
9883 
9884 	if (t4_rdmacaps_allowed == -1)
9885 		t4_rdmacaps_allowed = 0;
9886 
9887 	if (t4_iscsicaps_allowed == -1)
9888 		t4_iscsicaps_allowed = 0;
9889 #endif
9890 
9891 #ifdef DEV_NETMAP
9892 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
9893 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
9894 #endif
9895 
9896 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
9897 		t4_tmr_idx = TMR_IDX;
9898 
9899 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
9900 		t4_pktc_idx = PKTC_IDX;
9901 
9902 	if (t4_qsize_txq < 128)
9903 		t4_qsize_txq = 128;
9904 
9905 	if (t4_qsize_rxq < 128)
9906 		t4_qsize_rxq = 128;
9907 	while (t4_qsize_rxq & 7)
9908 		t4_qsize_rxq++;
9909 
9910 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
9911 
9912 	/*
9913 	 * Number of VIs to create per-port.  The first VI is the "main" regular
9914 	 * VI for the port.  The rest are additional virtual interfaces on the
9915 	 * same physical port.  Note that the main VI does not have native
9916 	 * netmap support but the extra VIs do.
9917 	 *
9918 	 * Limit the number of VIs per port to the number of available
9919 	 * MAC addresses per port.
9920 	 */
9921 	if (t4_num_vis < 1)
9922 		t4_num_vis = 1;
9923 	if (t4_num_vis > nitems(vi_mac_funcs)) {
9924 		t4_num_vis = nitems(vi_mac_funcs);
9925 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
9926 	}
9927 }
9928 
9929 #ifdef DDB
9930 static void
9931 t4_dump_tcb(struct adapter *sc, int tid)
9932 {
9933 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
9934 
9935 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
9936 	save = t4_read_reg(sc, reg);
9937 	base = sc->memwin[2].mw_base;
9938 
9939 	/* Dump TCB for the tid */
9940 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9941 	tcb_addr += tid * TCB_SIZE;
9942 
9943 	if (is_t4(sc)) {
9944 		pf = 0;
9945 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
9946 	} else {
9947 		pf = V_PFNUM(sc->pf);
9948 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
9949 	}
9950 	t4_write_reg(sc, reg, win_pos | pf);
9951 	t4_read_reg(sc, reg);
9952 
9953 	off = tcb_addr - win_pos;
9954 	for (i = 0; i < 4; i++) {
9955 		uint32_t buf[8];
9956 		for (j = 0; j < 8; j++, off += 4)
9957 			buf[j] = htonl(t4_read_reg(sc, base + off));
9958 
9959 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
9960 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
9961 		    buf[7]);
9962 	}
9963 
9964 	t4_write_reg(sc, reg, save);
9965 	t4_read_reg(sc, reg);
9966 }
9967 
9968 static void
9969 t4_dump_devlog(struct adapter *sc)
9970 {
9971 	struct devlog_params *dparams = &sc->params.devlog;
9972 	struct fw_devlog_e e;
9973 	int i, first, j, m, nentries, rc;
9974 	uint64_t ftstamp = UINT64_MAX;
9975 
9976 	if (dparams->start == 0) {
9977 		db_printf("devlog params not valid\n");
9978 		return;
9979 	}
9980 
9981 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9982 	m = fwmtype_to_hwmtype(dparams->memtype);
9983 
9984 	/* Find the first entry. */
9985 	first = -1;
9986 	for (i = 0; i < nentries && !db_pager_quit; i++) {
9987 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
9988 		    sizeof(e), (void *)&e);
9989 		if (rc != 0)
9990 			break;
9991 
9992 		if (e.timestamp == 0)
9993 			break;
9994 
9995 		e.timestamp = be64toh(e.timestamp);
9996 		if (e.timestamp < ftstamp) {
9997 			ftstamp = e.timestamp;
9998 			first = i;
9999 		}
10000 	}
10001 
10002 	if (first == -1)
10003 		return;
10004 
10005 	i = first;
10006 	do {
10007 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
10008 		    sizeof(e), (void *)&e);
10009 		if (rc != 0)
10010 			return;
10011 
10012 		if (e.timestamp == 0)
10013 			return;
10014 
10015 		e.timestamp = be64toh(e.timestamp);
10016 		e.seqno = be32toh(e.seqno);
10017 		for (j = 0; j < 8; j++)
10018 			e.params[j] = be32toh(e.params[j]);
10019 
10020 		db_printf("%10d  %15ju  %8s  %8s  ",
10021 		    e.seqno, e.timestamp,
10022 		    (e.level < nitems(devlog_level_strings) ?
10023 			devlog_level_strings[e.level] : "UNKNOWN"),
10024 		    (e.facility < nitems(devlog_facility_strings) ?
10025 			devlog_facility_strings[e.facility] : "UNKNOWN"));
10026 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
10027 		    e.params[3], e.params[4], e.params[5], e.params[6],
10028 		    e.params[7]);
10029 
10030 		if (++i == nentries)
10031 			i = 0;
10032 	} while (i != first && !db_pager_quit);
10033 }
10034 
10035 static struct command_table db_t4_table = LIST_HEAD_INITIALIZER(db_t4_table);
10036 _DB_SET(_show, t4, NULL, db_show_table, 0, &db_t4_table);
10037 
10038 DB_FUNC(devlog, db_show_devlog, db_t4_table, CS_OWN, NULL)
10039 {
10040 	device_t dev;
10041 	int t;
10042 	bool valid;
10043 
10044 	valid = false;
10045 	t = db_read_token();
10046 	if (t == tIDENT) {
10047 		dev = device_lookup_by_name(db_tok_string);
10048 		valid = true;
10049 	}
10050 	db_skip_to_eol();
10051 	if (!valid) {
10052 		db_printf("usage: show t4 devlog <nexus>\n");
10053 		return;
10054 	}
10055 
10056 	if (dev == NULL) {
10057 		db_printf("device not found\n");
10058 		return;
10059 	}
10060 
10061 	t4_dump_devlog(device_get_softc(dev));
10062 }
10063 
10064 DB_FUNC(tcb, db_show_t4tcb, db_t4_table, CS_OWN, NULL)
10065 {
10066 	device_t dev;
10067 	int radix, tid, t;
10068 	bool valid;
10069 
10070 	valid = false;
10071 	radix = db_radix;
10072 	db_radix = 10;
10073 	t = db_read_token();
10074 	if (t == tIDENT) {
10075 		dev = device_lookup_by_name(db_tok_string);
10076 		t = db_read_token();
10077 		if (t == tNUMBER) {
10078 			tid = db_tok_number;
10079 			valid = true;
10080 		}
10081 	}
10082 	db_radix = radix;
10083 	db_skip_to_eol();
10084 	if (!valid) {
10085 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
10086 		return;
10087 	}
10088 
10089 	if (dev == NULL) {
10090 		db_printf("device not found\n");
10091 		return;
10092 	}
10093 	if (tid < 0) {
10094 		db_printf("invalid tid\n");
10095 		return;
10096 	}
10097 
10098 	t4_dump_tcb(device_get_softc(dev), tid);
10099 }
10100 #endif
10101 
10102 static struct sx mlu;	/* mod load unload */
10103 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
10104 
10105 static int
10106 mod_event(module_t mod, int cmd, void *arg)
10107 {
10108 	int rc = 0;
10109 	static int loaded = 0;
10110 
10111 	switch (cmd) {
10112 	case MOD_LOAD:
10113 		sx_xlock(&mlu);
10114 		if (loaded++ == 0) {
10115 			t4_sge_modload();
10116 			t4_register_cpl_handler(CPL_SET_TCB_RPL, set_tcb_rpl);
10117 			t4_register_cpl_handler(CPL_L2T_WRITE_RPL, l2t_write_rpl);
10118 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
10119 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
10120 			sx_init(&t4_list_lock, "T4/T5 adapters");
10121 			SLIST_INIT(&t4_list);
10122 #ifdef TCP_OFFLOAD
10123 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
10124 			SLIST_INIT(&t4_uld_list);
10125 #endif
10126 			t4_tracer_modload();
10127 			tweak_tunables();
10128 		}
10129 		sx_xunlock(&mlu);
10130 		break;
10131 
10132 	case MOD_UNLOAD:
10133 		sx_xlock(&mlu);
10134 		if (--loaded == 0) {
10135 			int tries;
10136 
10137 			sx_slock(&t4_list_lock);
10138 			if (!SLIST_EMPTY(&t4_list)) {
10139 				rc = EBUSY;
10140 				sx_sunlock(&t4_list_lock);
10141 				goto done_unload;
10142 			}
10143 #ifdef TCP_OFFLOAD
10144 			sx_slock(&t4_uld_list_lock);
10145 			if (!SLIST_EMPTY(&t4_uld_list)) {
10146 				rc = EBUSY;
10147 				sx_sunlock(&t4_uld_list_lock);
10148 				sx_sunlock(&t4_list_lock);
10149 				goto done_unload;
10150 			}
10151 #endif
10152 			tries = 0;
10153 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
10154 				uprintf("%ju clusters with custom free routine "
10155 				    "still is use.\n", t4_sge_extfree_refs());
10156 				pause("t4unload", 2 * hz);
10157 			}
10158 #ifdef TCP_OFFLOAD
10159 			sx_sunlock(&t4_uld_list_lock);
10160 #endif
10161 			sx_sunlock(&t4_list_lock);
10162 
10163 			if (t4_sge_extfree_refs() == 0) {
10164 				t4_tracer_modunload();
10165 #ifdef TCP_OFFLOAD
10166 				sx_destroy(&t4_uld_list_lock);
10167 #endif
10168 				sx_destroy(&t4_list_lock);
10169 				t4_sge_modunload();
10170 				loaded = 0;
10171 			} else {
10172 				rc = EBUSY;
10173 				loaded++;	/* undo earlier decrement */
10174 			}
10175 		}
10176 done_unload:
10177 		sx_xunlock(&mlu);
10178 		break;
10179 	}
10180 
10181 	return (rc);
10182 }
10183 
10184 static devclass_t t4_devclass, t5_devclass, t6_devclass;
10185 static devclass_t cxgbe_devclass, cxl_devclass, cc_devclass;
10186 static devclass_t vcxgbe_devclass, vcxl_devclass, vcc_devclass;
10187 
10188 DRIVER_MODULE(t4nex, pci, t4_driver, t4_devclass, mod_event, 0);
10189 MODULE_VERSION(t4nex, 1);
10190 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
10191 #ifdef DEV_NETMAP
10192 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
10193 #endif /* DEV_NETMAP */
10194 
10195 DRIVER_MODULE(t5nex, pci, t5_driver, t5_devclass, mod_event, 0);
10196 MODULE_VERSION(t5nex, 1);
10197 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
10198 #ifdef DEV_NETMAP
10199 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
10200 #endif /* DEV_NETMAP */
10201 
10202 DRIVER_MODULE(t6nex, pci, t6_driver, t6_devclass, mod_event, 0);
10203 MODULE_VERSION(t6nex, 1);
10204 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
10205 #ifdef DEV_NETMAP
10206 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
10207 #endif /* DEV_NETMAP */
10208 
10209 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, cxgbe_devclass, 0, 0);
10210 MODULE_VERSION(cxgbe, 1);
10211 
10212 DRIVER_MODULE(cxl, t5nex, cxl_driver, cxl_devclass, 0, 0);
10213 MODULE_VERSION(cxl, 1);
10214 
10215 DRIVER_MODULE(cc, t6nex, cc_driver, cc_devclass, 0, 0);
10216 MODULE_VERSION(cc, 1);
10217 
10218 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, vcxgbe_devclass, 0, 0);
10219 MODULE_VERSION(vcxgbe, 1);
10220 
10221 DRIVER_MODULE(vcxl, cxl, vcxl_driver, vcxl_devclass, 0, 0);
10222 MODULE_VERSION(vcxl, 1);
10223 
10224 DRIVER_MODULE(vcc, cc, vcc_driver, vcc_devclass, 0, 0);
10225 MODULE_VERSION(vcc, 1);
10226