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