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