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