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