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