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