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