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