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