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