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