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