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