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