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