xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 315ee00f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
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 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_kern_tls.h"
35 #include "opt_ratelimit.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/eventhandler.h>
44 #include <sys/module.h>
45 #include <sys/malloc.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <sys/pciio.h>
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pci_private.h>
52 #include <sys/firmware.h>
53 #include <sys/sbuf.h>
54 #include <sys/smp.h>
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/sysctl.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_types.h>
61 #include <net/if_dl.h>
62 #include <net/if_vlan_var.h>
63 #ifdef RSS
64 #include <net/rss_config.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #ifdef KERN_TLS
69 #include <netinet/tcp_seq.h>
70 #endif
71 #if defined(__i386__) || defined(__amd64__)
72 #include <machine/md_var.h>
73 #include <machine/cputypes.h>
74 #include <vm/vm.h>
75 #include <vm/pmap.h>
76 #endif
77 #ifdef DDB
78 #include <ddb/ddb.h>
79 #include <ddb/db_lex.h>
80 #endif
81 
82 #include "common/common.h"
83 #include "common/t4_msg.h"
84 #include "common/t4_regs.h"
85 #include "common/t4_regs_values.h"
86 #include "cudbg/cudbg.h"
87 #include "t4_clip.h"
88 #include "t4_ioctl.h"
89 #include "t4_l2t.h"
90 #include "t4_mp_ring.h"
91 #include "t4_if.h"
92 #include "t4_smt.h"
93 
94 /* T4 bus driver interface */
95 static int t4_probe(device_t);
96 static int t4_attach(device_t);
97 static int t4_detach(device_t);
98 static int t4_child_location(device_t, device_t, struct sbuf *);
99 static int t4_ready(device_t);
100 static int t4_read_port_device(device_t, int, device_t *);
101 static int t4_suspend(device_t);
102 static int t4_resume(device_t);
103 static int t4_reset_prepare(device_t, device_t);
104 static int t4_reset_post(device_t, device_t);
105 static device_method_t t4_methods[] = {
106 	DEVMETHOD(device_probe,		t4_probe),
107 	DEVMETHOD(device_attach,	t4_attach),
108 	DEVMETHOD(device_detach,	t4_detach),
109 	DEVMETHOD(device_suspend,	t4_suspend),
110 	DEVMETHOD(device_resume,	t4_resume),
111 
112 	DEVMETHOD(bus_child_location,	t4_child_location),
113 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
114 	DEVMETHOD(bus_reset_post,	t4_reset_post),
115 
116 	DEVMETHOD(t4_is_main_ready,	t4_ready),
117 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
118 
119 	DEVMETHOD_END
120 };
121 static driver_t t4_driver = {
122 	"t4nex",
123 	t4_methods,
124 	sizeof(struct adapter)
125 };
126 
127 
128 /* T4 port (cxgbe) interface */
129 static int cxgbe_probe(device_t);
130 static int cxgbe_attach(device_t);
131 static int cxgbe_detach(device_t);
132 device_method_t cxgbe_methods[] = {
133 	DEVMETHOD(device_probe,		cxgbe_probe),
134 	DEVMETHOD(device_attach,	cxgbe_attach),
135 	DEVMETHOD(device_detach,	cxgbe_detach),
136 	{ 0, 0 }
137 };
138 static driver_t cxgbe_driver = {
139 	"cxgbe",
140 	cxgbe_methods,
141 	sizeof(struct port_info)
142 };
143 
144 /* T4 VI (vcxgbe) interface */
145 static int vcxgbe_probe(device_t);
146 static int vcxgbe_attach(device_t);
147 static int vcxgbe_detach(device_t);
148 static device_method_t vcxgbe_methods[] = {
149 	DEVMETHOD(device_probe,		vcxgbe_probe),
150 	DEVMETHOD(device_attach,	vcxgbe_attach),
151 	DEVMETHOD(device_detach,	vcxgbe_detach),
152 	{ 0, 0 }
153 };
154 static driver_t vcxgbe_driver = {
155 	"vcxgbe",
156 	vcxgbe_methods,
157 	sizeof(struct vi_info)
158 };
159 
160 static d_ioctl_t t4_ioctl;
161 
162 static struct cdevsw t4_cdevsw = {
163        .d_version = D_VERSION,
164        .d_ioctl = t4_ioctl,
165        .d_name = "t4nex",
166 };
167 
168 /* T5 bus driver interface */
169 static int t5_probe(device_t);
170 static device_method_t t5_methods[] = {
171 	DEVMETHOD(device_probe,		t5_probe),
172 	DEVMETHOD(device_attach,	t4_attach),
173 	DEVMETHOD(device_detach,	t4_detach),
174 	DEVMETHOD(device_suspend,	t4_suspend),
175 	DEVMETHOD(device_resume,	t4_resume),
176 
177 	DEVMETHOD(bus_child_location,	t4_child_location),
178 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
179 	DEVMETHOD(bus_reset_post,	t4_reset_post),
180 
181 	DEVMETHOD(t4_is_main_ready,	t4_ready),
182 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
183 
184 	DEVMETHOD_END
185 };
186 static driver_t t5_driver = {
187 	"t5nex",
188 	t5_methods,
189 	sizeof(struct adapter)
190 };
191 
192 
193 /* T5 port (cxl) interface */
194 static driver_t cxl_driver = {
195 	"cxl",
196 	cxgbe_methods,
197 	sizeof(struct port_info)
198 };
199 
200 /* T5 VI (vcxl) interface */
201 static driver_t vcxl_driver = {
202 	"vcxl",
203 	vcxgbe_methods,
204 	sizeof(struct vi_info)
205 };
206 
207 /* T6 bus driver interface */
208 static int t6_probe(device_t);
209 static device_method_t t6_methods[] = {
210 	DEVMETHOD(device_probe,		t6_probe),
211 	DEVMETHOD(device_attach,	t4_attach),
212 	DEVMETHOD(device_detach,	t4_detach),
213 	DEVMETHOD(device_suspend,	t4_suspend),
214 	DEVMETHOD(device_resume,	t4_resume),
215 
216 	DEVMETHOD(bus_child_location,	t4_child_location),
217 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
218 	DEVMETHOD(bus_reset_post,	t4_reset_post),
219 
220 	DEVMETHOD(t4_is_main_ready,	t4_ready),
221 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
222 
223 	DEVMETHOD_END
224 };
225 static driver_t t6_driver = {
226 	"t6nex",
227 	t6_methods,
228 	sizeof(struct adapter)
229 };
230 
231 
232 /* T6 port (cc) interface */
233 static driver_t cc_driver = {
234 	"cc",
235 	cxgbe_methods,
236 	sizeof(struct port_info)
237 };
238 
239 /* T6 VI (vcc) interface */
240 static driver_t vcc_driver = {
241 	"vcc",
242 	vcxgbe_methods,
243 	sizeof(struct vi_info)
244 };
245 
246 /* ifnet interface */
247 static void cxgbe_init(void *);
248 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
249 static int cxgbe_transmit(if_t, struct mbuf *);
250 static void cxgbe_qflush(if_t);
251 #if defined(KERN_TLS) || defined(RATELIMIT)
252 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
253     struct m_snd_tag **);
254 #endif
255 
256 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
257 
258 /*
259  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
260  * then ADAPTER_LOCK, then t4_uld_list_lock.
261  */
262 static struct sx t4_list_lock;
263 SLIST_HEAD(, adapter) t4_list;
264 #ifdef TCP_OFFLOAD
265 static struct sx t4_uld_list_lock;
266 SLIST_HEAD(, uld_info) t4_uld_list;
267 #endif
268 
269 /*
270  * Tunables.  See tweak_tunables() too.
271  *
272  * Each tunable is set to a default value here if it's known at compile-time.
273  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274  * provide a reasonable default (upto n) when the driver is loaded.
275  *
276  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277  * T5 are under hw.cxl.
278  */
279 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280     "cxgbe(4) parameters");
281 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) T5+ parameters");
283 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) TOE parameters");
285 
286 /*
287  * Number of queues for tx and rx, NIC and offload.
288  */
289 #define NTXQ 16
290 int t4_ntxq = -NTXQ;
291 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292     "Number of TX queues per port");
293 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294 
295 #define NRXQ 8
296 int t4_nrxq = -NRXQ;
297 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298     "Number of RX queues per port");
299 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300 
301 #define NTXQ_VI 1
302 static int t4_ntxq_vi = -NTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304     "Number of TX queues per VI");
305 
306 #define NRXQ_VI 1
307 static int t4_nrxq_vi = -NRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309     "Number of RX queues per VI");
310 
311 static int t4_rsrv_noflowq = 0;
312 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313     0, "Reserve TX queue 0 of each VI for non-flowid packets");
314 
315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316 #define NOFLDTXQ 8
317 static int t4_nofldtxq = -NOFLDTXQ;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319     "Number of offload TX queues per port");
320 
321 #define NOFLDRXQ 2
322 static int t4_nofldrxq = -NOFLDRXQ;
323 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324     "Number of offload RX queues per port");
325 
326 #define NOFLDTXQ_VI 1
327 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329     "Number of offload TX queues per VI");
330 
331 #define NOFLDRXQ_VI 1
332 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334     "Number of offload RX queues per VI");
335 
336 #define TMR_IDX_OFLD 1
337 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340 
341 #define PKTC_IDX_OFLD (-1)
342 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345 
346 /* 0 means chip/fw default, non-zero number is value in microseconds */
347 static u_long t4_toe_keepalive_idle = 0;
348 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350 
351 /* 0 means chip/fw default, non-zero number is value in microseconds */
352 static u_long t4_toe_keepalive_interval = 0;
353 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355 
356 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357 static int t4_toe_keepalive_count = 0;
358 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360 
361 /* 0 means chip/fw default, non-zero number is value in microseconds */
362 static u_long t4_toe_rexmt_min = 0;
363 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365 
366 /* 0 means chip/fw default, non-zero number is value in microseconds */
367 static u_long t4_toe_rexmt_max = 0;
368 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370 
371 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372 static int t4_toe_rexmt_count = 0;
373 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375 
376 /* -1 means chip/fw default, other values are raw backoff values to use */
377 static int t4_toe_rexmt_backoff[16] = {
378 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379 };
380 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382     "cxgbe(4) TOE retransmit backoff values");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[0], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[1], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[2], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[3], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[4], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[5], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[6], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[7], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[8], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[9], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[10], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[11], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[12], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[13], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[14], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[15], 0, "");
415 #endif
416 
417 #ifdef DEV_NETMAP
418 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
419 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
420 static int t4_native_netmap = NN_EXTRA_VI;
421 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
422     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
423 
424 #define NNMTXQ 8
425 static int t4_nnmtxq = -NNMTXQ;
426 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
427     "Number of netmap TX queues");
428 
429 #define NNMRXQ 8
430 static int t4_nnmrxq = -NNMRXQ;
431 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
432     "Number of netmap RX queues");
433 
434 #define NNMTXQ_VI 2
435 static int t4_nnmtxq_vi = -NNMTXQ_VI;
436 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
437     "Number of netmap TX queues per VI");
438 
439 #define NNMRXQ_VI 2
440 static int t4_nnmrxq_vi = -NNMRXQ_VI;
441 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
442     "Number of netmap RX queues per VI");
443 #endif
444 
445 /*
446  * Holdoff parameters for ports.
447  */
448 #define TMR_IDX 1
449 int t4_tmr_idx = TMR_IDX;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
451     0, "Holdoff timer index");
452 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
453 
454 #define PKTC_IDX (-1)
455 int t4_pktc_idx = PKTC_IDX;
456 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
457     0, "Holdoff packet counter index");
458 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
459 
460 /*
461  * Size (# of entries) of each tx and rx queue.
462  */
463 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
464 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
465     "Number of descriptors in each TX queue");
466 
467 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
468 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
469     "Number of descriptors in each RX queue");
470 
471 /*
472  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
473  */
474 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
475 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
476     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
477 
478 /*
479  * Configuration file.  All the _CF names here are special.
480  */
481 #define DEFAULT_CF	"default"
482 #define BUILTIN_CF	"built-in"
483 #define FLASH_CF	"flash"
484 #define UWIRE_CF	"uwire"
485 #define FPGA_CF		"fpga"
486 static char t4_cfg_file[32] = DEFAULT_CF;
487 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
488     sizeof(t4_cfg_file), "Firmware configuration file");
489 
490 /*
491  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
492  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
493  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
494  *            mark or when signalled to do so, 0 to never emit PAUSE.
495  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
496  *                 negotiated settings will override rx_pause/tx_pause.
497  *                 Otherwise rx_pause/tx_pause are applied forcibly.
498  */
499 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
500 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
501     &t4_pause_settings, 0,
502     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
503 
504 /*
505  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
506  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
507  *  0 to disable FEC.
508  */
509 static int t4_fec = -1;
510 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
511     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
512 
513 /*
514  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
515  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
516  * driver runs as if this is set to 0.
517  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
518  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
519  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
520  *    the firmware anyway (may result in l1cfg errors with old firmwares).
521  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
522  *    means set all FEC bits that are valid for the speed.
523  */
524 static int t4_force_fec = -1;
525 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
526     "Controls the use of FORCE_FEC bit in L1 configuration.");
527 
528 /*
529  * Link autonegotiation.
530  * -1 to run with the firmware default.
531  *  0 to disable.
532  *  1 to enable.
533  */
534 static int t4_autoneg = -1;
535 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
536     "Link autonegotiation");
537 
538 /*
539  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
540  * encouraged respectively).  '-n' is the same as 'n' except the firmware
541  * version used in the checks is read from the firmware bundled with the driver.
542  */
543 static int t4_fw_install = 1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
545     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
546 
547 /*
548  * ASIC features that will be used.  Disable the ones you don't want so that the
549  * chip resources aren't wasted on features that will not be used.
550  */
551 static int t4_nbmcaps_allowed = 0;
552 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
553     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
554 
555 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
556 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
557     &t4_linkcaps_allowed, 0, "Default link capabilities");
558 
559 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
560     FW_CAPS_CONFIG_SWITCH_EGRESS;
561 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
562     &t4_switchcaps_allowed, 0, "Default switch capabilities");
563 
564 #ifdef RATELIMIT
565 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
566 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
567 #else
568 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
569 	FW_CAPS_CONFIG_NIC_HASHFILTER;
570 #endif
571 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
572     &t4_niccaps_allowed, 0, "Default NIC capabilities");
573 
574 static int t4_toecaps_allowed = -1;
575 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
576     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
577 
578 static int t4_rdmacaps_allowed = -1;
579 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
580     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
581 
582 static int t4_cryptocaps_allowed = -1;
583 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
584     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
585 
586 static int t4_iscsicaps_allowed = -1;
587 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
588     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
589 
590 static int t4_fcoecaps_allowed = 0;
591 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
592     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
593 
594 static int t5_write_combine = 0;
595 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
596     0, "Use WC instead of UC for BAR2");
597 
598 static int t4_num_vis = 1;
599 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
600     "Number of VIs per port");
601 
602 /*
603  * PCIe Relaxed Ordering.
604  * -1: driver should figure out a good value.
605  * 0: disable RO.
606  * 1: enable RO.
607  * 2: leave RO alone.
608  */
609 static int pcie_relaxed_ordering = -1;
610 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
611     &pcie_relaxed_ordering, 0,
612     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
613 
614 static int t4_panic_on_fatal_err = 0;
615 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
616     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
617 
618 static int t4_reset_on_fatal_err = 0;
619 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
620     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
621 
622 static int t4_clock_gate_on_suspend = 0;
623 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
624     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
625 
626 static int t4_tx_vm_wr = 0;
627 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
628     "Use VM work requests to transmit packets.");
629 
630 /*
631  * Set to non-zero to enable the attack filter.  A packet that matches any of
632  * these conditions will get dropped on ingress:
633  * 1) IP && source address == destination address.
634  * 2) TCP/IP && source address is not a unicast address.
635  * 3) TCP/IP && destination address is not a unicast address.
636  * 4) IP && source address is loopback (127.x.y.z).
637  * 5) IP && destination address is loopback (127.x.y.z).
638  * 6) IPv6 && source address == destination address.
639  * 7) IPv6 && source address is not a unicast address.
640  * 8) IPv6 && source address is loopback (::1/128).
641  * 9) IPv6 && destination address is loopback (::1/128).
642  * 10) IPv6 && source address is unspecified (::/128).
643  * 11) IPv6 && destination address is unspecified (::/128).
644  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
645  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
646  */
647 static int t4_attack_filter = 0;
648 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
649     &t4_attack_filter, 0, "Drop suspicious traffic");
650 
651 static int t4_drop_ip_fragments = 0;
652 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
653     &t4_drop_ip_fragments, 0, "Drop IP fragments");
654 
655 static int t4_drop_pkts_with_l2_errors = 1;
656 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
657     &t4_drop_pkts_with_l2_errors, 0,
658     "Drop all frames with Layer 2 length or checksum errors");
659 
660 static int t4_drop_pkts_with_l3_errors = 0;
661 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
662     &t4_drop_pkts_with_l3_errors, 0,
663     "Drop all frames with IP version, length, or checksum errors");
664 
665 static int t4_drop_pkts_with_l4_errors = 0;
666 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
667     &t4_drop_pkts_with_l4_errors, 0,
668     "Drop all frames with Layer 4 length, checksum, or other errors");
669 
670 #ifdef TCP_OFFLOAD
671 /*
672  * TOE tunables.
673  */
674 static int t4_cop_managed_offloading = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
676     &t4_cop_managed_offloading, 0,
677     "COP (Connection Offload Policy) controls all TOE offload");
678 #endif
679 
680 #ifdef KERN_TLS
681 /*
682  * This enables KERN_TLS for all adapters if set.
683  */
684 static int t4_kern_tls = 0;
685 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
686     "Enable KERN_TLS mode for T6 adapters");
687 
688 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
689     "cxgbe(4) KERN_TLS parameters");
690 
691 static int t4_tls_inline_keys = 0;
692 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
693     &t4_tls_inline_keys, 0,
694     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
695     "in card memory.");
696 
697 static int t4_tls_combo_wrs = 0;
698 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
699     0, "Attempt to combine TCB field updates with TLS record work requests.");
700 #endif
701 
702 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
703 static int vi_mac_funcs[] = {
704 	FW_VI_FUNC_ETH,
705 	FW_VI_FUNC_OFLD,
706 	FW_VI_FUNC_IWARP,
707 	FW_VI_FUNC_OPENISCSI,
708 	FW_VI_FUNC_OPENFCOE,
709 	FW_VI_FUNC_FOISCSI,
710 	FW_VI_FUNC_FOFCOE,
711 };
712 
713 struct intrs_and_queues {
714 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
715 	uint16_t num_vis;	/* number of VIs for each port */
716 	uint16_t nirq;		/* Total # of vectors */
717 	uint16_t ntxq;		/* # of NIC txq's for each port */
718 	uint16_t nrxq;		/* # of NIC rxq's for each port */
719 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
720 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
721 	uint16_t nnmtxq;	/* # of netmap txq's */
722 	uint16_t nnmrxq;	/* # of netmap rxq's */
723 
724 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
725 	uint16_t ntxq_vi;	/* # of NIC txq's */
726 	uint16_t nrxq_vi;	/* # of NIC rxq's */
727 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
728 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
729 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
730 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
731 };
732 
733 static void setup_memwin(struct adapter *);
734 static void position_memwin(struct adapter *, int, uint32_t);
735 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
736 static int fwmtype_to_hwmtype(int);
737 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
738     uint32_t *);
739 static int fixup_devlog_params(struct adapter *);
740 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
741 static int contact_firmware(struct adapter *);
742 static int partition_resources(struct adapter *);
743 static int get_params__pre_init(struct adapter *);
744 static int set_params__pre_init(struct adapter *);
745 static int get_params__post_init(struct adapter *);
746 static int set_params__post_init(struct adapter *);
747 static void t4_set_desc(struct adapter *);
748 static bool fixed_ifmedia(struct port_info *);
749 static void build_medialist(struct port_info *);
750 static void init_link_config(struct port_info *);
751 static int fixup_link_config(struct port_info *);
752 static int apply_link_config(struct port_info *);
753 static int cxgbe_init_synchronized(struct vi_info *);
754 static int cxgbe_uninit_synchronized(struct vi_info *);
755 static int adapter_full_init(struct adapter *);
756 static void adapter_full_uninit(struct adapter *);
757 static int vi_full_init(struct vi_info *);
758 static void vi_full_uninit(struct vi_info *);
759 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
760 static void quiesce_txq(struct sge_txq *);
761 static void quiesce_wrq(struct sge_wrq *);
762 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
763 static void quiesce_vi(struct vi_info *);
764 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
765     driver_intr_t *, void *, char *);
766 static int t4_free_irq(struct adapter *, struct irq *);
767 static void t4_init_atid_table(struct adapter *);
768 static void t4_free_atid_table(struct adapter *);
769 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
770 static void vi_refresh_stats(struct vi_info *);
771 static void cxgbe_refresh_stats(struct vi_info *);
772 static void cxgbe_tick(void *);
773 static void vi_tick(void *);
774 static void cxgbe_sysctls(struct port_info *);
775 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
776 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
777 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
778 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
779 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
780 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
781 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
782 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
783 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
784 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
785 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
786 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
787 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
788 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
789 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
790 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
791 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
792 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
793 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
794 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
795 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
796 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
797 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
798 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
799 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
800 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
801 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
802 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
803 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
804 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
805 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
806 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
807 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
808 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
809 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
810 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
811 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
812 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
813 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
814 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
815 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
817 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
818 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
821 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
822 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
823 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
824 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
825 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
826 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
827 #ifdef TCP_OFFLOAD
828 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
829 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
830 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
831 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
834 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
835 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
836 #endif
837 static int get_sge_context(struct adapter *, struct t4_sge_context *);
838 static int load_fw(struct adapter *, struct t4_data *);
839 static int load_cfg(struct adapter *, struct t4_data *);
840 static int load_boot(struct adapter *, struct t4_bootrom *);
841 static int load_bootcfg(struct adapter *, struct t4_data *);
842 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
843 static void free_offload_policy(struct t4_offload_policy *);
844 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
845 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
846 static int read_i2c(struct adapter *, struct t4_i2c_data *);
847 static int clear_stats(struct adapter *, u_int);
848 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
849 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
850 #ifdef TCP_OFFLOAD
851 static int toe_capability(struct vi_info *, bool);
852 static int t4_deactivate_all_uld(struct adapter *);
853 static void t4_async_event(struct adapter *);
854 #endif
855 #ifdef KERN_TLS
856 static int ktls_capability(struct adapter *, bool);
857 #endif
858 static int mod_event(module_t, int, void *);
859 static int notify_siblings(device_t, int);
860 static uint64_t vi_get_counter(if_t, ift_counter);
861 static uint64_t cxgbe_get_counter(if_t, ift_counter);
862 static void enable_vxlan_rx(struct adapter *);
863 static void reset_adapter_task(void *, int);
864 static void fatal_error_task(void *, int);
865 static void dump_devlog(struct adapter *);
866 static void dump_cim_regs(struct adapter *);
867 static void dump_cimla(struct adapter *);
868 
869 struct {
870 	uint16_t device;
871 	char *desc;
872 } t4_pciids[] = {
873 	{0xa000, "Chelsio Terminator 4 FPGA"},
874 	{0x4400, "Chelsio T440-dbg"},
875 	{0x4401, "Chelsio T420-CR"},
876 	{0x4402, "Chelsio T422-CR"},
877 	{0x4403, "Chelsio T440-CR"},
878 	{0x4404, "Chelsio T420-BCH"},
879 	{0x4405, "Chelsio T440-BCH"},
880 	{0x4406, "Chelsio T440-CH"},
881 	{0x4407, "Chelsio T420-SO"},
882 	{0x4408, "Chelsio T420-CX"},
883 	{0x4409, "Chelsio T420-BT"},
884 	{0x440a, "Chelsio T404-BT"},
885 	{0x440e, "Chelsio T440-LP-CR"},
886 }, t5_pciids[] = {
887 	{0xb000, "Chelsio Terminator 5 FPGA"},
888 	{0x5400, "Chelsio T580-dbg"},
889 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
890 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
891 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
892 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
893 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
894 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
895 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
896 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
897 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
898 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
899 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
900 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
901 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
902 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
903 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
904 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
905 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
906 
907 	/* Custom */
908 	{0x5483, "Custom T540-CR"},
909 	{0x5484, "Custom T540-BT"},
910 }, t6_pciids[] = {
911 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
912 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
913 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
914 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
915 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
916 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
917 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
918 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
919 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
920 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
921 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
922 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
923 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
924 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
925 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
926 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
927 
928 	/* Custom */
929 	{0x6480, "Custom T6225-CR"},
930 	{0x6481, "Custom T62100-CR"},
931 	{0x6482, "Custom T6225-CR"},
932 	{0x6483, "Custom T62100-CR"},
933 	{0x6484, "Custom T64100-CR"},
934 	{0x6485, "Custom T6240-SO"},
935 	{0x6486, "Custom T6225-SO-CR"},
936 	{0x6487, "Custom T6225-CR"},
937 };
938 
939 #ifdef TCP_OFFLOAD
940 /*
941  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
942  * be exactly the same for both rxq and ofld_rxq.
943  */
944 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
945 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
946 #endif
947 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
948 
949 static int
950 t4_probe(device_t dev)
951 {
952 	int i;
953 	uint16_t v = pci_get_vendor(dev);
954 	uint16_t d = pci_get_device(dev);
955 	uint8_t f = pci_get_function(dev);
956 
957 	if (v != PCI_VENDOR_ID_CHELSIO)
958 		return (ENXIO);
959 
960 	/* Attach only to PF0 of the FPGA */
961 	if (d == 0xa000 && f != 0)
962 		return (ENXIO);
963 
964 	for (i = 0; i < nitems(t4_pciids); i++) {
965 		if (d == t4_pciids[i].device) {
966 			device_set_desc(dev, t4_pciids[i].desc);
967 			return (BUS_PROBE_DEFAULT);
968 		}
969 	}
970 
971 	return (ENXIO);
972 }
973 
974 static int
975 t5_probe(device_t dev)
976 {
977 	int i;
978 	uint16_t v = pci_get_vendor(dev);
979 	uint16_t d = pci_get_device(dev);
980 	uint8_t f = pci_get_function(dev);
981 
982 	if (v != PCI_VENDOR_ID_CHELSIO)
983 		return (ENXIO);
984 
985 	/* Attach only to PF0 of the FPGA */
986 	if (d == 0xb000 && f != 0)
987 		return (ENXIO);
988 
989 	for (i = 0; i < nitems(t5_pciids); i++) {
990 		if (d == t5_pciids[i].device) {
991 			device_set_desc(dev, t5_pciids[i].desc);
992 			return (BUS_PROBE_DEFAULT);
993 		}
994 	}
995 
996 	return (ENXIO);
997 }
998 
999 static int
1000 t6_probe(device_t dev)
1001 {
1002 	int i;
1003 	uint16_t v = pci_get_vendor(dev);
1004 	uint16_t d = pci_get_device(dev);
1005 
1006 	if (v != PCI_VENDOR_ID_CHELSIO)
1007 		return (ENXIO);
1008 
1009 	for (i = 0; i < nitems(t6_pciids); i++) {
1010 		if (d == t6_pciids[i].device) {
1011 			device_set_desc(dev, t6_pciids[i].desc);
1012 			return (BUS_PROBE_DEFAULT);
1013 		}
1014 	}
1015 
1016 	return (ENXIO);
1017 }
1018 
1019 static void
1020 t5_attribute_workaround(device_t dev)
1021 {
1022 	device_t root_port;
1023 	uint32_t v;
1024 
1025 	/*
1026 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1027 	 * Ordering attributes when replying to a TLP from a Root
1028 	 * Port.  As a workaround, find the parent Root Port and
1029 	 * disable No Snoop and Relaxed Ordering.  Note that this
1030 	 * affects all devices under this root port.
1031 	 */
1032 	root_port = pci_find_pcie_root_port(dev);
1033 	if (root_port == NULL) {
1034 		device_printf(dev, "Unable to find parent root port\n");
1035 		return;
1036 	}
1037 
1038 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1039 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1040 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1041 	    0)
1042 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1043 		    device_get_nameunit(root_port));
1044 }
1045 
1046 static const struct devnames devnames[] = {
1047 	{
1048 		.nexus_name = "t4nex",
1049 		.ifnet_name = "cxgbe",
1050 		.vi_ifnet_name = "vcxgbe",
1051 		.pf03_drv_name = "t4iov",
1052 		.vf_nexus_name = "t4vf",
1053 		.vf_ifnet_name = "cxgbev"
1054 	}, {
1055 		.nexus_name = "t5nex",
1056 		.ifnet_name = "cxl",
1057 		.vi_ifnet_name = "vcxl",
1058 		.pf03_drv_name = "t5iov",
1059 		.vf_nexus_name = "t5vf",
1060 		.vf_ifnet_name = "cxlv"
1061 	}, {
1062 		.nexus_name = "t6nex",
1063 		.ifnet_name = "cc",
1064 		.vi_ifnet_name = "vcc",
1065 		.pf03_drv_name = "t6iov",
1066 		.vf_nexus_name = "t6vf",
1067 		.vf_ifnet_name = "ccv"
1068 	}
1069 };
1070 
1071 void
1072 t4_init_devnames(struct adapter *sc)
1073 {
1074 	int id;
1075 
1076 	id = chip_id(sc);
1077 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1078 		sc->names = &devnames[id - CHELSIO_T4];
1079 	else {
1080 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1081 		sc->names = NULL;
1082 	}
1083 }
1084 
1085 static int
1086 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1087 {
1088 	const char *parent, *name;
1089 	long value;
1090 	int line, unit;
1091 
1092 	line = 0;
1093 	parent = device_get_nameunit(sc->dev);
1094 	name = sc->names->ifnet_name;
1095 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1096 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1097 		    value == pi->port_id)
1098 			return (unit);
1099 	}
1100 	return (-1);
1101 }
1102 
1103 static void
1104 t4_calibration(void *arg)
1105 {
1106 	struct adapter *sc;
1107 	struct clock_sync *cur, *nex;
1108 	uint64_t hw;
1109 	sbintime_t sbt;
1110 	int next_up;
1111 
1112 	sc = (struct adapter *)arg;
1113 
1114 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1115 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1116 	sbt = sbinuptime();
1117 
1118 	cur = &sc->cal_info[sc->cal_current];
1119 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1120 	nex = &sc->cal_info[next_up];
1121 	if (__predict_false(sc->cal_count == 0)) {
1122 		/* First time in, just get the values in */
1123 		cur->hw_cur = hw;
1124 		cur->sbt_cur = sbt;
1125 		sc->cal_count++;
1126 		goto done;
1127 	}
1128 
1129 	if (cur->hw_cur == hw) {
1130 		/* The clock is not advancing? */
1131 		sc->cal_count = 0;
1132 		atomic_store_rel_int(&cur->gen, 0);
1133 		goto done;
1134 	}
1135 
1136 	seqc_write_begin(&nex->gen);
1137 	nex->hw_prev = cur->hw_cur;
1138 	nex->sbt_prev = cur->sbt_cur;
1139 	nex->hw_cur = hw;
1140 	nex->sbt_cur = sbt;
1141 	seqc_write_end(&nex->gen);
1142 	sc->cal_current = next_up;
1143 done:
1144 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1145 	    sc, C_DIRECT_EXEC);
1146 }
1147 
1148 static void
1149 t4_calibration_start(struct adapter *sc)
1150 {
1151 	/*
1152 	 * Here if we have not done a calibration
1153 	 * then do so otherwise start the appropriate
1154 	 * timer.
1155 	 */
1156 	int i;
1157 
1158 	for (i = 0; i < CNT_CAL_INFO; i++) {
1159 		sc->cal_info[i].gen = 0;
1160 	}
1161 	sc->cal_current = 0;
1162 	sc->cal_count = 0;
1163 	sc->cal_gen = 0;
1164 	t4_calibration(sc);
1165 }
1166 
1167 static int
1168 t4_attach(device_t dev)
1169 {
1170 	struct adapter *sc;
1171 	int rc = 0, i, j, rqidx, tqidx, nports;
1172 	struct make_dev_args mda;
1173 	struct intrs_and_queues iaq;
1174 	struct sge *s;
1175 	uint32_t *buf;
1176 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1177 	int ofld_tqidx;
1178 #endif
1179 #ifdef TCP_OFFLOAD
1180 	int ofld_rqidx;
1181 #endif
1182 #ifdef DEV_NETMAP
1183 	int nm_rqidx, nm_tqidx;
1184 #endif
1185 	int num_vis;
1186 
1187 	sc = device_get_softc(dev);
1188 	sc->dev = dev;
1189 	sysctl_ctx_init(&sc->ctx);
1190 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1191 
1192 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1193 		t5_attribute_workaround(dev);
1194 	pci_enable_busmaster(dev);
1195 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1196 		uint32_t v;
1197 
1198 		pci_set_max_read_req(dev, 4096);
1199 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1200 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1201 		if (pcie_relaxed_ordering == 0 &&
1202 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1203 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1204 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1205 		} else if (pcie_relaxed_ordering == 1 &&
1206 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1207 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1208 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1209 		}
1210 	}
1211 
1212 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1213 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1214 	sc->traceq = -1;
1215 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1216 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1217 	    device_get_nameunit(dev));
1218 
1219 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1220 	    device_get_nameunit(dev));
1221 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1222 	t4_add_adapter(sc);
1223 
1224 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1225 	TAILQ_INIT(&sc->sfl);
1226 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1227 
1228 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1229 
1230 	sc->policy = NULL;
1231 	rw_init(&sc->policy_lock, "connection offload policy");
1232 
1233 	callout_init(&sc->ktls_tick, 1);
1234 
1235 	callout_init(&sc->cal_callout, 1);
1236 
1237 	refcount_init(&sc->vxlan_refcount, 0);
1238 
1239 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1240 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1241 
1242 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1243 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1244 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1245 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1246 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1247 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1248 
1249 	rc = t4_map_bars_0_and_4(sc);
1250 	if (rc != 0)
1251 		goto done; /* error message displayed already */
1252 
1253 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1254 
1255 	/* Prepare the adapter for operation. */
1256 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1257 	rc = -t4_prep_adapter(sc, buf);
1258 	free(buf, M_CXGBE);
1259 	if (rc != 0) {
1260 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1261 		goto done;
1262 	}
1263 
1264 	/*
1265 	 * This is the real PF# to which we're attaching.  Works from within PCI
1266 	 * passthrough environments too, where pci_get_function() could return a
1267 	 * different PF# depending on the passthrough configuration.  We need to
1268 	 * use the real PF# in all our communication with the firmware.
1269 	 */
1270 	j = t4_read_reg(sc, A_PL_WHOAMI);
1271 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1272 	sc->mbox = sc->pf;
1273 
1274 	t4_init_devnames(sc);
1275 	if (sc->names == NULL) {
1276 		rc = ENOTSUP;
1277 		goto done; /* error message displayed already */
1278 	}
1279 
1280 	/*
1281 	 * Do this really early, with the memory windows set up even before the
1282 	 * character device.  The userland tool's register i/o and mem read
1283 	 * will work even in "recovery mode".
1284 	 */
1285 	setup_memwin(sc);
1286 	if (t4_init_devlog_params(sc, 0) == 0)
1287 		fixup_devlog_params(sc);
1288 	make_dev_args_init(&mda);
1289 	mda.mda_devsw = &t4_cdevsw;
1290 	mda.mda_uid = UID_ROOT;
1291 	mda.mda_gid = GID_WHEEL;
1292 	mda.mda_mode = 0600;
1293 	mda.mda_si_drv1 = sc;
1294 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1295 	if (rc != 0)
1296 		device_printf(dev, "failed to create nexus char device: %d.\n",
1297 		    rc);
1298 
1299 	/* Go no further if recovery mode has been requested. */
1300 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1301 		device_printf(dev, "recovery mode.\n");
1302 		goto done;
1303 	}
1304 
1305 #if defined(__i386__)
1306 	if ((cpu_feature & CPUID_CX8) == 0) {
1307 		device_printf(dev, "64 bit atomics not available.\n");
1308 		rc = ENOTSUP;
1309 		goto done;
1310 	}
1311 #endif
1312 
1313 	/* Contact the firmware and try to become the master driver. */
1314 	rc = contact_firmware(sc);
1315 	if (rc != 0)
1316 		goto done; /* error message displayed already */
1317 	MPASS(sc->flags & FW_OK);
1318 
1319 	rc = get_params__pre_init(sc);
1320 	if (rc != 0)
1321 		goto done; /* error message displayed already */
1322 
1323 	if (sc->flags & MASTER_PF) {
1324 		rc = partition_resources(sc);
1325 		if (rc != 0)
1326 			goto done; /* error message displayed already */
1327 		t4_intr_clear(sc);
1328 	}
1329 
1330 	rc = get_params__post_init(sc);
1331 	if (rc != 0)
1332 		goto done; /* error message displayed already */
1333 
1334 	rc = set_params__post_init(sc);
1335 	if (rc != 0)
1336 		goto done; /* error message displayed already */
1337 
1338 	rc = t4_map_bar_2(sc);
1339 	if (rc != 0)
1340 		goto done; /* error message displayed already */
1341 
1342 	rc = t4_create_dma_tag(sc);
1343 	if (rc != 0)
1344 		goto done; /* error message displayed already */
1345 
1346 	/*
1347 	 * First pass over all the ports - allocate VIs and initialize some
1348 	 * basic parameters like mac address, port type, etc.
1349 	 */
1350 	for_each_port(sc, i) {
1351 		struct port_info *pi;
1352 
1353 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1354 		sc->port[i] = pi;
1355 
1356 		/* These must be set before t4_port_init */
1357 		pi->adapter = sc;
1358 		pi->port_id = i;
1359 		/*
1360 		 * XXX: vi[0] is special so we can't delay this allocation until
1361 		 * pi->nvi's final value is known.
1362 		 */
1363 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1364 		    M_ZERO | M_WAITOK);
1365 
1366 		/*
1367 		 * Allocate the "main" VI and initialize parameters
1368 		 * like mac addr.
1369 		 */
1370 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1371 		if (rc != 0) {
1372 			device_printf(dev, "unable to initialize port %d: %d\n",
1373 			    i, rc);
1374 			free(pi->vi, M_CXGBE);
1375 			free(pi, M_CXGBE);
1376 			sc->port[i] = NULL;
1377 			goto done;
1378 		}
1379 
1380 		if (is_bt(pi->port_type))
1381 			setbit(&sc->bt_map, pi->tx_chan);
1382 		else
1383 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1384 
1385 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1386 		    device_get_nameunit(dev), i);
1387 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1388 		sc->chan_map[pi->tx_chan] = i;
1389 
1390 		/*
1391 		 * The MPS counter for FCS errors doesn't work correctly on the
1392 		 * T6 so we use the MAC counter here.  Which MAC is in use
1393 		 * depends on the link settings which will be known when the
1394 		 * link comes up.
1395 		 */
1396 		if (is_t6(sc)) {
1397 			pi->fcs_reg = -1;
1398 		} else if (is_t4(sc)) {
1399 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1400 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1401 		} else {
1402 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1403 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1404 		}
1405 		pi->fcs_base = 0;
1406 
1407 		/* All VIs on this port share this media. */
1408 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1409 		    cxgbe_media_status);
1410 
1411 		PORT_LOCK(pi);
1412 		init_link_config(pi);
1413 		fixup_link_config(pi);
1414 		build_medialist(pi);
1415 		if (fixed_ifmedia(pi))
1416 			pi->flags |= FIXED_IFMEDIA;
1417 		PORT_UNLOCK(pi);
1418 
1419 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1420 		    t4_ifnet_unit(sc, pi));
1421 		if (pi->dev == NULL) {
1422 			device_printf(dev,
1423 			    "failed to add device for port %d.\n", i);
1424 			rc = ENXIO;
1425 			goto done;
1426 		}
1427 		pi->vi[0].dev = pi->dev;
1428 		device_set_softc(pi->dev, pi);
1429 	}
1430 
1431 	/*
1432 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1433 	 */
1434 	nports = sc->params.nports;
1435 	rc = cfg_itype_and_nqueues(sc, &iaq);
1436 	if (rc != 0)
1437 		goto done; /* error message displayed already */
1438 
1439 	num_vis = iaq.num_vis;
1440 	sc->intr_type = iaq.intr_type;
1441 	sc->intr_count = iaq.nirq;
1442 
1443 	s = &sc->sge;
1444 	s->nrxq = nports * iaq.nrxq;
1445 	s->ntxq = nports * iaq.ntxq;
1446 	if (num_vis > 1) {
1447 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1448 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1449 	}
1450 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1451 	s->neq += nports;		/* ctrl queues: 1 per port */
1452 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1453 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1454 	if (is_offload(sc) || is_ethoffload(sc)) {
1455 		s->nofldtxq = nports * iaq.nofldtxq;
1456 		if (num_vis > 1)
1457 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1458 		s->neq += s->nofldtxq;
1459 
1460 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1461 		    M_CXGBE, M_ZERO | M_WAITOK);
1462 	}
1463 #endif
1464 #ifdef TCP_OFFLOAD
1465 	if (is_offload(sc)) {
1466 		s->nofldrxq = nports * iaq.nofldrxq;
1467 		if (num_vis > 1)
1468 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1469 		s->neq += s->nofldrxq;	/* free list */
1470 		s->niq += s->nofldrxq;
1471 
1472 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1473 		    M_CXGBE, M_ZERO | M_WAITOK);
1474 	}
1475 #endif
1476 #ifdef DEV_NETMAP
1477 	s->nnmrxq = 0;
1478 	s->nnmtxq = 0;
1479 	if (t4_native_netmap & NN_MAIN_VI) {
1480 		s->nnmrxq += nports * iaq.nnmrxq;
1481 		s->nnmtxq += nports * iaq.nnmtxq;
1482 	}
1483 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1484 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1485 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1486 	}
1487 	s->neq += s->nnmtxq + s->nnmrxq;
1488 	s->niq += s->nnmrxq;
1489 
1490 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1491 	    M_CXGBE, M_ZERO | M_WAITOK);
1492 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1493 	    M_CXGBE, M_ZERO | M_WAITOK);
1494 #endif
1495 	MPASS(s->niq <= s->iqmap_sz);
1496 	MPASS(s->neq <= s->eqmap_sz);
1497 
1498 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1499 	    M_ZERO | M_WAITOK);
1500 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1501 	    M_ZERO | M_WAITOK);
1502 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1503 	    M_ZERO | M_WAITOK);
1504 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1505 	    M_ZERO | M_WAITOK);
1506 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1507 	    M_ZERO | M_WAITOK);
1508 
1509 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1510 	    M_ZERO | M_WAITOK);
1511 
1512 	t4_init_l2t(sc, M_WAITOK);
1513 	t4_init_smt(sc, M_WAITOK);
1514 	t4_init_tx_sched(sc);
1515 	t4_init_atid_table(sc);
1516 #ifdef RATELIMIT
1517 	t4_init_etid_table(sc);
1518 #endif
1519 #ifdef INET6
1520 	t4_init_clip_table(sc);
1521 #endif
1522 	if (sc->vres.key.size != 0)
1523 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1524 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1525 
1526 	/*
1527 	 * Second pass over the ports.  This time we know the number of rx and
1528 	 * tx queues that each port should get.
1529 	 */
1530 	rqidx = tqidx = 0;
1531 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1532 	ofld_tqidx = 0;
1533 #endif
1534 #ifdef TCP_OFFLOAD
1535 	ofld_rqidx = 0;
1536 #endif
1537 #ifdef DEV_NETMAP
1538 	nm_rqidx = nm_tqidx = 0;
1539 #endif
1540 	for_each_port(sc, i) {
1541 		struct port_info *pi = sc->port[i];
1542 		struct vi_info *vi;
1543 
1544 		if (pi == NULL)
1545 			continue;
1546 
1547 		pi->nvi = num_vis;
1548 		for_each_vi(pi, j, vi) {
1549 			vi->pi = pi;
1550 			vi->adapter = sc;
1551 			vi->first_intr = -1;
1552 			vi->qsize_rxq = t4_qsize_rxq;
1553 			vi->qsize_txq = t4_qsize_txq;
1554 
1555 			vi->first_rxq = rqidx;
1556 			vi->first_txq = tqidx;
1557 			vi->tmr_idx = t4_tmr_idx;
1558 			vi->pktc_idx = t4_pktc_idx;
1559 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1560 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1561 
1562 			rqidx += vi->nrxq;
1563 			tqidx += vi->ntxq;
1564 
1565 			if (j == 0 && vi->ntxq > 1)
1566 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1567 			else
1568 				vi->rsrv_noflowq = 0;
1569 
1570 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1571 			vi->first_ofld_txq = ofld_tqidx;
1572 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1573 			ofld_tqidx += vi->nofldtxq;
1574 #endif
1575 #ifdef TCP_OFFLOAD
1576 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1577 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1578 			vi->first_ofld_rxq = ofld_rqidx;
1579 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1580 
1581 			ofld_rqidx += vi->nofldrxq;
1582 #endif
1583 #ifdef DEV_NETMAP
1584 			vi->first_nm_rxq = nm_rqidx;
1585 			vi->first_nm_txq = nm_tqidx;
1586 			if (j == 0) {
1587 				vi->nnmrxq = iaq.nnmrxq;
1588 				vi->nnmtxq = iaq.nnmtxq;
1589 			} else {
1590 				vi->nnmrxq = iaq.nnmrxq_vi;
1591 				vi->nnmtxq = iaq.nnmtxq_vi;
1592 			}
1593 			nm_rqidx += vi->nnmrxq;
1594 			nm_tqidx += vi->nnmtxq;
1595 #endif
1596 		}
1597 	}
1598 
1599 	rc = t4_setup_intr_handlers(sc);
1600 	if (rc != 0) {
1601 		device_printf(dev,
1602 		    "failed to setup interrupt handlers: %d\n", rc);
1603 		goto done;
1604 	}
1605 
1606 	rc = bus_generic_probe(dev);
1607 	if (rc != 0) {
1608 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1609 		goto done;
1610 	}
1611 
1612 	/*
1613 	 * Ensure thread-safe mailbox access (in debug builds).
1614 	 *
1615 	 * So far this was the only thread accessing the mailbox but various
1616 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1617 	 * will access the mailbox from different threads.
1618 	 */
1619 	sc->flags |= CHK_MBOX_ACCESS;
1620 
1621 	rc = bus_generic_attach(dev);
1622 	if (rc != 0) {
1623 		device_printf(dev,
1624 		    "failed to attach all child ports: %d\n", rc);
1625 		goto done;
1626 	}
1627 	t4_calibration_start(sc);
1628 
1629 	device_printf(dev,
1630 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1631 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1632 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1633 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1634 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1635 
1636 	t4_set_desc(sc);
1637 
1638 	notify_siblings(dev, 0);
1639 
1640 done:
1641 	if (rc != 0 && sc->cdev) {
1642 		/* cdev was created and so cxgbetool works; recover that way. */
1643 		device_printf(dev,
1644 		    "error during attach, adapter is now in recovery mode.\n");
1645 		rc = 0;
1646 	}
1647 
1648 	if (rc != 0)
1649 		t4_detach_common(dev);
1650 	else
1651 		t4_sysctls(sc);
1652 
1653 	return (rc);
1654 }
1655 
1656 static int
1657 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1658 {
1659 	struct adapter *sc;
1660 	struct port_info *pi;
1661 	int i;
1662 
1663 	sc = device_get_softc(bus);
1664 	for_each_port(sc, i) {
1665 		pi = sc->port[i];
1666 		if (pi != NULL && pi->dev == dev) {
1667 			sbuf_printf(sb, "port=%d", pi->port_id);
1668 			break;
1669 		}
1670 	}
1671 	return (0);
1672 }
1673 
1674 static int
1675 t4_ready(device_t dev)
1676 {
1677 	struct adapter *sc;
1678 
1679 	sc = device_get_softc(dev);
1680 	if (sc->flags & FW_OK)
1681 		return (0);
1682 	return (ENXIO);
1683 }
1684 
1685 static int
1686 t4_read_port_device(device_t dev, int port, device_t *child)
1687 {
1688 	struct adapter *sc;
1689 	struct port_info *pi;
1690 
1691 	sc = device_get_softc(dev);
1692 	if (port < 0 || port >= MAX_NPORTS)
1693 		return (EINVAL);
1694 	pi = sc->port[port];
1695 	if (pi == NULL || pi->dev == NULL)
1696 		return (ENXIO);
1697 	*child = pi->dev;
1698 	return (0);
1699 }
1700 
1701 static int
1702 notify_siblings(device_t dev, int detaching)
1703 {
1704 	device_t sibling;
1705 	int error, i;
1706 
1707 	error = 0;
1708 	for (i = 0; i < PCI_FUNCMAX; i++) {
1709 		if (i == pci_get_function(dev))
1710 			continue;
1711 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1712 		    pci_get_slot(dev), i);
1713 		if (sibling == NULL || !device_is_attached(sibling))
1714 			continue;
1715 		if (detaching)
1716 			error = T4_DETACH_CHILD(sibling);
1717 		else
1718 			(void)T4_ATTACH_CHILD(sibling);
1719 		if (error)
1720 			break;
1721 	}
1722 	return (error);
1723 }
1724 
1725 /*
1726  * Idempotent
1727  */
1728 static int
1729 t4_detach(device_t dev)
1730 {
1731 	int rc;
1732 
1733 	rc = notify_siblings(dev, 1);
1734 	if (rc) {
1735 		device_printf(dev,
1736 		    "failed to detach sibling devices: %d\n", rc);
1737 		return (rc);
1738 	}
1739 
1740 	return (t4_detach_common(dev));
1741 }
1742 
1743 int
1744 t4_detach_common(device_t dev)
1745 {
1746 	struct adapter *sc;
1747 	struct port_info *pi;
1748 	int i, rc;
1749 
1750 	sc = device_get_softc(dev);
1751 
1752 #ifdef TCP_OFFLOAD
1753 	rc = t4_deactivate_all_uld(sc);
1754 	if (rc) {
1755 		device_printf(dev,
1756 		    "failed to detach upper layer drivers: %d\n", rc);
1757 		return (rc);
1758 	}
1759 #endif
1760 
1761 	if (sc->cdev) {
1762 		destroy_dev(sc->cdev);
1763 		sc->cdev = NULL;
1764 	}
1765 
1766 	sx_xlock(&t4_list_lock);
1767 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1768 	sx_xunlock(&t4_list_lock);
1769 
1770 	sc->flags &= ~CHK_MBOX_ACCESS;
1771 	if (sc->flags & FULL_INIT_DONE) {
1772 		if (!(sc->flags & IS_VF))
1773 			t4_intr_disable(sc);
1774 	}
1775 
1776 	if (device_is_attached(dev)) {
1777 		rc = bus_generic_detach(dev);
1778 		if (rc) {
1779 			device_printf(dev,
1780 			    "failed to detach child devices: %d\n", rc);
1781 			return (rc);
1782 		}
1783 	}
1784 
1785 	for (i = 0; i < sc->intr_count; i++)
1786 		t4_free_irq(sc, &sc->irq[i]);
1787 
1788 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1789 		t4_free_tx_sched(sc);
1790 
1791 	for (i = 0; i < MAX_NPORTS; i++) {
1792 		pi = sc->port[i];
1793 		if (pi) {
1794 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1795 			if (pi->dev)
1796 				device_delete_child(dev, pi->dev);
1797 
1798 			mtx_destroy(&pi->pi_lock);
1799 			free(pi->vi, M_CXGBE);
1800 			free(pi, M_CXGBE);
1801 		}
1802 	}
1803 	callout_stop(&sc->cal_callout);
1804 	callout_drain(&sc->cal_callout);
1805 	device_delete_children(dev);
1806 	sysctl_ctx_free(&sc->ctx);
1807 	adapter_full_uninit(sc);
1808 
1809 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1810 		t4_fw_bye(sc, sc->mbox);
1811 
1812 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1813 		pci_release_msi(dev);
1814 
1815 	if (sc->regs_res)
1816 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1817 		    sc->regs_res);
1818 
1819 	if (sc->udbs_res)
1820 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1821 		    sc->udbs_res);
1822 
1823 	if (sc->msix_res)
1824 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1825 		    sc->msix_res);
1826 
1827 	if (sc->l2t)
1828 		t4_free_l2t(sc->l2t);
1829 	if (sc->smt)
1830 		t4_free_smt(sc->smt);
1831 	t4_free_atid_table(sc);
1832 #ifdef RATELIMIT
1833 	t4_free_etid_table(sc);
1834 #endif
1835 	if (sc->key_map)
1836 		vmem_destroy(sc->key_map);
1837 #ifdef INET6
1838 	t4_destroy_clip_table(sc);
1839 #endif
1840 
1841 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1842 	free(sc->sge.ofld_txq, M_CXGBE);
1843 #endif
1844 #ifdef TCP_OFFLOAD
1845 	free(sc->sge.ofld_rxq, M_CXGBE);
1846 #endif
1847 #ifdef DEV_NETMAP
1848 	free(sc->sge.nm_rxq, M_CXGBE);
1849 	free(sc->sge.nm_txq, M_CXGBE);
1850 #endif
1851 	free(sc->irq, M_CXGBE);
1852 	free(sc->sge.rxq, M_CXGBE);
1853 	free(sc->sge.txq, M_CXGBE);
1854 	free(sc->sge.ctrlq, M_CXGBE);
1855 	free(sc->sge.iqmap, M_CXGBE);
1856 	free(sc->sge.eqmap, M_CXGBE);
1857 	free(sc->tids.ftid_tab, M_CXGBE);
1858 	free(sc->tids.hpftid_tab, M_CXGBE);
1859 	free_hftid_hash(&sc->tids);
1860 	free(sc->tids.tid_tab, M_CXGBE);
1861 	t4_destroy_dma_tag(sc);
1862 
1863 	callout_drain(&sc->ktls_tick);
1864 	callout_drain(&sc->sfl_callout);
1865 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1866 		mtx_destroy(&sc->tids.ftid_lock);
1867 		cv_destroy(&sc->tids.ftid_cv);
1868 	}
1869 	if (mtx_initialized(&sc->tids.atid_lock))
1870 		mtx_destroy(&sc->tids.atid_lock);
1871 	if (mtx_initialized(&sc->ifp_lock))
1872 		mtx_destroy(&sc->ifp_lock);
1873 
1874 	if (rw_initialized(&sc->policy_lock)) {
1875 		rw_destroy(&sc->policy_lock);
1876 #ifdef TCP_OFFLOAD
1877 		if (sc->policy != NULL)
1878 			free_offload_policy(sc->policy);
1879 #endif
1880 	}
1881 
1882 	for (i = 0; i < NUM_MEMWIN; i++) {
1883 		struct memwin *mw = &sc->memwin[i];
1884 
1885 		if (rw_initialized(&mw->mw_lock))
1886 			rw_destroy(&mw->mw_lock);
1887 	}
1888 
1889 	mtx_destroy(&sc->sfl_lock);
1890 	mtx_destroy(&sc->reg_lock);
1891 	mtx_destroy(&sc->sc_lock);
1892 
1893 	bzero(sc, sizeof(*sc));
1894 
1895 	return (0);
1896 }
1897 
1898 static inline bool
1899 ok_to_reset(struct adapter *sc)
1900 {
1901 	struct tid_info *t = &sc->tids;
1902 	struct port_info *pi;
1903 	struct vi_info *vi;
1904 	int i, j;
1905 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1906 
1907 	if (is_t6(sc))
1908 		caps |= IFCAP_TXTLS;
1909 
1910 	ASSERT_SYNCHRONIZED_OP(sc);
1911 	MPASS(!(sc->flags & IS_VF));
1912 
1913 	for_each_port(sc, i) {
1914 		pi = sc->port[i];
1915 		for_each_vi(pi, j, vi) {
1916 			if (if_getcapenable(vi->ifp) & caps)
1917 				return (false);
1918 		}
1919 	}
1920 
1921 	if (atomic_load_int(&t->tids_in_use) > 0)
1922 		return (false);
1923 	if (atomic_load_int(&t->stids_in_use) > 0)
1924 		return (false);
1925 	if (atomic_load_int(&t->atids_in_use) > 0)
1926 		return (false);
1927 	if (atomic_load_int(&t->ftids_in_use) > 0)
1928 		return (false);
1929 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1930 		return (false);
1931 	if (atomic_load_int(&t->etids_in_use) > 0)
1932 		return (false);
1933 
1934 	return (true);
1935 }
1936 
1937 static inline int
1938 stop_adapter(struct adapter *sc)
1939 {
1940 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1941 		return (1);		/* Already stopped. */
1942 	return (t4_shutdown_adapter(sc));
1943 }
1944 
1945 static int
1946 t4_suspend(device_t dev)
1947 {
1948 	struct adapter *sc = device_get_softc(dev);
1949 	struct port_info *pi;
1950 	struct vi_info *vi;
1951 	if_t ifp;
1952 	struct sge_rxq *rxq;
1953 	struct sge_txq *txq;
1954 	struct sge_wrq *wrq;
1955 #ifdef TCP_OFFLOAD
1956 	struct sge_ofld_rxq *ofld_rxq;
1957 #endif
1958 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1959 	struct sge_ofld_txq *ofld_txq;
1960 #endif
1961 	int rc, i, j, k;
1962 
1963 	CH_ALERT(sc, "suspend requested\n");
1964 
1965 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1966 	if (rc != 0)
1967 		return (ENXIO);
1968 
1969 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1970 	MPASS(!hw_off_limits(sc));
1971 
1972 	if (!ok_to_reset(sc)) {
1973 		/* XXX: should list what resource is preventing suspend. */
1974 		CH_ERR(sc, "not safe to suspend.\n");
1975 		rc = EBUSY;
1976 		goto done;
1977 	}
1978 
1979 	/* No more DMA or interrupts. */
1980 	stop_adapter(sc);
1981 
1982 	/* Quiesce all activity. */
1983 	for_each_port(sc, i) {
1984 		pi = sc->port[i];
1985 		pi->vxlan_tcam_entry = false;
1986 
1987 		PORT_LOCK(pi);
1988 		if (pi->up_vis > 0) {
1989 			/*
1990 			 * t4_shutdown_adapter has already shut down all the
1991 			 * PHYs but it also disables interrupts and DMA so there
1992 			 * won't be a link interrupt.  So we update the state
1993 			 * manually and inform the kernel.
1994 			 */
1995 			pi->link_cfg.link_ok = false;
1996 			t4_os_link_changed(pi);
1997 		}
1998 		PORT_UNLOCK(pi);
1999 
2000 		for_each_vi(pi, j, vi) {
2001 			vi->xact_addr_filt = -1;
2002 			mtx_lock(&vi->tick_mtx);
2003 			vi->flags |= VI_SKIP_STATS;
2004 			mtx_unlock(&vi->tick_mtx);
2005 			if (!(vi->flags & VI_INIT_DONE))
2006 				continue;
2007 
2008 			ifp = vi->ifp;
2009 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2010 				mtx_lock(&vi->tick_mtx);
2011 				callout_stop(&vi->tick);
2012 				mtx_unlock(&vi->tick_mtx);
2013 				callout_drain(&vi->tick);
2014 			}
2015 
2016 			/*
2017 			 * Note that the HW is not available.
2018 			 */
2019 			for_each_txq(vi, k, txq) {
2020 				TXQ_LOCK(txq);
2021 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2022 				TXQ_UNLOCK(txq);
2023 			}
2024 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2025 			for_each_ofld_txq(vi, k, ofld_txq) {
2026 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2027 			}
2028 #endif
2029 			for_each_rxq(vi, k, rxq) {
2030 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2031 			}
2032 #if defined(TCP_OFFLOAD)
2033 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2034 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2035 			}
2036 #endif
2037 
2038 			quiesce_vi(vi);
2039 		}
2040 
2041 		if (sc->flags & FULL_INIT_DONE) {
2042 			/* Control queue */
2043 			wrq = &sc->sge.ctrlq[i];
2044 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2045 			quiesce_wrq(wrq);
2046 		}
2047 	}
2048 	if (sc->flags & FULL_INIT_DONE) {
2049 		/* Firmware event queue */
2050 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2051 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2052 	}
2053 
2054 	/* Stop calibration */
2055 	callout_stop(&sc->cal_callout);
2056 	callout_drain(&sc->cal_callout);
2057 
2058 	/* Mark the adapter totally off limits. */
2059 	mtx_lock(&sc->reg_lock);
2060 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2061 	sc->flags &= ~(FW_OK | MASTER_PF);
2062 	sc->reset_thread = NULL;
2063 	mtx_unlock(&sc->reg_lock);
2064 
2065 	if (t4_clock_gate_on_suspend) {
2066 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2067 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2068 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2069 	}
2070 
2071 	CH_ALERT(sc, "suspend completed.\n");
2072 done:
2073 	end_synchronized_op(sc, 0);
2074 	return (rc);
2075 }
2076 
2077 struct adapter_pre_reset_state {
2078 	u_int flags;
2079 	uint16_t nbmcaps;
2080 	uint16_t linkcaps;
2081 	uint16_t switchcaps;
2082 	uint16_t niccaps;
2083 	uint16_t toecaps;
2084 	uint16_t rdmacaps;
2085 	uint16_t cryptocaps;
2086 	uint16_t iscsicaps;
2087 	uint16_t fcoecaps;
2088 
2089 	u_int cfcsum;
2090 	char cfg_file[32];
2091 
2092 	struct adapter_params params;
2093 	struct t4_virt_res vres;
2094 	struct tid_info tids;
2095 	struct sge sge;
2096 
2097 	int rawf_base;
2098 	int nrawf;
2099 
2100 };
2101 
2102 static void
2103 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2104 {
2105 
2106 	ASSERT_SYNCHRONIZED_OP(sc);
2107 
2108 	o->flags = sc->flags;
2109 
2110 	o->nbmcaps =  sc->nbmcaps;
2111 	o->linkcaps = sc->linkcaps;
2112 	o->switchcaps = sc->switchcaps;
2113 	o->niccaps = sc->niccaps;
2114 	o->toecaps = sc->toecaps;
2115 	o->rdmacaps = sc->rdmacaps;
2116 	o->cryptocaps = sc->cryptocaps;
2117 	o->iscsicaps = sc->iscsicaps;
2118 	o->fcoecaps = sc->fcoecaps;
2119 
2120 	o->cfcsum = sc->cfcsum;
2121 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2122 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2123 
2124 	o->params = sc->params;
2125 	o->vres = sc->vres;
2126 	o->tids = sc->tids;
2127 	o->sge = sc->sge;
2128 
2129 	o->rawf_base = sc->rawf_base;
2130 	o->nrawf = sc->nrawf;
2131 }
2132 
2133 static int
2134 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2135 {
2136 	int rc = 0;
2137 
2138 	ASSERT_SYNCHRONIZED_OP(sc);
2139 
2140 	/* Capabilities */
2141 #define COMPARE_CAPS(c) do { \
2142 	if (o->c##caps != sc->c##caps) { \
2143 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2144 		    sc->c##caps); \
2145 		rc = EINVAL; \
2146 	} \
2147 } while (0)
2148 	COMPARE_CAPS(nbm);
2149 	COMPARE_CAPS(link);
2150 	COMPARE_CAPS(switch);
2151 	COMPARE_CAPS(nic);
2152 	COMPARE_CAPS(toe);
2153 	COMPARE_CAPS(rdma);
2154 	COMPARE_CAPS(crypto);
2155 	COMPARE_CAPS(iscsi);
2156 	COMPARE_CAPS(fcoe);
2157 #undef COMPARE_CAPS
2158 
2159 	/* Firmware config file */
2160 	if (o->cfcsum != sc->cfcsum) {
2161 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2162 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2163 		rc = EINVAL;
2164 	}
2165 
2166 #define COMPARE_PARAM(p, name) do { \
2167 	if (o->p != sc->p) { \
2168 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2169 		rc = EINVAL; \
2170 	} \
2171 } while (0)
2172 	COMPARE_PARAM(sge.iq_start, iq_start);
2173 	COMPARE_PARAM(sge.eq_start, eq_start);
2174 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2175 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2176 	COMPARE_PARAM(tids.nftids, nftids);
2177 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2178 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2179 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2180 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2181 	COMPARE_PARAM(tids.tid_base, tid_base);
2182 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2183 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2184 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2185 	COMPARE_PARAM(rawf_base, rawf_base);
2186 	COMPARE_PARAM(nrawf, nrawf);
2187 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2188 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2189 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2190 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2191 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2192 	COMPARE_PARAM(tids.ntids, ntids);
2193 	COMPARE_PARAM(tids.etid_base, etid_base);
2194 	COMPARE_PARAM(tids.etid_end, etid_end);
2195 	COMPARE_PARAM(tids.netids, netids);
2196 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2197 	COMPARE_PARAM(params.ethoffload, ethoffload);
2198 	COMPARE_PARAM(tids.natids, natids);
2199 	COMPARE_PARAM(tids.stid_base, stid_base);
2200 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2201 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2202 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2203 	COMPARE_PARAM(vres.stag.start, stag_start);
2204 	COMPARE_PARAM(vres.stag.size, stag_size);
2205 	COMPARE_PARAM(vres.rq.start, rq_start);
2206 	COMPARE_PARAM(vres.rq.size, rq_size);
2207 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2208 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2209 	COMPARE_PARAM(vres.qp.start, qp_start);
2210 	COMPARE_PARAM(vres.qp.size, qp_size);
2211 	COMPARE_PARAM(vres.cq.start, cq_start);
2212 	COMPARE_PARAM(vres.cq.size, cq_size);
2213 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2214 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2215 	COMPARE_PARAM(vres.srq.start, srq_start);
2216 	COMPARE_PARAM(vres.srq.size, srq_size);
2217 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2218 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2219 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2220 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2221 	COMPARE_PARAM(vres.key.start, key_start);
2222 	COMPARE_PARAM(vres.key.size, key_size);
2223 #undef COMPARE_PARAM
2224 
2225 	return (rc);
2226 }
2227 
2228 static int
2229 t4_resume(device_t dev)
2230 {
2231 	struct adapter *sc = device_get_softc(dev);
2232 	struct adapter_pre_reset_state *old_state = NULL;
2233 	struct port_info *pi;
2234 	struct vi_info *vi;
2235 	if_t ifp;
2236 	struct sge_txq *txq;
2237 	int rc, i, j, k;
2238 
2239 	CH_ALERT(sc, "resume requested.\n");
2240 
2241 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2242 	if (rc != 0)
2243 		return (ENXIO);
2244 	MPASS(hw_off_limits(sc));
2245 	MPASS((sc->flags & FW_OK) == 0);
2246 	MPASS((sc->flags & MASTER_PF) == 0);
2247 	MPASS(sc->reset_thread == NULL);
2248 	sc->reset_thread = curthread;
2249 
2250 	/* Register access is expected to work by the time we're here. */
2251 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2252 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2253 		rc = ENXIO;
2254 		goto done;
2255 	}
2256 
2257 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2258 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2259 
2260 	/* Restore memory window. */
2261 	setup_memwin(sc);
2262 
2263 	/* Go no further if recovery mode has been requested. */
2264 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2265 		CH_ALERT(sc, "recovery mode on resume.\n");
2266 		rc = 0;
2267 		mtx_lock(&sc->reg_lock);
2268 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2269 		mtx_unlock(&sc->reg_lock);
2270 		goto done;
2271 	}
2272 
2273 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2274 	save_caps_and_params(sc, old_state);
2275 
2276 	/* Reestablish contact with firmware and become the primary PF. */
2277 	rc = contact_firmware(sc);
2278 	if (rc != 0)
2279 		goto done; /* error message displayed already */
2280 	MPASS(sc->flags & FW_OK);
2281 
2282 	if (sc->flags & MASTER_PF) {
2283 		rc = partition_resources(sc);
2284 		if (rc != 0)
2285 			goto done; /* error message displayed already */
2286 		t4_intr_clear(sc);
2287 	}
2288 
2289 	rc = get_params__post_init(sc);
2290 	if (rc != 0)
2291 		goto done; /* error message displayed already */
2292 
2293 	rc = set_params__post_init(sc);
2294 	if (rc != 0)
2295 		goto done; /* error message displayed already */
2296 
2297 	rc = compare_caps_and_params(sc, old_state);
2298 	if (rc != 0)
2299 		goto done; /* error message displayed already */
2300 
2301 	for_each_port(sc, i) {
2302 		pi = sc->port[i];
2303 		MPASS(pi != NULL);
2304 		MPASS(pi->vi != NULL);
2305 		MPASS(pi->vi[0].dev == pi->dev);
2306 
2307 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2308 		if (rc != 0) {
2309 			CH_ERR(sc,
2310 			    "failed to re-initialize port %d: %d\n", i, rc);
2311 			goto done;
2312 		}
2313 		MPASS(sc->chan_map[pi->tx_chan] == i);
2314 
2315 		PORT_LOCK(pi);
2316 		fixup_link_config(pi);
2317 		build_medialist(pi);
2318 		PORT_UNLOCK(pi);
2319 		for_each_vi(pi, j, vi) {
2320 			if (IS_MAIN_VI(vi))
2321 				continue;
2322 			rc = alloc_extra_vi(sc, pi, vi);
2323 			if (rc != 0) {
2324 				CH_ERR(vi,
2325 				    "failed to re-allocate extra VI: %d\n", rc);
2326 				goto done;
2327 			}
2328 		}
2329 	}
2330 
2331 	/*
2332 	 * Interrupts and queues are about to be enabled and other threads will
2333 	 * want to access the hardware too.  It is safe to do so.  Note that
2334 	 * this thread is still in the middle of a synchronized_op.
2335 	 */
2336 	mtx_lock(&sc->reg_lock);
2337 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2338 	mtx_unlock(&sc->reg_lock);
2339 
2340 	if (sc->flags & FULL_INIT_DONE) {
2341 		rc = adapter_full_init(sc);
2342 		if (rc != 0) {
2343 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2344 			goto done;
2345 		}
2346 
2347 		if (sc->vxlan_refcount > 0)
2348 			enable_vxlan_rx(sc);
2349 
2350 		for_each_port(sc, i) {
2351 			pi = sc->port[i];
2352 			for_each_vi(pi, j, vi) {
2353 				mtx_lock(&vi->tick_mtx);
2354 				vi->flags &= ~VI_SKIP_STATS;
2355 				mtx_unlock(&vi->tick_mtx);
2356 				if (!(vi->flags & VI_INIT_DONE))
2357 					continue;
2358 				rc = vi_full_init(vi);
2359 				if (rc != 0) {
2360 					CH_ERR(vi, "failed to re-initialize "
2361 					    "interface: %d\n", rc);
2362 					goto done;
2363 				}
2364 
2365 				ifp = vi->ifp;
2366 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2367 					continue;
2368 				/*
2369 				 * Note that we do not setup multicast addresses
2370 				 * in the first pass.  This ensures that the
2371 				 * unicast DMACs for all VIs on all ports get an
2372 				 * MPS TCAM entry.
2373 				 */
2374 				rc = update_mac_settings(ifp, XGMAC_ALL &
2375 				    ~XGMAC_MCADDRS);
2376 				if (rc != 0) {
2377 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2378 					goto done;
2379 				}
2380 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2381 				    true);
2382 				if (rc != 0) {
2383 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2384 					goto done;
2385 				}
2386 				for_each_txq(vi, k, txq) {
2387 					TXQ_LOCK(txq);
2388 					txq->eq.flags |= EQ_ENABLED;
2389 					TXQ_UNLOCK(txq);
2390 				}
2391 				mtx_lock(&vi->tick_mtx);
2392 				callout_schedule(&vi->tick, hz);
2393 				mtx_unlock(&vi->tick_mtx);
2394 			}
2395 			PORT_LOCK(pi);
2396 			if (pi->up_vis > 0) {
2397 				t4_update_port_info(pi);
2398 				fixup_link_config(pi);
2399 				build_medialist(pi);
2400 				apply_link_config(pi);
2401 				if (pi->link_cfg.link_ok)
2402 					t4_os_link_changed(pi);
2403 			}
2404 			PORT_UNLOCK(pi);
2405 		}
2406 
2407 		/* Now reprogram the L2 multicast addresses. */
2408 		for_each_port(sc, i) {
2409 			pi = sc->port[i];
2410 			for_each_vi(pi, j, vi) {
2411 				if (!(vi->flags & VI_INIT_DONE))
2412 					continue;
2413 				ifp = vi->ifp;
2414 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2415 					continue;
2416 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2417 				if (rc != 0) {
2418 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2419 					rc = 0;	/* carry on */
2420 				}
2421 			}
2422 		}
2423 	}
2424 
2425 	/* Reset all calibration */
2426 	t4_calibration_start(sc);
2427 
2428 done:
2429 	if (rc == 0) {
2430 		sc->incarnation++;
2431 		CH_ALERT(sc, "resume completed.\n");
2432 	}
2433 	end_synchronized_op(sc, 0);
2434 	free(old_state, M_CXGBE);
2435 	return (rc);
2436 }
2437 
2438 static int
2439 t4_reset_prepare(device_t dev, device_t child)
2440 {
2441 	struct adapter *sc = device_get_softc(dev);
2442 
2443 	CH_ALERT(sc, "reset_prepare.\n");
2444 	return (0);
2445 }
2446 
2447 static int
2448 t4_reset_post(device_t dev, device_t child)
2449 {
2450 	struct adapter *sc = device_get_softc(dev);
2451 
2452 	CH_ALERT(sc, "reset_post.\n");
2453 	return (0);
2454 }
2455 
2456 static int
2457 reset_adapter(struct adapter *sc)
2458 {
2459 	int rc, oldinc, error_flags;
2460 
2461 	CH_ALERT(sc, "reset requested.\n");
2462 
2463 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2464 	if (rc != 0)
2465 		return (EBUSY);
2466 
2467 	if (hw_off_limits(sc)) {
2468 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2469 		rc = ENXIO;
2470 		goto done;
2471 	}
2472 
2473 	if (!ok_to_reset(sc)) {
2474 		/* XXX: should list what resource is preventing reset. */
2475 		CH_ERR(sc, "not safe to reset.\n");
2476 		rc = EBUSY;
2477 		goto done;
2478 	}
2479 
2480 done:
2481 	oldinc = sc->incarnation;
2482 	end_synchronized_op(sc, 0);
2483 	if (rc != 0)
2484 		return (rc);	/* Error logged already. */
2485 
2486 	atomic_add_int(&sc->num_resets, 1);
2487 	mtx_lock(&Giant);
2488 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2489 	mtx_unlock(&Giant);
2490 	if (rc != 0)
2491 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2492 	else {
2493 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2494 		if (rc != 0)
2495 			return (EBUSY);
2496 		error_flags = atomic_load_int(&sc->error_flags);
2497 		if (sc->incarnation > oldinc && error_flags == 0) {
2498 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2499 		} else {
2500 			CH_ERR(sc, "adapter did not reset properly, flags "
2501 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2502 			    error_flags);
2503 			rc = ENXIO;
2504 		}
2505 		end_synchronized_op(sc, 0);
2506 	}
2507 
2508 	return (rc);
2509 }
2510 
2511 static void
2512 reset_adapter_task(void *arg, int pending)
2513 {
2514 	/* XXX: t4_async_event here? */
2515 	reset_adapter(arg);
2516 }
2517 
2518 static int
2519 cxgbe_probe(device_t dev)
2520 {
2521 	char buf[128];
2522 	struct port_info *pi = device_get_softc(dev);
2523 
2524 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2525 	device_set_desc_copy(dev, buf);
2526 
2527 	return (BUS_PROBE_DEFAULT);
2528 }
2529 
2530 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2531     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2532     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2533     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2534 #define T4_CAP_ENABLE (T4_CAP)
2535 
2536 static int
2537 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2538 {
2539 	if_t ifp;
2540 	struct sbuf *sb;
2541 	struct sysctl_ctx_list *ctx = &vi->ctx;
2542 	struct sysctl_oid_list *children;
2543 	struct pfil_head_args pa;
2544 	struct adapter *sc = vi->adapter;
2545 
2546 	sysctl_ctx_init(ctx);
2547 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2548 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2549 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2550 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2551 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2552 #ifdef DEV_NETMAP
2553 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2554 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2555 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2556 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2557 #endif
2558 #ifdef TCP_OFFLOAD
2559 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2560 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2561 #endif
2562 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2563 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2564 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2565 #endif
2566 
2567 	vi->xact_addr_filt = -1;
2568 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2569 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2570 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2571 		vi->flags |= TX_USES_VM_WR;
2572 
2573 	/* Allocate an ifnet and set it up */
2574 	ifp = if_alloc_dev(IFT_ETHER, dev);
2575 	if (ifp == NULL) {
2576 		device_printf(dev, "Cannot allocate ifnet\n");
2577 		return (ENOMEM);
2578 	}
2579 	vi->ifp = ifp;
2580 	if_setsoftc(ifp, vi);
2581 
2582 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2583 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2584 
2585 	if_setinitfn(ifp, cxgbe_init);
2586 	if_setioctlfn(ifp, cxgbe_ioctl);
2587 	if_settransmitfn(ifp, cxgbe_transmit);
2588 	if_setqflushfn(ifp, cxgbe_qflush);
2589 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2590 		if_setgetcounterfn(ifp, vi_get_counter);
2591 	else
2592 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2593 #if defined(KERN_TLS) || defined(RATELIMIT)
2594 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2595 #endif
2596 #ifdef RATELIMIT
2597 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2598 #endif
2599 
2600 	if_setcapabilities(ifp, T4_CAP);
2601 	if_setcapenable(ifp, T4_CAP_ENABLE);
2602 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2603 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2604 	if (chip_id(sc) >= CHELSIO_T6) {
2605 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2606 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2607 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2608 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2609 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2610 	}
2611 
2612 #ifdef TCP_OFFLOAD
2613 	if (vi->nofldrxq != 0)
2614 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2615 #endif
2616 #ifdef RATELIMIT
2617 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2618 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2619 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2620 	}
2621 #endif
2622 
2623 	if_sethwtsomax(ifp, IP_MAXPACKET);
2624 	if (vi->flags & TX_USES_VM_WR)
2625 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2626 	else
2627 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2628 #ifdef RATELIMIT
2629 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2630 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2631 #endif
2632 	if_sethwtsomaxsegsize(ifp, 65536);
2633 #ifdef KERN_TLS
2634 	if (is_ktls(sc)) {
2635 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2636 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2637 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2638 	}
2639 #endif
2640 
2641 	ether_ifattach(ifp, vi->hw_addr);
2642 #ifdef DEV_NETMAP
2643 	if (vi->nnmrxq != 0)
2644 		cxgbe_nm_attach(vi);
2645 #endif
2646 	sb = sbuf_new_auto();
2647 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2648 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2649 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2650 	case IFCAP_TOE:
2651 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2652 		break;
2653 	case IFCAP_TOE | IFCAP_TXRTLMT:
2654 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2655 		break;
2656 	case IFCAP_TXRTLMT:
2657 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2658 		break;
2659 	}
2660 #endif
2661 #ifdef TCP_OFFLOAD
2662 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2663 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2664 #endif
2665 #ifdef DEV_NETMAP
2666 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2667 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2668 		    vi->nnmtxq, vi->nnmrxq);
2669 #endif
2670 	sbuf_finish(sb);
2671 	device_printf(dev, "%s\n", sbuf_data(sb));
2672 	sbuf_delete(sb);
2673 
2674 	vi_sysctls(vi);
2675 
2676 	pa.pa_version = PFIL_VERSION;
2677 	pa.pa_flags = PFIL_IN;
2678 	pa.pa_type = PFIL_TYPE_ETHERNET;
2679 	pa.pa_headname = if_name(ifp);
2680 	vi->pfil = pfil_head_register(&pa);
2681 
2682 	return (0);
2683 }
2684 
2685 static int
2686 cxgbe_attach(device_t dev)
2687 {
2688 	struct port_info *pi = device_get_softc(dev);
2689 	struct adapter *sc = pi->adapter;
2690 	struct vi_info *vi;
2691 	int i, rc;
2692 
2693 	sysctl_ctx_init(&pi->ctx);
2694 
2695 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2696 	if (rc)
2697 		return (rc);
2698 
2699 	for_each_vi(pi, i, vi) {
2700 		if (i == 0)
2701 			continue;
2702 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2703 		if (vi->dev == NULL) {
2704 			device_printf(dev, "failed to add VI %d\n", i);
2705 			continue;
2706 		}
2707 		device_set_softc(vi->dev, vi);
2708 	}
2709 
2710 	cxgbe_sysctls(pi);
2711 
2712 	bus_generic_attach(dev);
2713 
2714 	return (0);
2715 }
2716 
2717 static void
2718 cxgbe_vi_detach(struct vi_info *vi)
2719 {
2720 	if_t ifp = vi->ifp;
2721 
2722 	if (vi->pfil != NULL) {
2723 		pfil_head_unregister(vi->pfil);
2724 		vi->pfil = NULL;
2725 	}
2726 
2727 	ether_ifdetach(ifp);
2728 
2729 	/* Let detach proceed even if these fail. */
2730 #ifdef DEV_NETMAP
2731 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2732 		cxgbe_nm_detach(vi);
2733 #endif
2734 	cxgbe_uninit_synchronized(vi);
2735 	callout_drain(&vi->tick);
2736 	sysctl_ctx_free(&vi->ctx);
2737 	vi_full_uninit(vi);
2738 
2739 	if_free(vi->ifp);
2740 	vi->ifp = NULL;
2741 }
2742 
2743 static int
2744 cxgbe_detach(device_t dev)
2745 {
2746 	struct port_info *pi = device_get_softc(dev);
2747 	struct adapter *sc = pi->adapter;
2748 	int rc;
2749 
2750 	/* Detach the extra VIs first. */
2751 	rc = bus_generic_detach(dev);
2752 	if (rc)
2753 		return (rc);
2754 	device_delete_children(dev);
2755 
2756 	sysctl_ctx_free(&pi->ctx);
2757 	doom_vi(sc, &pi->vi[0]);
2758 
2759 	if (pi->flags & HAS_TRACEQ) {
2760 		sc->traceq = -1;	/* cloner should not create ifnet */
2761 		t4_tracer_port_detach(sc);
2762 	}
2763 
2764 	cxgbe_vi_detach(&pi->vi[0]);
2765 	ifmedia_removeall(&pi->media);
2766 
2767 	end_synchronized_op(sc, 0);
2768 
2769 	return (0);
2770 }
2771 
2772 static void
2773 cxgbe_init(void *arg)
2774 {
2775 	struct vi_info *vi = arg;
2776 	struct adapter *sc = vi->adapter;
2777 
2778 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2779 		return;
2780 	cxgbe_init_synchronized(vi);
2781 	end_synchronized_op(sc, 0);
2782 }
2783 
2784 static int
2785 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2786 {
2787 	int rc = 0, mtu, flags;
2788 	struct vi_info *vi = if_getsoftc(ifp);
2789 	struct port_info *pi = vi->pi;
2790 	struct adapter *sc = pi->adapter;
2791 	struct ifreq *ifr = (struct ifreq *)data;
2792 	uint32_t mask;
2793 
2794 	switch (cmd) {
2795 	case SIOCSIFMTU:
2796 		mtu = ifr->ifr_mtu;
2797 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2798 			return (EINVAL);
2799 
2800 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2801 		if (rc)
2802 			return (rc);
2803 		if_setmtu(ifp, mtu);
2804 		if (vi->flags & VI_INIT_DONE) {
2805 			t4_update_fl_bufsize(ifp);
2806 			if (!hw_off_limits(sc) &&
2807 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2808 				rc = update_mac_settings(ifp, XGMAC_MTU);
2809 		}
2810 		end_synchronized_op(sc, 0);
2811 		break;
2812 
2813 	case SIOCSIFFLAGS:
2814 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2815 		if (rc)
2816 			return (rc);
2817 
2818 		if (hw_off_limits(sc)) {
2819 			rc = ENXIO;
2820 			goto fail;
2821 		}
2822 
2823 		if (if_getflags(ifp) & IFF_UP) {
2824 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2825 				flags = vi->if_flags;
2826 				if ((if_getflags(ifp) ^ flags) &
2827 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2828 					rc = update_mac_settings(ifp,
2829 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2830 				}
2831 			} else {
2832 				rc = cxgbe_init_synchronized(vi);
2833 			}
2834 			vi->if_flags = if_getflags(ifp);
2835 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2836 			rc = cxgbe_uninit_synchronized(vi);
2837 		}
2838 		end_synchronized_op(sc, 0);
2839 		break;
2840 
2841 	case SIOCADDMULTI:
2842 	case SIOCDELMULTI:
2843 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2844 		if (rc)
2845 			return (rc);
2846 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2847 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2848 		end_synchronized_op(sc, 0);
2849 		break;
2850 
2851 	case SIOCSIFCAP:
2852 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2853 		if (rc)
2854 			return (rc);
2855 
2856 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2857 		if (mask & IFCAP_TXCSUM) {
2858 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2859 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2860 
2861 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2862 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2863 				mask &= ~IFCAP_TSO4;
2864 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2865 				if_printf(ifp,
2866 				    "tso4 disabled due to -txcsum.\n");
2867 			}
2868 		}
2869 		if (mask & IFCAP_TXCSUM_IPV6) {
2870 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2871 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2872 
2873 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2874 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2875 				mask &= ~IFCAP_TSO6;
2876 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2877 				if_printf(ifp,
2878 				    "tso6 disabled due to -txcsum6.\n");
2879 			}
2880 		}
2881 		if (mask & IFCAP_RXCSUM)
2882 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2883 		if (mask & IFCAP_RXCSUM_IPV6)
2884 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2885 
2886 		/*
2887 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2888 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2889 		 * sending a TSO request our way, so it's sufficient to toggle
2890 		 * IFCAP_TSOx only.
2891 		 */
2892 		if (mask & IFCAP_TSO4) {
2893 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2894 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2895 				if_printf(ifp, "enable txcsum first.\n");
2896 				rc = EAGAIN;
2897 				goto fail;
2898 			}
2899 			if_togglecapenable(ifp, IFCAP_TSO4);
2900 		}
2901 		if (mask & IFCAP_TSO6) {
2902 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2903 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2904 				if_printf(ifp, "enable txcsum6 first.\n");
2905 				rc = EAGAIN;
2906 				goto fail;
2907 			}
2908 			if_togglecapenable(ifp, IFCAP_TSO6);
2909 		}
2910 		if (mask & IFCAP_LRO) {
2911 #if defined(INET) || defined(INET6)
2912 			int i;
2913 			struct sge_rxq *rxq;
2914 
2915 			if_togglecapenable(ifp, IFCAP_LRO);
2916 			for_each_rxq(vi, i, rxq) {
2917 				if (if_getcapenable(ifp) & IFCAP_LRO)
2918 					rxq->iq.flags |= IQ_LRO_ENABLED;
2919 				else
2920 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2921 			}
2922 #endif
2923 		}
2924 #ifdef TCP_OFFLOAD
2925 		if (mask & IFCAP_TOE) {
2926 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2927 
2928 			rc = toe_capability(vi, enable);
2929 			if (rc != 0)
2930 				goto fail;
2931 
2932 			if_togglecapenable(ifp, mask);
2933 		}
2934 #endif
2935 		if (mask & IFCAP_VLAN_HWTAGGING) {
2936 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2937 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2938 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2939 		}
2940 		if (mask & IFCAP_VLAN_MTU) {
2941 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2942 
2943 			/* Need to find out how to disable auto-mtu-inflation */
2944 		}
2945 		if (mask & IFCAP_VLAN_HWTSO)
2946 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2947 		if (mask & IFCAP_VLAN_HWCSUM)
2948 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2949 #ifdef RATELIMIT
2950 		if (mask & IFCAP_TXRTLMT)
2951 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2952 #endif
2953 		if (mask & IFCAP_HWRXTSTMP) {
2954 			int i;
2955 			struct sge_rxq *rxq;
2956 
2957 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2958 			for_each_rxq(vi, i, rxq) {
2959 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2960 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2961 				else
2962 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2963 			}
2964 		}
2965 		if (mask & IFCAP_MEXTPG)
2966 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2967 
2968 #ifdef KERN_TLS
2969 		if (mask & IFCAP_TXTLS) {
2970 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2971 
2972 			rc = ktls_capability(sc, enable);
2973 			if (rc != 0)
2974 				goto fail;
2975 
2976 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2977 		}
2978 #endif
2979 		if (mask & IFCAP_VXLAN_HWCSUM) {
2980 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2981 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2982 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2983 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2984 		}
2985 		if (mask & IFCAP_VXLAN_HWTSO) {
2986 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2987 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2988 			    CSUM_INNER_IP_TSO);
2989 		}
2990 
2991 #ifdef VLAN_CAPABILITIES
2992 		VLAN_CAPABILITIES(ifp);
2993 #endif
2994 fail:
2995 		end_synchronized_op(sc, 0);
2996 		break;
2997 
2998 	case SIOCSIFMEDIA:
2999 	case SIOCGIFMEDIA:
3000 	case SIOCGIFXMEDIA:
3001 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3002 		break;
3003 
3004 	case SIOCGI2C: {
3005 		struct ifi2creq i2c;
3006 
3007 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3008 		if (rc != 0)
3009 			break;
3010 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3011 			rc = EPERM;
3012 			break;
3013 		}
3014 		if (i2c.len > sizeof(i2c.data)) {
3015 			rc = EINVAL;
3016 			break;
3017 		}
3018 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3019 		if (rc)
3020 			return (rc);
3021 		if (hw_off_limits(sc))
3022 			rc = ENXIO;
3023 		else
3024 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3025 			    i2c.offset, i2c.len, &i2c.data[0]);
3026 		end_synchronized_op(sc, 0);
3027 		if (rc == 0)
3028 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3029 		break;
3030 	}
3031 
3032 	default:
3033 		rc = ether_ioctl(ifp, cmd, data);
3034 	}
3035 
3036 	return (rc);
3037 }
3038 
3039 static int
3040 cxgbe_transmit(if_t ifp, struct mbuf *m)
3041 {
3042 	struct vi_info *vi = if_getsoftc(ifp);
3043 	struct port_info *pi = vi->pi;
3044 	struct adapter *sc;
3045 	struct sge_txq *txq;
3046 	void *items[1];
3047 	int rc;
3048 
3049 	M_ASSERTPKTHDR(m);
3050 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3051 #if defined(KERN_TLS) || defined(RATELIMIT)
3052 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3053 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3054 #endif
3055 
3056 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3057 		m_freem(m);
3058 		return (ENETDOWN);
3059 	}
3060 
3061 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3062 	if (__predict_false(rc != 0)) {
3063 		if (__predict_true(rc == EINPROGRESS)) {
3064 			/* queued by parse_pkt */
3065 			MPASS(m != NULL);
3066 			return (0);
3067 		}
3068 
3069 		MPASS(m == NULL);			/* was freed already */
3070 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3071 		return (rc);
3072 	}
3073 
3074 	/* Select a txq. */
3075 	sc = vi->adapter;
3076 	txq = &sc->sge.txq[vi->first_txq];
3077 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3078 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3079 		    vi->rsrv_noflowq);
3080 
3081 	items[0] = m;
3082 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3083 	if (__predict_false(rc != 0))
3084 		m_freem(m);
3085 
3086 	return (rc);
3087 }
3088 
3089 static void
3090 cxgbe_qflush(if_t ifp)
3091 {
3092 	struct vi_info *vi = if_getsoftc(ifp);
3093 	struct sge_txq *txq;
3094 	int i;
3095 
3096 	/* queues do not exist if !VI_INIT_DONE. */
3097 	if (vi->flags & VI_INIT_DONE) {
3098 		for_each_txq(vi, i, txq) {
3099 			TXQ_LOCK(txq);
3100 			txq->eq.flags |= EQ_QFLUSH;
3101 			TXQ_UNLOCK(txq);
3102 			while (!mp_ring_is_idle(txq->r)) {
3103 				mp_ring_check_drainage(txq->r, 4096);
3104 				pause("qflush", 1);
3105 			}
3106 			TXQ_LOCK(txq);
3107 			txq->eq.flags &= ~EQ_QFLUSH;
3108 			TXQ_UNLOCK(txq);
3109 		}
3110 	}
3111 	if_qflush(ifp);
3112 }
3113 
3114 static uint64_t
3115 vi_get_counter(if_t ifp, ift_counter c)
3116 {
3117 	struct vi_info *vi = if_getsoftc(ifp);
3118 	struct fw_vi_stats_vf *s = &vi->stats;
3119 
3120 	mtx_lock(&vi->tick_mtx);
3121 	vi_refresh_stats(vi);
3122 	mtx_unlock(&vi->tick_mtx);
3123 
3124 	switch (c) {
3125 	case IFCOUNTER_IPACKETS:
3126 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3127 		    s->rx_ucast_frames);
3128 	case IFCOUNTER_IERRORS:
3129 		return (s->rx_err_frames);
3130 	case IFCOUNTER_OPACKETS:
3131 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3132 		    s->tx_ucast_frames + s->tx_offload_frames);
3133 	case IFCOUNTER_OERRORS:
3134 		return (s->tx_drop_frames);
3135 	case IFCOUNTER_IBYTES:
3136 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3137 		    s->rx_ucast_bytes);
3138 	case IFCOUNTER_OBYTES:
3139 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3140 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3141 	case IFCOUNTER_IMCASTS:
3142 		return (s->rx_mcast_frames);
3143 	case IFCOUNTER_OMCASTS:
3144 		return (s->tx_mcast_frames);
3145 	case IFCOUNTER_OQDROPS: {
3146 		uint64_t drops;
3147 
3148 		drops = 0;
3149 		if (vi->flags & VI_INIT_DONE) {
3150 			int i;
3151 			struct sge_txq *txq;
3152 
3153 			for_each_txq(vi, i, txq)
3154 				drops += counter_u64_fetch(txq->r->dropped);
3155 		}
3156 
3157 		return (drops);
3158 
3159 	}
3160 
3161 	default:
3162 		return (if_get_counter_default(ifp, c));
3163 	}
3164 }
3165 
3166 static uint64_t
3167 cxgbe_get_counter(if_t ifp, ift_counter c)
3168 {
3169 	struct vi_info *vi = if_getsoftc(ifp);
3170 	struct port_info *pi = vi->pi;
3171 	struct port_stats *s = &pi->stats;
3172 
3173 	mtx_lock(&vi->tick_mtx);
3174 	cxgbe_refresh_stats(vi);
3175 	mtx_unlock(&vi->tick_mtx);
3176 
3177 	switch (c) {
3178 	case IFCOUNTER_IPACKETS:
3179 		return (s->rx_frames);
3180 
3181 	case IFCOUNTER_IERRORS:
3182 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3183 		    s->rx_fcs_err + s->rx_len_err);
3184 
3185 	case IFCOUNTER_OPACKETS:
3186 		return (s->tx_frames);
3187 
3188 	case IFCOUNTER_OERRORS:
3189 		return (s->tx_error_frames);
3190 
3191 	case IFCOUNTER_IBYTES:
3192 		return (s->rx_octets);
3193 
3194 	case IFCOUNTER_OBYTES:
3195 		return (s->tx_octets);
3196 
3197 	case IFCOUNTER_IMCASTS:
3198 		return (s->rx_mcast_frames);
3199 
3200 	case IFCOUNTER_OMCASTS:
3201 		return (s->tx_mcast_frames);
3202 
3203 	case IFCOUNTER_IQDROPS:
3204 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3205 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3206 		    s->rx_trunc3 + pi->tnl_cong_drops);
3207 
3208 	case IFCOUNTER_OQDROPS: {
3209 		uint64_t drops;
3210 
3211 		drops = s->tx_drop;
3212 		if (vi->flags & VI_INIT_DONE) {
3213 			int i;
3214 			struct sge_txq *txq;
3215 
3216 			for_each_txq(vi, i, txq)
3217 				drops += counter_u64_fetch(txq->r->dropped);
3218 		}
3219 
3220 		return (drops);
3221 
3222 	}
3223 
3224 	default:
3225 		return (if_get_counter_default(ifp, c));
3226 	}
3227 }
3228 
3229 #if defined(KERN_TLS) || defined(RATELIMIT)
3230 static int
3231 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3232     struct m_snd_tag **pt)
3233 {
3234 	int error;
3235 
3236 	switch (params->hdr.type) {
3237 #ifdef RATELIMIT
3238 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3239 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3240 		break;
3241 #endif
3242 #ifdef KERN_TLS
3243 	case IF_SND_TAG_TYPE_TLS:
3244 	{
3245 		struct vi_info *vi = if_getsoftc(ifp);
3246 
3247 		if (is_t6(vi->pi->adapter))
3248 			error = t6_tls_tag_alloc(ifp, params, pt);
3249 		else
3250 			error = EOPNOTSUPP;
3251 		break;
3252 	}
3253 #endif
3254 	default:
3255 		error = EOPNOTSUPP;
3256 	}
3257 	return (error);
3258 }
3259 #endif
3260 
3261 /*
3262  * The kernel picks a media from the list we had provided but we still validate
3263  * the requeste.
3264  */
3265 int
3266 cxgbe_media_change(if_t ifp)
3267 {
3268 	struct vi_info *vi = if_getsoftc(ifp);
3269 	struct port_info *pi = vi->pi;
3270 	struct ifmedia *ifm = &pi->media;
3271 	struct link_config *lc = &pi->link_cfg;
3272 	struct adapter *sc = pi->adapter;
3273 	int rc;
3274 
3275 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3276 	if (rc != 0)
3277 		return (rc);
3278 	PORT_LOCK(pi);
3279 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3280 		/* ifconfig .. media autoselect */
3281 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3282 			rc = ENOTSUP; /* AN not supported by transceiver */
3283 			goto done;
3284 		}
3285 		lc->requested_aneg = AUTONEG_ENABLE;
3286 		lc->requested_speed = 0;
3287 		lc->requested_fc |= PAUSE_AUTONEG;
3288 	} else {
3289 		lc->requested_aneg = AUTONEG_DISABLE;
3290 		lc->requested_speed =
3291 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3292 		lc->requested_fc = 0;
3293 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3294 			lc->requested_fc |= PAUSE_RX;
3295 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3296 			lc->requested_fc |= PAUSE_TX;
3297 	}
3298 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3299 		fixup_link_config(pi);
3300 		rc = apply_link_config(pi);
3301 	}
3302 done:
3303 	PORT_UNLOCK(pi);
3304 	end_synchronized_op(sc, 0);
3305 	return (rc);
3306 }
3307 
3308 /*
3309  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3310  * given speed.
3311  */
3312 static int
3313 port_mword(struct port_info *pi, uint32_t speed)
3314 {
3315 
3316 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3317 	MPASS(powerof2(speed));
3318 
3319 	switch(pi->port_type) {
3320 	case FW_PORT_TYPE_BT_SGMII:
3321 	case FW_PORT_TYPE_BT_XFI:
3322 	case FW_PORT_TYPE_BT_XAUI:
3323 		/* BaseT */
3324 		switch (speed) {
3325 		case FW_PORT_CAP32_SPEED_100M:
3326 			return (IFM_100_T);
3327 		case FW_PORT_CAP32_SPEED_1G:
3328 			return (IFM_1000_T);
3329 		case FW_PORT_CAP32_SPEED_10G:
3330 			return (IFM_10G_T);
3331 		}
3332 		break;
3333 	case FW_PORT_TYPE_KX4:
3334 		if (speed == FW_PORT_CAP32_SPEED_10G)
3335 			return (IFM_10G_KX4);
3336 		break;
3337 	case FW_PORT_TYPE_CX4:
3338 		if (speed == FW_PORT_CAP32_SPEED_10G)
3339 			return (IFM_10G_CX4);
3340 		break;
3341 	case FW_PORT_TYPE_KX:
3342 		if (speed == FW_PORT_CAP32_SPEED_1G)
3343 			return (IFM_1000_KX);
3344 		break;
3345 	case FW_PORT_TYPE_KR:
3346 	case FW_PORT_TYPE_BP_AP:
3347 	case FW_PORT_TYPE_BP4_AP:
3348 	case FW_PORT_TYPE_BP40_BA:
3349 	case FW_PORT_TYPE_KR4_100G:
3350 	case FW_PORT_TYPE_KR_SFP28:
3351 	case FW_PORT_TYPE_KR_XLAUI:
3352 		switch (speed) {
3353 		case FW_PORT_CAP32_SPEED_1G:
3354 			return (IFM_1000_KX);
3355 		case FW_PORT_CAP32_SPEED_10G:
3356 			return (IFM_10G_KR);
3357 		case FW_PORT_CAP32_SPEED_25G:
3358 			return (IFM_25G_KR);
3359 		case FW_PORT_CAP32_SPEED_40G:
3360 			return (IFM_40G_KR4);
3361 		case FW_PORT_CAP32_SPEED_50G:
3362 			return (IFM_50G_KR2);
3363 		case FW_PORT_CAP32_SPEED_100G:
3364 			return (IFM_100G_KR4);
3365 		}
3366 		break;
3367 	case FW_PORT_TYPE_FIBER_XFI:
3368 	case FW_PORT_TYPE_FIBER_XAUI:
3369 	case FW_PORT_TYPE_SFP:
3370 	case FW_PORT_TYPE_QSFP_10G:
3371 	case FW_PORT_TYPE_QSA:
3372 	case FW_PORT_TYPE_QSFP:
3373 	case FW_PORT_TYPE_CR4_QSFP:
3374 	case FW_PORT_TYPE_CR_QSFP:
3375 	case FW_PORT_TYPE_CR2_QSFP:
3376 	case FW_PORT_TYPE_SFP28:
3377 		/* Pluggable transceiver */
3378 		switch (pi->mod_type) {
3379 		case FW_PORT_MOD_TYPE_LR:
3380 			switch (speed) {
3381 			case FW_PORT_CAP32_SPEED_1G:
3382 				return (IFM_1000_LX);
3383 			case FW_PORT_CAP32_SPEED_10G:
3384 				return (IFM_10G_LR);
3385 			case FW_PORT_CAP32_SPEED_25G:
3386 				return (IFM_25G_LR);
3387 			case FW_PORT_CAP32_SPEED_40G:
3388 				return (IFM_40G_LR4);
3389 			case FW_PORT_CAP32_SPEED_50G:
3390 				return (IFM_50G_LR2);
3391 			case FW_PORT_CAP32_SPEED_100G:
3392 				return (IFM_100G_LR4);
3393 			}
3394 			break;
3395 		case FW_PORT_MOD_TYPE_SR:
3396 			switch (speed) {
3397 			case FW_PORT_CAP32_SPEED_1G:
3398 				return (IFM_1000_SX);
3399 			case FW_PORT_CAP32_SPEED_10G:
3400 				return (IFM_10G_SR);
3401 			case FW_PORT_CAP32_SPEED_25G:
3402 				return (IFM_25G_SR);
3403 			case FW_PORT_CAP32_SPEED_40G:
3404 				return (IFM_40G_SR4);
3405 			case FW_PORT_CAP32_SPEED_50G:
3406 				return (IFM_50G_SR2);
3407 			case FW_PORT_CAP32_SPEED_100G:
3408 				return (IFM_100G_SR4);
3409 			}
3410 			break;
3411 		case FW_PORT_MOD_TYPE_ER:
3412 			if (speed == FW_PORT_CAP32_SPEED_10G)
3413 				return (IFM_10G_ER);
3414 			break;
3415 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3416 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3417 			switch (speed) {
3418 			case FW_PORT_CAP32_SPEED_1G:
3419 				return (IFM_1000_CX);
3420 			case FW_PORT_CAP32_SPEED_10G:
3421 				return (IFM_10G_TWINAX);
3422 			case FW_PORT_CAP32_SPEED_25G:
3423 				return (IFM_25G_CR);
3424 			case FW_PORT_CAP32_SPEED_40G:
3425 				return (IFM_40G_CR4);
3426 			case FW_PORT_CAP32_SPEED_50G:
3427 				return (IFM_50G_CR2);
3428 			case FW_PORT_CAP32_SPEED_100G:
3429 				return (IFM_100G_CR4);
3430 			}
3431 			break;
3432 		case FW_PORT_MOD_TYPE_LRM:
3433 			if (speed == FW_PORT_CAP32_SPEED_10G)
3434 				return (IFM_10G_LRM);
3435 			break;
3436 		case FW_PORT_MOD_TYPE_NA:
3437 			MPASS(0);	/* Not pluggable? */
3438 			/* fall throough */
3439 		case FW_PORT_MOD_TYPE_ERROR:
3440 		case FW_PORT_MOD_TYPE_UNKNOWN:
3441 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3442 			break;
3443 		case FW_PORT_MOD_TYPE_NONE:
3444 			return (IFM_NONE);
3445 		}
3446 		break;
3447 	case FW_PORT_TYPE_NONE:
3448 		return (IFM_NONE);
3449 	}
3450 
3451 	return (IFM_UNKNOWN);
3452 }
3453 
3454 void
3455 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3456 {
3457 	struct vi_info *vi = if_getsoftc(ifp);
3458 	struct port_info *pi = vi->pi;
3459 	struct adapter *sc = pi->adapter;
3460 	struct link_config *lc = &pi->link_cfg;
3461 
3462 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4med") != 0)
3463 		return;
3464 	PORT_LOCK(pi);
3465 
3466 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3467 		/*
3468 		 * If all the interfaces are administratively down the firmware
3469 		 * does not report transceiver changes.  Refresh port info here
3470 		 * so that ifconfig displays accurate ifmedia at all times.
3471 		 * This is the only reason we have a synchronized op in this
3472 		 * function.  Just PORT_LOCK would have been enough otherwise.
3473 		 */
3474 		t4_update_port_info(pi);
3475 		build_medialist(pi);
3476 	}
3477 
3478 	/* ifm_status */
3479 	ifmr->ifm_status = IFM_AVALID;
3480 	if (lc->link_ok == false)
3481 		goto done;
3482 	ifmr->ifm_status |= IFM_ACTIVE;
3483 
3484 	/* ifm_active */
3485 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3486 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3487 	if (lc->fc & PAUSE_RX)
3488 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3489 	if (lc->fc & PAUSE_TX)
3490 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3491 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3492 done:
3493 	PORT_UNLOCK(pi);
3494 	end_synchronized_op(sc, 0);
3495 }
3496 
3497 static int
3498 vcxgbe_probe(device_t dev)
3499 {
3500 	char buf[128];
3501 	struct vi_info *vi = device_get_softc(dev);
3502 
3503 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3504 	    vi - vi->pi->vi);
3505 	device_set_desc_copy(dev, buf);
3506 
3507 	return (BUS_PROBE_DEFAULT);
3508 }
3509 
3510 static int
3511 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3512 {
3513 	int func, index, rc;
3514 	uint32_t param, val;
3515 
3516 	ASSERT_SYNCHRONIZED_OP(sc);
3517 
3518 	index = vi - pi->vi;
3519 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3520 	KASSERT(index < nitems(vi_mac_funcs),
3521 	    ("%s: VI %s doesn't have a MAC func", __func__,
3522 	    device_get_nameunit(vi->dev)));
3523 	func = vi_mac_funcs[index];
3524 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3525 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3526 	if (rc < 0) {
3527 		CH_ERR(vi, "failed to allocate virtual interface %d"
3528 		    "for port %d: %d\n", index, pi->port_id, -rc);
3529 		return (-rc);
3530 	}
3531 	vi->viid = rc;
3532 
3533 	if (vi->rss_size == 1) {
3534 		/*
3535 		 * This VI didn't get a slice of the RSS table.  Reduce the
3536 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3537 		 * configuration file (nvi, rssnvi for this PF) if this is a
3538 		 * problem.
3539 		 */
3540 		device_printf(vi->dev, "RSS table not available.\n");
3541 		vi->rss_base = 0xffff;
3542 
3543 		return (0);
3544 	}
3545 
3546 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3547 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3548 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3549 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3550 	if (rc)
3551 		vi->rss_base = 0xffff;
3552 	else {
3553 		MPASS((val >> 16) == vi->rss_size);
3554 		vi->rss_base = val & 0xffff;
3555 	}
3556 
3557 	return (0);
3558 }
3559 
3560 static int
3561 vcxgbe_attach(device_t dev)
3562 {
3563 	struct vi_info *vi;
3564 	struct port_info *pi;
3565 	struct adapter *sc;
3566 	int rc;
3567 
3568 	vi = device_get_softc(dev);
3569 	pi = vi->pi;
3570 	sc = pi->adapter;
3571 
3572 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3573 	if (rc)
3574 		return (rc);
3575 	rc = alloc_extra_vi(sc, pi, vi);
3576 	end_synchronized_op(sc, 0);
3577 	if (rc)
3578 		return (rc);
3579 
3580 	rc = cxgbe_vi_attach(dev, vi);
3581 	if (rc) {
3582 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3583 		return (rc);
3584 	}
3585 	return (0);
3586 }
3587 
3588 static int
3589 vcxgbe_detach(device_t dev)
3590 {
3591 	struct vi_info *vi;
3592 	struct adapter *sc;
3593 
3594 	vi = device_get_softc(dev);
3595 	sc = vi->adapter;
3596 
3597 	doom_vi(sc, vi);
3598 
3599 	cxgbe_vi_detach(vi);
3600 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3601 
3602 	end_synchronized_op(sc, 0);
3603 
3604 	return (0);
3605 }
3606 
3607 static struct callout fatal_callout;
3608 static struct taskqueue *reset_tq;
3609 
3610 static void
3611 delayed_panic(void *arg)
3612 {
3613 	struct adapter *sc = arg;
3614 
3615 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3616 }
3617 
3618 static void
3619 fatal_error_task(void *arg, int pending)
3620 {
3621 	struct adapter *sc = arg;
3622 	int rc;
3623 
3624 #ifdef TCP_OFFLOAD
3625 	t4_async_event(sc);
3626 #endif
3627 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3628 		dump_cim_regs(sc);
3629 		dump_cimla(sc);
3630 		dump_devlog(sc);
3631 	}
3632 
3633 	if (t4_reset_on_fatal_err) {
3634 		CH_ALERT(sc, "resetting on fatal error.\n");
3635 		rc = reset_adapter(sc);
3636 		if (rc == 0 && t4_panic_on_fatal_err) {
3637 			CH_ALERT(sc, "reset was successful, "
3638 			    "system will NOT panic.\n");
3639 			return;
3640 		}
3641 	}
3642 
3643 	if (t4_panic_on_fatal_err) {
3644 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3645 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3646 	}
3647 }
3648 
3649 void
3650 t4_fatal_err(struct adapter *sc, bool fw_error)
3651 {
3652 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3653 
3654 	stop_adapter(sc);
3655 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3656 		return;
3657 	if (fw_error) {
3658 		/*
3659 		 * We are here because of a firmware error/timeout and not
3660 		 * because of a hardware interrupt.  It is possible (although
3661 		 * not very likely) that an error interrupt was also raised but
3662 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3663 		 * main INT_CAUSE registers here to make sure we haven't missed
3664 		 * anything interesting.
3665 		 */
3666 		t4_slow_intr_handler(sc, verbose);
3667 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3668 	}
3669 	t4_report_fw_error(sc);
3670 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3671 	    device_get_nameunit(sc->dev), fw_error);
3672 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3673 }
3674 
3675 void
3676 t4_add_adapter(struct adapter *sc)
3677 {
3678 	sx_xlock(&t4_list_lock);
3679 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3680 	sx_xunlock(&t4_list_lock);
3681 }
3682 
3683 int
3684 t4_map_bars_0_and_4(struct adapter *sc)
3685 {
3686 	sc->regs_rid = PCIR_BAR(0);
3687 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3688 	    &sc->regs_rid, RF_ACTIVE);
3689 	if (sc->regs_res == NULL) {
3690 		device_printf(sc->dev, "cannot map registers.\n");
3691 		return (ENXIO);
3692 	}
3693 	sc->bt = rman_get_bustag(sc->regs_res);
3694 	sc->bh = rman_get_bushandle(sc->regs_res);
3695 	sc->mmio_len = rman_get_size(sc->regs_res);
3696 	setbit(&sc->doorbells, DOORBELL_KDB);
3697 
3698 	sc->msix_rid = PCIR_BAR(4);
3699 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3700 	    &sc->msix_rid, RF_ACTIVE);
3701 	if (sc->msix_res == NULL) {
3702 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3703 		return (ENXIO);
3704 	}
3705 
3706 	return (0);
3707 }
3708 
3709 int
3710 t4_map_bar_2(struct adapter *sc)
3711 {
3712 
3713 	/*
3714 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3715 	 * to map it if RDMA is disabled.
3716 	 */
3717 	if (is_t4(sc) && sc->rdmacaps == 0)
3718 		return (0);
3719 
3720 	sc->udbs_rid = PCIR_BAR(2);
3721 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3722 	    &sc->udbs_rid, RF_ACTIVE);
3723 	if (sc->udbs_res == NULL) {
3724 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3725 		return (ENXIO);
3726 	}
3727 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3728 
3729 	if (chip_id(sc) >= CHELSIO_T5) {
3730 		setbit(&sc->doorbells, DOORBELL_UDB);
3731 #if defined(__i386__) || defined(__amd64__)
3732 		if (t5_write_combine) {
3733 			int rc, mode;
3734 
3735 			/*
3736 			 * Enable write combining on BAR2.  This is the
3737 			 * userspace doorbell BAR and is split into 128B
3738 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3739 			 * with an egress queue.  The first 64B has the doorbell
3740 			 * and the second 64B can be used to submit a tx work
3741 			 * request with an implicit doorbell.
3742 			 */
3743 
3744 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3745 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3746 			if (rc == 0) {
3747 				clrbit(&sc->doorbells, DOORBELL_UDB);
3748 				setbit(&sc->doorbells, DOORBELL_WCWR);
3749 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3750 			} else {
3751 				device_printf(sc->dev,
3752 				    "couldn't enable write combining: %d\n",
3753 				    rc);
3754 			}
3755 
3756 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3757 			t4_write_reg(sc, A_SGE_STAT_CFG,
3758 			    V_STATSOURCE_T5(7) | mode);
3759 		}
3760 #endif
3761 	}
3762 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3763 
3764 	return (0);
3765 }
3766 
3767 struct memwin_init {
3768 	uint32_t base;
3769 	uint32_t aperture;
3770 };
3771 
3772 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3773 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3774 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3775 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3776 };
3777 
3778 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3779 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3780 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3781 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3782 };
3783 
3784 static void
3785 setup_memwin(struct adapter *sc)
3786 {
3787 	const struct memwin_init *mw_init;
3788 	struct memwin *mw;
3789 	int i;
3790 	uint32_t bar0;
3791 
3792 	if (is_t4(sc)) {
3793 		/*
3794 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3795 		 * mechanism.  Works from within PCI passthrough environments
3796 		 * too, where rman_get_start() can return a different value.  We
3797 		 * need to program the T4 memory window decoders with the actual
3798 		 * addresses that will be coming across the PCIe link.
3799 		 */
3800 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3801 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3802 
3803 		mw_init = &t4_memwin[0];
3804 	} else {
3805 		/* T5+ use the relative offset inside the PCIe BAR */
3806 		bar0 = 0;
3807 
3808 		mw_init = &t5_memwin[0];
3809 	}
3810 
3811 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3812 		if (!rw_initialized(&mw->mw_lock)) {
3813 			rw_init(&mw->mw_lock, "memory window access");
3814 			mw->mw_base = mw_init->base;
3815 			mw->mw_aperture = mw_init->aperture;
3816 			mw->mw_curpos = 0;
3817 		}
3818 		t4_write_reg(sc,
3819 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3820 		    (mw->mw_base + bar0) | V_BIR(0) |
3821 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3822 		rw_wlock(&mw->mw_lock);
3823 		position_memwin(sc, i, mw->mw_curpos);
3824 		rw_wunlock(&mw->mw_lock);
3825 	}
3826 
3827 	/* flush */
3828 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3829 }
3830 
3831 /*
3832  * Positions the memory window at the given address in the card's address space.
3833  * There are some alignment requirements and the actual position may be at an
3834  * address prior to the requested address.  mw->mw_curpos always has the actual
3835  * position of the window.
3836  */
3837 static void
3838 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3839 {
3840 	struct memwin *mw;
3841 	uint32_t pf;
3842 	uint32_t reg;
3843 
3844 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3845 	mw = &sc->memwin[idx];
3846 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3847 
3848 	if (is_t4(sc)) {
3849 		pf = 0;
3850 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3851 	} else {
3852 		pf = V_PFNUM(sc->pf);
3853 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3854 	}
3855 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3856 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3857 	t4_read_reg(sc, reg);	/* flush */
3858 }
3859 
3860 int
3861 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3862     int len, int rw)
3863 {
3864 	struct memwin *mw;
3865 	uint32_t mw_end, v;
3866 
3867 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3868 
3869 	/* Memory can only be accessed in naturally aligned 4 byte units */
3870 	if (addr & 3 || len & 3 || len <= 0)
3871 		return (EINVAL);
3872 
3873 	mw = &sc->memwin[idx];
3874 	while (len > 0) {
3875 		rw_rlock(&mw->mw_lock);
3876 		mw_end = mw->mw_curpos + mw->mw_aperture;
3877 		if (addr >= mw_end || addr < mw->mw_curpos) {
3878 			/* Will need to reposition the window */
3879 			if (!rw_try_upgrade(&mw->mw_lock)) {
3880 				rw_runlock(&mw->mw_lock);
3881 				rw_wlock(&mw->mw_lock);
3882 			}
3883 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3884 			position_memwin(sc, idx, addr);
3885 			rw_downgrade(&mw->mw_lock);
3886 			mw_end = mw->mw_curpos + mw->mw_aperture;
3887 		}
3888 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3889 		while (addr < mw_end && len > 0) {
3890 			if (rw == 0) {
3891 				v = t4_read_reg(sc, mw->mw_base + addr -
3892 				    mw->mw_curpos);
3893 				*val++ = le32toh(v);
3894 			} else {
3895 				v = *val++;
3896 				t4_write_reg(sc, mw->mw_base + addr -
3897 				    mw->mw_curpos, htole32(v));
3898 			}
3899 			addr += 4;
3900 			len -= 4;
3901 		}
3902 		rw_runlock(&mw->mw_lock);
3903 	}
3904 
3905 	return (0);
3906 }
3907 
3908 static void
3909 t4_init_atid_table(struct adapter *sc)
3910 {
3911 	struct tid_info *t;
3912 	int i;
3913 
3914 	t = &sc->tids;
3915 	if (t->natids == 0)
3916 		return;
3917 
3918 	MPASS(t->atid_tab == NULL);
3919 
3920 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3921 	    M_ZERO | M_WAITOK);
3922 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3923 	t->afree = t->atid_tab;
3924 	t->atids_in_use = 0;
3925 	for (i = 1; i < t->natids; i++)
3926 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3927 	t->atid_tab[t->natids - 1].next = NULL;
3928 }
3929 
3930 static void
3931 t4_free_atid_table(struct adapter *sc)
3932 {
3933 	struct tid_info *t;
3934 
3935 	t = &sc->tids;
3936 
3937 	KASSERT(t->atids_in_use == 0,
3938 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3939 
3940 	if (mtx_initialized(&t->atid_lock))
3941 		mtx_destroy(&t->atid_lock);
3942 	free(t->atid_tab, M_CXGBE);
3943 	t->atid_tab = NULL;
3944 }
3945 
3946 int
3947 alloc_atid(struct adapter *sc, void *ctx)
3948 {
3949 	struct tid_info *t = &sc->tids;
3950 	int atid = -1;
3951 
3952 	mtx_lock(&t->atid_lock);
3953 	if (t->afree) {
3954 		union aopen_entry *p = t->afree;
3955 
3956 		atid = p - t->atid_tab;
3957 		MPASS(atid <= M_TID_TID);
3958 		t->afree = p->next;
3959 		p->data = ctx;
3960 		t->atids_in_use++;
3961 	}
3962 	mtx_unlock(&t->atid_lock);
3963 	return (atid);
3964 }
3965 
3966 void *
3967 lookup_atid(struct adapter *sc, int atid)
3968 {
3969 	struct tid_info *t = &sc->tids;
3970 
3971 	return (t->atid_tab[atid].data);
3972 }
3973 
3974 void
3975 free_atid(struct adapter *sc, int atid)
3976 {
3977 	struct tid_info *t = &sc->tids;
3978 	union aopen_entry *p = &t->atid_tab[atid];
3979 
3980 	mtx_lock(&t->atid_lock);
3981 	p->next = t->afree;
3982 	t->afree = p;
3983 	t->atids_in_use--;
3984 	mtx_unlock(&t->atid_lock);
3985 }
3986 
3987 static void
3988 queue_tid_release(struct adapter *sc, int tid)
3989 {
3990 
3991 	CXGBE_UNIMPLEMENTED("deferred tid release");
3992 }
3993 
3994 void
3995 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
3996 {
3997 	struct wrqe *wr;
3998 	struct cpl_tid_release *req;
3999 
4000 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4001 	if (wr == NULL) {
4002 		queue_tid_release(sc, tid);	/* defer */
4003 		return;
4004 	}
4005 	req = wrtod(wr);
4006 
4007 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4008 
4009 	t4_wrq_tx(sc, wr);
4010 }
4011 
4012 static int
4013 t4_range_cmp(const void *a, const void *b)
4014 {
4015 	return ((const struct t4_range *)a)->start -
4016 	       ((const struct t4_range *)b)->start;
4017 }
4018 
4019 /*
4020  * Verify that the memory range specified by the addr/len pair is valid within
4021  * the card's address space.
4022  */
4023 static int
4024 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4025 {
4026 	struct t4_range mem_ranges[4], *r, *next;
4027 	uint32_t em, addr_len;
4028 	int i, n, remaining;
4029 
4030 	/* Memory can only be accessed in naturally aligned 4 byte units */
4031 	if (addr & 3 || len & 3 || len == 0)
4032 		return (EINVAL);
4033 
4034 	/* Enabled memories */
4035 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4036 
4037 	r = &mem_ranges[0];
4038 	n = 0;
4039 	bzero(r, sizeof(mem_ranges));
4040 	if (em & F_EDRAM0_ENABLE) {
4041 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4042 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4043 		if (r->size > 0) {
4044 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4045 			if (addr >= r->start &&
4046 			    addr + len <= r->start + r->size)
4047 				return (0);
4048 			r++;
4049 			n++;
4050 		}
4051 	}
4052 	if (em & F_EDRAM1_ENABLE) {
4053 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4054 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4055 		if (r->size > 0) {
4056 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4057 			if (addr >= r->start &&
4058 			    addr + len <= r->start + r->size)
4059 				return (0);
4060 			r++;
4061 			n++;
4062 		}
4063 	}
4064 	if (em & F_EXT_MEM_ENABLE) {
4065 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4066 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4067 		if (r->size > 0) {
4068 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4069 			if (addr >= r->start &&
4070 			    addr + len <= r->start + r->size)
4071 				return (0);
4072 			r++;
4073 			n++;
4074 		}
4075 	}
4076 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4077 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4078 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4079 		if (r->size > 0) {
4080 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4081 			if (addr >= r->start &&
4082 			    addr + len <= r->start + r->size)
4083 				return (0);
4084 			r++;
4085 			n++;
4086 		}
4087 	}
4088 	MPASS(n <= nitems(mem_ranges));
4089 
4090 	if (n > 1) {
4091 		/* Sort and merge the ranges. */
4092 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4093 
4094 		/* Start from index 0 and examine the next n - 1 entries. */
4095 		r = &mem_ranges[0];
4096 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4097 
4098 			MPASS(r->size > 0);	/* r is a valid entry. */
4099 			next = r + 1;
4100 			MPASS(next->size > 0);	/* and so is the next one. */
4101 
4102 			while (r->start + r->size >= next->start) {
4103 				/* Merge the next one into the current entry. */
4104 				r->size = max(r->start + r->size,
4105 				    next->start + next->size) - r->start;
4106 				n--;	/* One fewer entry in total. */
4107 				if (--remaining == 0)
4108 					goto done;	/* short circuit */
4109 				next++;
4110 			}
4111 			if (next != r + 1) {
4112 				/*
4113 				 * Some entries were merged into r and next
4114 				 * points to the first valid entry that couldn't
4115 				 * be merged.
4116 				 */
4117 				MPASS(next->size > 0);	/* must be valid */
4118 				memcpy(r + 1, next, remaining * sizeof(*r));
4119 #ifdef INVARIANTS
4120 				/*
4121 				 * This so that the foo->size assertion in the
4122 				 * next iteration of the loop do the right
4123 				 * thing for entries that were pulled up and are
4124 				 * no longer valid.
4125 				 */
4126 				MPASS(n < nitems(mem_ranges));
4127 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4128 				    sizeof(struct t4_range));
4129 #endif
4130 			}
4131 		}
4132 done:
4133 		/* Done merging the ranges. */
4134 		MPASS(n > 0);
4135 		r = &mem_ranges[0];
4136 		for (i = 0; i < n; i++, r++) {
4137 			if (addr >= r->start &&
4138 			    addr + len <= r->start + r->size)
4139 				return (0);
4140 		}
4141 	}
4142 
4143 	return (EFAULT);
4144 }
4145 
4146 static int
4147 fwmtype_to_hwmtype(int mtype)
4148 {
4149 
4150 	switch (mtype) {
4151 	case FW_MEMTYPE_EDC0:
4152 		return (MEM_EDC0);
4153 	case FW_MEMTYPE_EDC1:
4154 		return (MEM_EDC1);
4155 	case FW_MEMTYPE_EXTMEM:
4156 		return (MEM_MC0);
4157 	case FW_MEMTYPE_EXTMEM1:
4158 		return (MEM_MC1);
4159 	default:
4160 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4161 	}
4162 }
4163 
4164 /*
4165  * Verify that the memory range specified by the memtype/offset/len pair is
4166  * valid and lies entirely within the memtype specified.  The global address of
4167  * the start of the range is returned in addr.
4168  */
4169 static int
4170 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4171     uint32_t *addr)
4172 {
4173 	uint32_t em, addr_len, maddr;
4174 
4175 	/* Memory can only be accessed in naturally aligned 4 byte units */
4176 	if (off & 3 || len & 3 || len == 0)
4177 		return (EINVAL);
4178 
4179 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4180 	switch (fwmtype_to_hwmtype(mtype)) {
4181 	case MEM_EDC0:
4182 		if (!(em & F_EDRAM0_ENABLE))
4183 			return (EINVAL);
4184 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4185 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4186 		break;
4187 	case MEM_EDC1:
4188 		if (!(em & F_EDRAM1_ENABLE))
4189 			return (EINVAL);
4190 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4191 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4192 		break;
4193 	case MEM_MC:
4194 		if (!(em & F_EXT_MEM_ENABLE))
4195 			return (EINVAL);
4196 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4197 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4198 		break;
4199 	case MEM_MC1:
4200 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4201 			return (EINVAL);
4202 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4203 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4204 		break;
4205 	default:
4206 		return (EINVAL);
4207 	}
4208 
4209 	*addr = maddr + off;	/* global address */
4210 	return (validate_mem_range(sc, *addr, len));
4211 }
4212 
4213 static int
4214 fixup_devlog_params(struct adapter *sc)
4215 {
4216 	struct devlog_params *dparams = &sc->params.devlog;
4217 	int rc;
4218 
4219 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4220 	    dparams->size, &dparams->addr);
4221 
4222 	return (rc);
4223 }
4224 
4225 static void
4226 update_nirq(struct intrs_and_queues *iaq, int nports)
4227 {
4228 
4229 	iaq->nirq = T4_EXTRA_INTR;
4230 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4231 	iaq->nirq += nports * iaq->nofldrxq;
4232 	iaq->nirq += nports * (iaq->num_vis - 1) *
4233 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4234 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4235 }
4236 
4237 /*
4238  * Adjust requirements to fit the number of interrupts available.
4239  */
4240 static void
4241 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4242     int navail)
4243 {
4244 	int old_nirq;
4245 	const int nports = sc->params.nports;
4246 
4247 	MPASS(nports > 0);
4248 	MPASS(navail > 0);
4249 
4250 	bzero(iaq, sizeof(*iaq));
4251 	iaq->intr_type = itype;
4252 	iaq->num_vis = t4_num_vis;
4253 	iaq->ntxq = t4_ntxq;
4254 	iaq->ntxq_vi = t4_ntxq_vi;
4255 	iaq->nrxq = t4_nrxq;
4256 	iaq->nrxq_vi = t4_nrxq_vi;
4257 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4258 	if (is_offload(sc) || is_ethoffload(sc)) {
4259 		iaq->nofldtxq = t4_nofldtxq;
4260 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4261 	}
4262 #endif
4263 #ifdef TCP_OFFLOAD
4264 	if (is_offload(sc)) {
4265 		iaq->nofldrxq = t4_nofldrxq;
4266 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4267 	}
4268 #endif
4269 #ifdef DEV_NETMAP
4270 	if (t4_native_netmap & NN_MAIN_VI) {
4271 		iaq->nnmtxq = t4_nnmtxq;
4272 		iaq->nnmrxq = t4_nnmrxq;
4273 	}
4274 	if (t4_native_netmap & NN_EXTRA_VI) {
4275 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4276 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4277 	}
4278 #endif
4279 
4280 	update_nirq(iaq, nports);
4281 	if (iaq->nirq <= navail &&
4282 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4283 		/*
4284 		 * This is the normal case -- there are enough interrupts for
4285 		 * everything.
4286 		 */
4287 		goto done;
4288 	}
4289 
4290 	/*
4291 	 * If extra VIs have been configured try reducing their count and see if
4292 	 * that works.
4293 	 */
4294 	while (iaq->num_vis > 1) {
4295 		iaq->num_vis--;
4296 		update_nirq(iaq, nports);
4297 		if (iaq->nirq <= navail &&
4298 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4299 			device_printf(sc->dev, "virtual interfaces per port "
4300 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4301 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4302 			    "itype %d, navail %u, nirq %d.\n",
4303 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4304 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4305 			    itype, navail, iaq->nirq);
4306 			goto done;
4307 		}
4308 	}
4309 
4310 	/*
4311 	 * Extra VIs will not be created.  Log a message if they were requested.
4312 	 */
4313 	MPASS(iaq->num_vis == 1);
4314 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4315 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4316 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4317 	if (iaq->num_vis != t4_num_vis) {
4318 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4319 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4320 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4321 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4322 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4323 	}
4324 
4325 	/*
4326 	 * Keep reducing the number of NIC rx queues to the next lower power of
4327 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4328 	 * if that works.
4329 	 */
4330 	do {
4331 		if (iaq->nrxq > 1) {
4332 			do {
4333 				iaq->nrxq--;
4334 			} while (!powerof2(iaq->nrxq));
4335 			if (iaq->nnmrxq > iaq->nrxq)
4336 				iaq->nnmrxq = iaq->nrxq;
4337 		}
4338 		if (iaq->nofldrxq > 1)
4339 			iaq->nofldrxq >>= 1;
4340 
4341 		old_nirq = iaq->nirq;
4342 		update_nirq(iaq, nports);
4343 		if (iaq->nirq <= navail &&
4344 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4345 			device_printf(sc->dev, "running with reduced number of "
4346 			    "rx queues because of shortage of interrupts.  "
4347 			    "nrxq=%u, nofldrxq=%u.  "
4348 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4349 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4350 			goto done;
4351 		}
4352 	} while (old_nirq != iaq->nirq);
4353 
4354 	/* One interrupt for everything.  Ugh. */
4355 	device_printf(sc->dev, "running with minimal number of queues.  "
4356 	    "itype %d, navail %u.\n", itype, navail);
4357 	iaq->nirq = 1;
4358 	iaq->nrxq = 1;
4359 	iaq->ntxq = 1;
4360 	if (iaq->nofldrxq > 0) {
4361 		iaq->nofldrxq = 1;
4362 		iaq->nofldtxq = 1;
4363 	}
4364 	iaq->nnmtxq = 0;
4365 	iaq->nnmrxq = 0;
4366 done:
4367 	MPASS(iaq->num_vis > 0);
4368 	if (iaq->num_vis > 1) {
4369 		MPASS(iaq->nrxq_vi > 0);
4370 		MPASS(iaq->ntxq_vi > 0);
4371 	}
4372 	MPASS(iaq->nirq > 0);
4373 	MPASS(iaq->nrxq > 0);
4374 	MPASS(iaq->ntxq > 0);
4375 	if (itype == INTR_MSI) {
4376 		MPASS(powerof2(iaq->nirq));
4377 	}
4378 }
4379 
4380 static int
4381 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4382 {
4383 	int rc, itype, navail, nalloc;
4384 
4385 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4386 
4387 		if ((itype & t4_intr_types) == 0)
4388 			continue;	/* not allowed */
4389 
4390 		if (itype == INTR_MSIX)
4391 			navail = pci_msix_count(sc->dev);
4392 		else if (itype == INTR_MSI)
4393 			navail = pci_msi_count(sc->dev);
4394 		else
4395 			navail = 1;
4396 restart:
4397 		if (navail == 0)
4398 			continue;
4399 
4400 		calculate_iaq(sc, iaq, itype, navail);
4401 		nalloc = iaq->nirq;
4402 		rc = 0;
4403 		if (itype == INTR_MSIX)
4404 			rc = pci_alloc_msix(sc->dev, &nalloc);
4405 		else if (itype == INTR_MSI)
4406 			rc = pci_alloc_msi(sc->dev, &nalloc);
4407 
4408 		if (rc == 0 && nalloc > 0) {
4409 			if (nalloc == iaq->nirq)
4410 				return (0);
4411 
4412 			/*
4413 			 * Didn't get the number requested.  Use whatever number
4414 			 * the kernel is willing to allocate.
4415 			 */
4416 			device_printf(sc->dev, "fewer vectors than requested, "
4417 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4418 			    itype, iaq->nirq, nalloc);
4419 			pci_release_msi(sc->dev);
4420 			navail = nalloc;
4421 			goto restart;
4422 		}
4423 
4424 		device_printf(sc->dev,
4425 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4426 		    itype, rc, iaq->nirq, nalloc);
4427 	}
4428 
4429 	device_printf(sc->dev,
4430 	    "failed to find a usable interrupt type.  "
4431 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4432 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4433 
4434 	return (ENXIO);
4435 }
4436 
4437 #define FW_VERSION(chip) ( \
4438     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4439     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4440     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4441     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4442 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4443 
4444 /* Just enough of fw_hdr to cover all version info. */
4445 struct fw_h {
4446 	__u8	ver;
4447 	__u8	chip;
4448 	__be16	len512;
4449 	__be32	fw_ver;
4450 	__be32	tp_microcode_ver;
4451 	__u8	intfver_nic;
4452 	__u8	intfver_vnic;
4453 	__u8	intfver_ofld;
4454 	__u8	intfver_ri;
4455 	__u8	intfver_iscsipdu;
4456 	__u8	intfver_iscsi;
4457 	__u8	intfver_fcoepdu;
4458 	__u8	intfver_fcoe;
4459 };
4460 /* Spot check a couple of fields. */
4461 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4462 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4463 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4464 
4465 struct fw_info {
4466 	uint8_t chip;
4467 	char *kld_name;
4468 	char *fw_mod_name;
4469 	struct fw_h fw_h;
4470 } fw_info[] = {
4471 	{
4472 		.chip = CHELSIO_T4,
4473 		.kld_name = "t4fw_cfg",
4474 		.fw_mod_name = "t4fw",
4475 		.fw_h = {
4476 			.chip = FW_HDR_CHIP_T4,
4477 			.fw_ver = htobe32(FW_VERSION(T4)),
4478 			.intfver_nic = FW_INTFVER(T4, NIC),
4479 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4480 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4481 			.intfver_ri = FW_INTFVER(T4, RI),
4482 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4483 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4484 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4485 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4486 		},
4487 	}, {
4488 		.chip = CHELSIO_T5,
4489 		.kld_name = "t5fw_cfg",
4490 		.fw_mod_name = "t5fw",
4491 		.fw_h = {
4492 			.chip = FW_HDR_CHIP_T5,
4493 			.fw_ver = htobe32(FW_VERSION(T5)),
4494 			.intfver_nic = FW_INTFVER(T5, NIC),
4495 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4496 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4497 			.intfver_ri = FW_INTFVER(T5, RI),
4498 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4499 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4500 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4501 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4502 		},
4503 	}, {
4504 		.chip = CHELSIO_T6,
4505 		.kld_name = "t6fw_cfg",
4506 		.fw_mod_name = "t6fw",
4507 		.fw_h = {
4508 			.chip = FW_HDR_CHIP_T6,
4509 			.fw_ver = htobe32(FW_VERSION(T6)),
4510 			.intfver_nic = FW_INTFVER(T6, NIC),
4511 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4512 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4513 			.intfver_ri = FW_INTFVER(T6, RI),
4514 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4515 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4516 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4517 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4518 		},
4519 	}
4520 };
4521 
4522 static struct fw_info *
4523 find_fw_info(int chip)
4524 {
4525 	int i;
4526 
4527 	for (i = 0; i < nitems(fw_info); i++) {
4528 		if (fw_info[i].chip == chip)
4529 			return (&fw_info[i]);
4530 	}
4531 	return (NULL);
4532 }
4533 
4534 /*
4535  * Is the given firmware API compatible with the one the driver was compiled
4536  * with?
4537  */
4538 static int
4539 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4540 {
4541 
4542 	/* short circuit if it's the exact same firmware version */
4543 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4544 		return (1);
4545 
4546 	/*
4547 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4548 	 * features that are supported in the driver.
4549 	 */
4550 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4551 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4552 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4553 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4554 		return (1);
4555 #undef SAME_INTF
4556 
4557 	return (0);
4558 }
4559 
4560 static int
4561 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4562     const struct firmware **fw)
4563 {
4564 	struct fw_info *fw_info;
4565 
4566 	*dcfg = NULL;
4567 	if (fw != NULL)
4568 		*fw = NULL;
4569 
4570 	fw_info = find_fw_info(chip_id(sc));
4571 	if (fw_info == NULL) {
4572 		device_printf(sc->dev,
4573 		    "unable to look up firmware information for chip %d.\n",
4574 		    chip_id(sc));
4575 		return (EINVAL);
4576 	}
4577 
4578 	*dcfg = firmware_get(fw_info->kld_name);
4579 	if (*dcfg != NULL) {
4580 		if (fw != NULL)
4581 			*fw = firmware_get(fw_info->fw_mod_name);
4582 		return (0);
4583 	}
4584 
4585 	return (ENOENT);
4586 }
4587 
4588 static void
4589 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4590     const struct firmware *fw)
4591 {
4592 
4593 	if (fw != NULL)
4594 		firmware_put(fw, FIRMWARE_UNLOAD);
4595 	if (dcfg != NULL)
4596 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4597 }
4598 
4599 /*
4600  * Return values:
4601  * 0 means no firmware install attempted.
4602  * ERESTART means a firmware install was attempted and was successful.
4603  * +ve errno means a firmware install was attempted but failed.
4604  */
4605 static int
4606 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4607     const struct fw_h *drv_fw, const char *reason, int *already)
4608 {
4609 	const struct firmware *cfg, *fw;
4610 	const uint32_t c = be32toh(card_fw->fw_ver);
4611 	uint32_t d, k;
4612 	int rc, fw_install;
4613 	struct fw_h bundled_fw;
4614 	bool load_attempted;
4615 
4616 	cfg = fw = NULL;
4617 	load_attempted = false;
4618 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4619 
4620 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4621 	if (t4_fw_install < 0) {
4622 		rc = load_fw_module(sc, &cfg, &fw);
4623 		if (rc != 0 || fw == NULL) {
4624 			device_printf(sc->dev,
4625 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4626 			    " will use compiled-in firmware version for"
4627 			    "hw.cxgbe.fw_install checks.\n",
4628 			    rc, cfg, fw);
4629 		} else {
4630 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4631 		}
4632 		load_attempted = true;
4633 	}
4634 	d = be32toh(bundled_fw.fw_ver);
4635 
4636 	if (reason != NULL)
4637 		goto install;
4638 
4639 	if ((sc->flags & FW_OK) == 0) {
4640 
4641 		if (c == 0xffffffff) {
4642 			reason = "missing";
4643 			goto install;
4644 		}
4645 
4646 		rc = 0;
4647 		goto done;
4648 	}
4649 
4650 	if (!fw_compatible(card_fw, &bundled_fw)) {
4651 		reason = "incompatible or unusable";
4652 		goto install;
4653 	}
4654 
4655 	if (d > c) {
4656 		reason = "older than the version bundled with this driver";
4657 		goto install;
4658 	}
4659 
4660 	if (fw_install == 2 && d != c) {
4661 		reason = "different than the version bundled with this driver";
4662 		goto install;
4663 	}
4664 
4665 	/* No reason to do anything to the firmware already on the card. */
4666 	rc = 0;
4667 	goto done;
4668 
4669 install:
4670 	rc = 0;
4671 	if ((*already)++)
4672 		goto done;
4673 
4674 	if (fw_install == 0) {
4675 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4676 		    "but the driver is prohibited from installing a firmware "
4677 		    "on the card.\n",
4678 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4679 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4680 
4681 		goto done;
4682 	}
4683 
4684 	/*
4685 	 * We'll attempt to install a firmware.  Load the module first (if it
4686 	 * hasn't been loaded already).
4687 	 */
4688 	if (!load_attempted) {
4689 		rc = load_fw_module(sc, &cfg, &fw);
4690 		if (rc != 0 || fw == NULL) {
4691 			device_printf(sc->dev,
4692 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4693 			    rc, cfg, fw);
4694 			/* carry on */
4695 		}
4696 	}
4697 	if (fw == NULL) {
4698 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4699 		    "but the driver cannot take corrective action because it "
4700 		    "is unable to load the firmware module.\n",
4701 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4702 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4703 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4704 		goto done;
4705 	}
4706 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4707 	if (k != d) {
4708 		MPASS(t4_fw_install > 0);
4709 		device_printf(sc->dev,
4710 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4711 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4712 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4713 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4714 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4715 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4716 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4717 		goto done;
4718 	}
4719 
4720 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4721 	    "installing firmware %u.%u.%u.%u on card.\n",
4722 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4723 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4724 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4725 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4726 
4727 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4728 	if (rc != 0) {
4729 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4730 	} else {
4731 		/* Installed successfully, update the cached header too. */
4732 		rc = ERESTART;
4733 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4734 	}
4735 done:
4736 	unload_fw_module(sc, cfg, fw);
4737 
4738 	return (rc);
4739 }
4740 
4741 /*
4742  * Establish contact with the firmware and attempt to become the master driver.
4743  *
4744  * A firmware will be installed to the card if needed (if the driver is allowed
4745  * to do so).
4746  */
4747 static int
4748 contact_firmware(struct adapter *sc)
4749 {
4750 	int rc, already = 0;
4751 	enum dev_state state;
4752 	struct fw_info *fw_info;
4753 	struct fw_hdr *card_fw;		/* fw on the card */
4754 	const struct fw_h *drv_fw;
4755 
4756 	fw_info = find_fw_info(chip_id(sc));
4757 	if (fw_info == NULL) {
4758 		device_printf(sc->dev,
4759 		    "unable to look up firmware information for chip %d.\n",
4760 		    chip_id(sc));
4761 		return (EINVAL);
4762 	}
4763 	drv_fw = &fw_info->fw_h;
4764 
4765 	/* Read the header of the firmware on the card */
4766 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4767 restart:
4768 	rc = -t4_get_fw_hdr(sc, card_fw);
4769 	if (rc != 0) {
4770 		device_printf(sc->dev,
4771 		    "unable to read firmware header from card's flash: %d\n",
4772 		    rc);
4773 		goto done;
4774 	}
4775 
4776 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4777 	    &already);
4778 	if (rc == ERESTART)
4779 		goto restart;
4780 	if (rc != 0)
4781 		goto done;
4782 
4783 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4784 	if (rc < 0 || state == DEV_STATE_ERR) {
4785 		rc = -rc;
4786 		device_printf(sc->dev,
4787 		    "failed to connect to the firmware: %d, %d.  "
4788 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4789 #if 0
4790 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4791 		    "not responding properly to HELLO", &already) == ERESTART)
4792 			goto restart;
4793 #endif
4794 		goto done;
4795 	}
4796 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4797 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4798 
4799 	if (rc == sc->pf) {
4800 		sc->flags |= MASTER_PF;
4801 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4802 		    NULL, &already);
4803 		if (rc == ERESTART)
4804 			rc = 0;
4805 		else if (rc != 0)
4806 			goto done;
4807 	} else if (state == DEV_STATE_UNINIT) {
4808 		/*
4809 		 * We didn't get to be the master so we definitely won't be
4810 		 * configuring the chip.  It's a bug if someone else hasn't
4811 		 * configured it already.
4812 		 */
4813 		device_printf(sc->dev, "couldn't be master(%d), "
4814 		    "device not already initialized either(%d).  "
4815 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4816 		rc = EPROTO;
4817 		goto done;
4818 	} else {
4819 		/*
4820 		 * Some other PF is the master and has configured the chip.
4821 		 * This is allowed but untested.
4822 		 */
4823 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4824 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4825 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4826 		sc->cfcsum = 0;
4827 		rc = 0;
4828 	}
4829 done:
4830 	if (rc != 0 && sc->flags & FW_OK) {
4831 		t4_fw_bye(sc, sc->mbox);
4832 		sc->flags &= ~FW_OK;
4833 	}
4834 	free(card_fw, M_CXGBE);
4835 	return (rc);
4836 }
4837 
4838 static int
4839 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4840     uint32_t mtype, uint32_t moff)
4841 {
4842 	struct fw_info *fw_info;
4843 	const struct firmware *dcfg, *rcfg = NULL;
4844 	const uint32_t *cfdata;
4845 	uint32_t cflen, addr;
4846 	int rc;
4847 
4848 	load_fw_module(sc, &dcfg, NULL);
4849 
4850 	/* Card specific interpretation of "default". */
4851 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4852 		if (pci_get_device(sc->dev) == 0x440a)
4853 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4854 		if (is_fpga(sc))
4855 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4856 	}
4857 
4858 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4859 		if (dcfg == NULL) {
4860 			device_printf(sc->dev,
4861 			    "KLD with default config is not available.\n");
4862 			rc = ENOENT;
4863 			goto done;
4864 		}
4865 		cfdata = dcfg->data;
4866 		cflen = dcfg->datasize & ~3;
4867 	} else {
4868 		char s[32];
4869 
4870 		fw_info = find_fw_info(chip_id(sc));
4871 		if (fw_info == NULL) {
4872 			device_printf(sc->dev,
4873 			    "unable to look up firmware information for chip %d.\n",
4874 			    chip_id(sc));
4875 			rc = EINVAL;
4876 			goto done;
4877 		}
4878 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4879 
4880 		rcfg = firmware_get(s);
4881 		if (rcfg == NULL) {
4882 			device_printf(sc->dev,
4883 			    "unable to load module \"%s\" for configuration "
4884 			    "profile \"%s\".\n", s, cfg_file);
4885 			rc = ENOENT;
4886 			goto done;
4887 		}
4888 		cfdata = rcfg->data;
4889 		cflen = rcfg->datasize & ~3;
4890 	}
4891 
4892 	if (cflen > FLASH_CFG_MAX_SIZE) {
4893 		device_printf(sc->dev,
4894 		    "config file too long (%d, max allowed is %d).\n",
4895 		    cflen, FLASH_CFG_MAX_SIZE);
4896 		rc = EINVAL;
4897 		goto done;
4898 	}
4899 
4900 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4901 	if (rc != 0) {
4902 		device_printf(sc->dev,
4903 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4904 		    __func__, mtype, moff, cflen, rc);
4905 		rc = EINVAL;
4906 		goto done;
4907 	}
4908 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4909 done:
4910 	if (rcfg != NULL)
4911 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4912 	unload_fw_module(sc, dcfg, NULL);
4913 	return (rc);
4914 }
4915 
4916 struct caps_allowed {
4917 	uint16_t nbmcaps;
4918 	uint16_t linkcaps;
4919 	uint16_t switchcaps;
4920 	uint16_t niccaps;
4921 	uint16_t toecaps;
4922 	uint16_t rdmacaps;
4923 	uint16_t cryptocaps;
4924 	uint16_t iscsicaps;
4925 	uint16_t fcoecaps;
4926 };
4927 
4928 #define FW_PARAM_DEV(param) \
4929 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4930 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4931 #define FW_PARAM_PFVF(param) \
4932 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4933 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4934 
4935 /*
4936  * Provide a configuration profile to the firmware and have it initialize the
4937  * chip accordingly.  This may involve uploading a configuration file to the
4938  * card.
4939  */
4940 static int
4941 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4942     const struct caps_allowed *caps_allowed)
4943 {
4944 	int rc;
4945 	struct fw_caps_config_cmd caps;
4946 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4947 
4948 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4949 	if (rc != 0) {
4950 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4951 		return (rc);
4952 	}
4953 
4954 	bzero(&caps, sizeof(caps));
4955 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4956 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4957 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4958 		mtype = 0;
4959 		moff = 0;
4960 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4961 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4962 		mtype = FW_MEMTYPE_FLASH;
4963 		moff = t4_flash_cfg_addr(sc);
4964 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4965 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4966 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4967 		    FW_LEN16(caps));
4968 	} else {
4969 		/*
4970 		 * Ask the firmware where it wants us to upload the config file.
4971 		 */
4972 		param = FW_PARAM_DEV(CF);
4973 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4974 		if (rc != 0) {
4975 			/* No support for config file?  Shouldn't happen. */
4976 			device_printf(sc->dev,
4977 			    "failed to query config file location: %d.\n", rc);
4978 			goto done;
4979 		}
4980 		mtype = G_FW_PARAMS_PARAM_Y(val);
4981 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4982 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4983 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4984 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4985 		    FW_LEN16(caps));
4986 
4987 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4988 		if (rc != 0) {
4989 			device_printf(sc->dev,
4990 			    "failed to upload config file to card: %d.\n", rc);
4991 			goto done;
4992 		}
4993 	}
4994 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
4995 	if (rc != 0) {
4996 		device_printf(sc->dev, "failed to pre-process config file: %d "
4997 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
4998 		goto done;
4999 	}
5000 
5001 	finicsum = be32toh(caps.finicsum);
5002 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5003 	if (finicsum != cfcsum) {
5004 		device_printf(sc->dev,
5005 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5006 		    finicsum, cfcsum);
5007 	}
5008 	sc->cfcsum = cfcsum;
5009 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5010 
5011 	/*
5012 	 * Let the firmware know what features will (not) be used so it can tune
5013 	 * things accordingly.
5014 	 */
5015 #define LIMIT_CAPS(x) do { \
5016 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5017 } while (0)
5018 	LIMIT_CAPS(nbm);
5019 	LIMIT_CAPS(link);
5020 	LIMIT_CAPS(switch);
5021 	LIMIT_CAPS(nic);
5022 	LIMIT_CAPS(toe);
5023 	LIMIT_CAPS(rdma);
5024 	LIMIT_CAPS(crypto);
5025 	LIMIT_CAPS(iscsi);
5026 	LIMIT_CAPS(fcoe);
5027 #undef LIMIT_CAPS
5028 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5029 		/*
5030 		 * TOE and hashfilters are mutually exclusive.  It is a config
5031 		 * file or firmware bug if both are reported as available.  Try
5032 		 * to cope with the situation in non-debug builds by disabling
5033 		 * TOE.
5034 		 */
5035 		MPASS(caps.toecaps == 0);
5036 
5037 		caps.toecaps = 0;
5038 		caps.rdmacaps = 0;
5039 		caps.iscsicaps = 0;
5040 	}
5041 
5042 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5043 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5044 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5045 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5046 	if (rc != 0) {
5047 		device_printf(sc->dev,
5048 		    "failed to process config file: %d.\n", rc);
5049 		goto done;
5050 	}
5051 
5052 	t4_tweak_chip_settings(sc);
5053 	set_params__pre_init(sc);
5054 
5055 	/* get basic stuff going */
5056 	rc = -t4_fw_initialize(sc, sc->mbox);
5057 	if (rc != 0) {
5058 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5059 		goto done;
5060 	}
5061 done:
5062 	return (rc);
5063 }
5064 
5065 /*
5066  * Partition chip resources for use between various PFs, VFs, etc.
5067  */
5068 static int
5069 partition_resources(struct adapter *sc)
5070 {
5071 	char cfg_file[sizeof(t4_cfg_file)];
5072 	struct caps_allowed caps_allowed;
5073 	int rc;
5074 	bool fallback;
5075 
5076 	/* Only the master driver gets to configure the chip resources. */
5077 	MPASS(sc->flags & MASTER_PF);
5078 
5079 #define COPY_CAPS(x) do { \
5080 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5081 } while (0)
5082 	bzero(&caps_allowed, sizeof(caps_allowed));
5083 	COPY_CAPS(nbm);
5084 	COPY_CAPS(link);
5085 	COPY_CAPS(switch);
5086 	COPY_CAPS(nic);
5087 	COPY_CAPS(toe);
5088 	COPY_CAPS(rdma);
5089 	COPY_CAPS(crypto);
5090 	COPY_CAPS(iscsi);
5091 	COPY_CAPS(fcoe);
5092 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5093 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5094 retry:
5095 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5096 	if (rc != 0 && fallback) {
5097 		dump_devlog(sc);
5098 		device_printf(sc->dev,
5099 		    "failed (%d) to configure card with \"%s\" profile, "
5100 		    "will fall back to a basic configuration and retry.\n",
5101 		    rc, cfg_file);
5102 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5103 		bzero(&caps_allowed, sizeof(caps_allowed));
5104 		COPY_CAPS(switch);
5105 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5106 		fallback = false;
5107 		goto retry;
5108 	}
5109 #undef COPY_CAPS
5110 	return (rc);
5111 }
5112 
5113 /*
5114  * Retrieve parameters that are needed (or nice to have) very early.
5115  */
5116 static int
5117 get_params__pre_init(struct adapter *sc)
5118 {
5119 	int rc;
5120 	uint32_t param[2], val[2];
5121 
5122 	t4_get_version_info(sc);
5123 
5124 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5125 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5126 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5127 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5128 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5129 
5130 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5131 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5132 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5133 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5134 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5135 
5136 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5137 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5138 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5139 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5140 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5141 
5142 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5143 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5144 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5145 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5146 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5147 
5148 	param[0] = FW_PARAM_DEV(PORTVEC);
5149 	param[1] = FW_PARAM_DEV(CCLK);
5150 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5151 	if (rc != 0) {
5152 		device_printf(sc->dev,
5153 		    "failed to query parameters (pre_init): %d.\n", rc);
5154 		return (rc);
5155 	}
5156 
5157 	sc->params.portvec = val[0];
5158 	sc->params.nports = bitcount32(val[0]);
5159 	sc->params.vpd.cclk = val[1];
5160 
5161 	/* Read device log parameters. */
5162 	rc = -t4_init_devlog_params(sc, 1);
5163 	if (rc == 0)
5164 		fixup_devlog_params(sc);
5165 	else {
5166 		device_printf(sc->dev,
5167 		    "failed to get devlog parameters: %d.\n", rc);
5168 		rc = 0;	/* devlog isn't critical for device operation */
5169 	}
5170 
5171 	return (rc);
5172 }
5173 
5174 /*
5175  * Any params that need to be set before FW_INITIALIZE.
5176  */
5177 static int
5178 set_params__pre_init(struct adapter *sc)
5179 {
5180 	int rc = 0;
5181 	uint32_t param, val;
5182 
5183 	if (chip_id(sc) >= CHELSIO_T6) {
5184 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5185 		val = 1;
5186 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5187 		/* firmwares < 1.20.1.0 do not have this param. */
5188 		if (rc == FW_EINVAL &&
5189 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5190 			rc = 0;
5191 		}
5192 		if (rc != 0) {
5193 			device_printf(sc->dev,
5194 			    "failed to enable high priority filters :%d.\n",
5195 			    rc);
5196 		}
5197 
5198 		param = FW_PARAM_DEV(PPOD_EDRAM);
5199 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5200 		if (rc == 0 && val == 1) {
5201 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5202 			    &val);
5203 			if (rc != 0) {
5204 				device_printf(sc->dev,
5205 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5206 			}
5207 		}
5208 	}
5209 
5210 	/* Enable opaque VIIDs with firmwares that support it. */
5211 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5212 	val = 1;
5213 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5214 	if (rc == 0 && val == 1)
5215 		sc->params.viid_smt_extn_support = true;
5216 	else
5217 		sc->params.viid_smt_extn_support = false;
5218 
5219 	return (rc);
5220 }
5221 
5222 /*
5223  * Retrieve various parameters that are of interest to the driver.  The device
5224  * has been initialized by the firmware at this point.
5225  */
5226 static int
5227 get_params__post_init(struct adapter *sc)
5228 {
5229 	int rc;
5230 	uint32_t param[7], val[7];
5231 	struct fw_caps_config_cmd caps;
5232 
5233 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5234 	param[1] = FW_PARAM_PFVF(EQ_START);
5235 	param[2] = FW_PARAM_PFVF(FILTER_START);
5236 	param[3] = FW_PARAM_PFVF(FILTER_END);
5237 	param[4] = FW_PARAM_PFVF(L2T_START);
5238 	param[5] = FW_PARAM_PFVF(L2T_END);
5239 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5240 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5241 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5242 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5243 	if (rc != 0) {
5244 		device_printf(sc->dev,
5245 		    "failed to query parameters (post_init): %d.\n", rc);
5246 		return (rc);
5247 	}
5248 
5249 	sc->sge.iq_start = val[0];
5250 	sc->sge.eq_start = val[1];
5251 	if ((int)val[3] > (int)val[2]) {
5252 		sc->tids.ftid_base = val[2];
5253 		sc->tids.ftid_end = val[3];
5254 		sc->tids.nftids = val[3] - val[2] + 1;
5255 	}
5256 	sc->vres.l2t.start = val[4];
5257 	sc->vres.l2t.size = val[5] - val[4] + 1;
5258 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5259 	    ("%s: L2 table size (%u) larger than expected (%u)",
5260 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5261 	sc->params.core_vdd = val[6];
5262 
5263 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5264 	param[1] = FW_PARAM_PFVF(EQ_END);
5265 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5266 	if (rc != 0) {
5267 		device_printf(sc->dev,
5268 		    "failed to query parameters (post_init2): %d.\n", rc);
5269 		return (rc);
5270 	}
5271 	MPASS((int)val[0] >= sc->sge.iq_start);
5272 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5273 	MPASS((int)val[1] >= sc->sge.eq_start);
5274 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5275 
5276 	if (chip_id(sc) >= CHELSIO_T6) {
5277 
5278 		sc->tids.tid_base = t4_read_reg(sc,
5279 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5280 
5281 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5282 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5283 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5284 		if (rc != 0) {
5285 			device_printf(sc->dev,
5286 			   "failed to query hpfilter parameters: %d.\n", rc);
5287 			return (rc);
5288 		}
5289 		if ((int)val[1] > (int)val[0]) {
5290 			sc->tids.hpftid_base = val[0];
5291 			sc->tids.hpftid_end = val[1];
5292 			sc->tids.nhpftids = val[1] - val[0] + 1;
5293 
5294 			/*
5295 			 * These should go off if the layout changes and the
5296 			 * driver needs to catch up.
5297 			 */
5298 			MPASS(sc->tids.hpftid_base == 0);
5299 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5300 		}
5301 
5302 		param[0] = FW_PARAM_PFVF(RAWF_START);
5303 		param[1] = FW_PARAM_PFVF(RAWF_END);
5304 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5305 		if (rc != 0) {
5306 			device_printf(sc->dev,
5307 			   "failed to query rawf parameters: %d.\n", rc);
5308 			return (rc);
5309 		}
5310 		if ((int)val[1] > (int)val[0]) {
5311 			sc->rawf_base = val[0];
5312 			sc->nrawf = val[1] - val[0] + 1;
5313 		}
5314 	}
5315 
5316 	/*
5317 	 * MPSBGMAP is queried separately because only recent firmwares support
5318 	 * it as a parameter and we don't want the compound query above to fail
5319 	 * on older firmwares.
5320 	 */
5321 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5322 	val[0] = 0;
5323 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5324 	if (rc == 0)
5325 		sc->params.mps_bg_map = val[0];
5326 	else
5327 		sc->params.mps_bg_map = 0;
5328 
5329 	/*
5330 	 * Determine whether the firmware supports the filter2 work request.
5331 	 * This is queried separately for the same reason as MPSBGMAP above.
5332 	 */
5333 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5334 	val[0] = 0;
5335 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5336 	if (rc == 0)
5337 		sc->params.filter2_wr_support = val[0] != 0;
5338 	else
5339 		sc->params.filter2_wr_support = 0;
5340 
5341 	/*
5342 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5343 	 * This is queried separately for the same reason as other params above.
5344 	 */
5345 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5346 	val[0] = 0;
5347 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5348 	if (rc == 0)
5349 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5350 	else
5351 		sc->params.ulptx_memwrite_dsgl = false;
5352 
5353 	/* FW_RI_FR_NSMR_TPTE_WR support */
5354 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5355 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5356 	if (rc == 0)
5357 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5358 	else
5359 		sc->params.fr_nsmr_tpte_wr_support = false;
5360 
5361 	/* Support for 512 SGL entries per FR MR. */
5362 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5363 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5364 	if (rc == 0)
5365 		sc->params.dev_512sgl_mr = val[0] != 0;
5366 	else
5367 		sc->params.dev_512sgl_mr = false;
5368 
5369 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5370 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5371 	if (rc == 0)
5372 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5373 	else
5374 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5375 
5376 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5377 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5378 	if (rc == 0) {
5379 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5380 		sc->params.nsched_cls = val[0];
5381 	} else
5382 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5383 
5384 	/* get capabilites */
5385 	bzero(&caps, sizeof(caps));
5386 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5387 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5388 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5389 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5390 	if (rc != 0) {
5391 		device_printf(sc->dev,
5392 		    "failed to get card capabilities: %d.\n", rc);
5393 		return (rc);
5394 	}
5395 
5396 #define READ_CAPS(x) do { \
5397 	sc->x = htobe16(caps.x); \
5398 } while (0)
5399 	READ_CAPS(nbmcaps);
5400 	READ_CAPS(linkcaps);
5401 	READ_CAPS(switchcaps);
5402 	READ_CAPS(niccaps);
5403 	READ_CAPS(toecaps);
5404 	READ_CAPS(rdmacaps);
5405 	READ_CAPS(cryptocaps);
5406 	READ_CAPS(iscsicaps);
5407 	READ_CAPS(fcoecaps);
5408 
5409 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5410 		MPASS(chip_id(sc) > CHELSIO_T4);
5411 		MPASS(sc->toecaps == 0);
5412 		sc->toecaps = 0;
5413 
5414 		param[0] = FW_PARAM_DEV(NTID);
5415 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5416 		if (rc != 0) {
5417 			device_printf(sc->dev,
5418 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5419 			return (rc);
5420 		}
5421 		sc->tids.ntids = val[0];
5422 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5423 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5424 			sc->tids.ntids -= sc->tids.nhpftids;
5425 		}
5426 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5427 		sc->params.hash_filter = 1;
5428 	}
5429 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5430 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5431 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5432 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5433 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5434 		if (rc != 0) {
5435 			device_printf(sc->dev,
5436 			    "failed to query NIC parameters: %d.\n", rc);
5437 			return (rc);
5438 		}
5439 		if ((int)val[1] > (int)val[0]) {
5440 			sc->tids.etid_base = val[0];
5441 			sc->tids.etid_end = val[1];
5442 			sc->tids.netids = val[1] - val[0] + 1;
5443 			sc->params.eo_wr_cred = val[2];
5444 			sc->params.ethoffload = 1;
5445 		}
5446 	}
5447 	if (sc->toecaps) {
5448 		/* query offload-related parameters */
5449 		param[0] = FW_PARAM_DEV(NTID);
5450 		param[1] = FW_PARAM_PFVF(SERVER_START);
5451 		param[2] = FW_PARAM_PFVF(SERVER_END);
5452 		param[3] = FW_PARAM_PFVF(TDDP_START);
5453 		param[4] = FW_PARAM_PFVF(TDDP_END);
5454 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5455 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5456 		if (rc != 0) {
5457 			device_printf(sc->dev,
5458 			    "failed to query TOE parameters: %d.\n", rc);
5459 			return (rc);
5460 		}
5461 		sc->tids.ntids = val[0];
5462 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5463 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5464 			sc->tids.ntids -= sc->tids.nhpftids;
5465 		}
5466 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5467 		if ((int)val[2] > (int)val[1]) {
5468 			sc->tids.stid_base = val[1];
5469 			sc->tids.nstids = val[2] - val[1] + 1;
5470 		}
5471 		sc->vres.ddp.start = val[3];
5472 		sc->vres.ddp.size = val[4] - val[3] + 1;
5473 		sc->params.ofldq_wr_cred = val[5];
5474 		sc->params.offload = 1;
5475 	} else {
5476 		/*
5477 		 * The firmware attempts memfree TOE configuration for -SO cards
5478 		 * and will report toecaps=0 if it runs out of resources (this
5479 		 * depends on the config file).  It may not report 0 for other
5480 		 * capabilities dependent on the TOE in this case.  Set them to
5481 		 * 0 here so that the driver doesn't bother tracking resources
5482 		 * that will never be used.
5483 		 */
5484 		sc->iscsicaps = 0;
5485 		sc->rdmacaps = 0;
5486 	}
5487 	if (sc->rdmacaps) {
5488 		param[0] = FW_PARAM_PFVF(STAG_START);
5489 		param[1] = FW_PARAM_PFVF(STAG_END);
5490 		param[2] = FW_PARAM_PFVF(RQ_START);
5491 		param[3] = FW_PARAM_PFVF(RQ_END);
5492 		param[4] = FW_PARAM_PFVF(PBL_START);
5493 		param[5] = FW_PARAM_PFVF(PBL_END);
5494 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5495 		if (rc != 0) {
5496 			device_printf(sc->dev,
5497 			    "failed to query RDMA parameters(1): %d.\n", rc);
5498 			return (rc);
5499 		}
5500 		sc->vres.stag.start = val[0];
5501 		sc->vres.stag.size = val[1] - val[0] + 1;
5502 		sc->vres.rq.start = val[2];
5503 		sc->vres.rq.size = val[3] - val[2] + 1;
5504 		sc->vres.pbl.start = val[4];
5505 		sc->vres.pbl.size = val[5] - val[4] + 1;
5506 
5507 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5508 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5509 		param[2] = FW_PARAM_PFVF(CQ_START);
5510 		param[3] = FW_PARAM_PFVF(CQ_END);
5511 		param[4] = FW_PARAM_PFVF(OCQ_START);
5512 		param[5] = FW_PARAM_PFVF(OCQ_END);
5513 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5514 		if (rc != 0) {
5515 			device_printf(sc->dev,
5516 			    "failed to query RDMA parameters(2): %d.\n", rc);
5517 			return (rc);
5518 		}
5519 		sc->vres.qp.start = val[0];
5520 		sc->vres.qp.size = val[1] - val[0] + 1;
5521 		sc->vres.cq.start = val[2];
5522 		sc->vres.cq.size = val[3] - val[2] + 1;
5523 		sc->vres.ocq.start = val[4];
5524 		sc->vres.ocq.size = val[5] - val[4] + 1;
5525 
5526 		param[0] = FW_PARAM_PFVF(SRQ_START);
5527 		param[1] = FW_PARAM_PFVF(SRQ_END);
5528 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5529 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5530 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5531 		if (rc != 0) {
5532 			device_printf(sc->dev,
5533 			    "failed to query RDMA parameters(3): %d.\n", rc);
5534 			return (rc);
5535 		}
5536 		sc->vres.srq.start = val[0];
5537 		sc->vres.srq.size = val[1] - val[0] + 1;
5538 		sc->params.max_ordird_qp = val[2];
5539 		sc->params.max_ird_adapter = val[3];
5540 	}
5541 	if (sc->iscsicaps) {
5542 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5543 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5544 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5545 		if (rc != 0) {
5546 			device_printf(sc->dev,
5547 			    "failed to query iSCSI parameters: %d.\n", rc);
5548 			return (rc);
5549 		}
5550 		sc->vres.iscsi.start = val[0];
5551 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5552 	}
5553 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5554 		param[0] = FW_PARAM_PFVF(TLS_START);
5555 		param[1] = FW_PARAM_PFVF(TLS_END);
5556 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5557 		if (rc != 0) {
5558 			device_printf(sc->dev,
5559 			    "failed to query TLS parameters: %d.\n", rc);
5560 			return (rc);
5561 		}
5562 		sc->vres.key.start = val[0];
5563 		sc->vres.key.size = val[1] - val[0] + 1;
5564 	}
5565 
5566 	/*
5567 	 * We've got the params we wanted to query directly from the firmware.
5568 	 * Grab some others via other means.
5569 	 */
5570 	t4_init_sge_params(sc);
5571 	t4_init_tp_params(sc);
5572 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5573 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5574 
5575 	rc = t4_verify_chip_settings(sc);
5576 	if (rc != 0)
5577 		return (rc);
5578 	t4_init_rx_buf_info(sc);
5579 
5580 	return (rc);
5581 }
5582 
5583 #ifdef KERN_TLS
5584 static void
5585 ktls_tick(void *arg)
5586 {
5587 	struct adapter *sc;
5588 	uint32_t tstamp;
5589 
5590 	sc = arg;
5591 	tstamp = tcp_ts_getticks();
5592 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5593 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5594 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5595 }
5596 
5597 static int
5598 t6_config_kern_tls(struct adapter *sc, bool enable)
5599 {
5600 	int rc;
5601 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5602 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5603 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5604 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5605 
5606 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5607 	if (rc != 0) {
5608 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5609 		    enable ?  "enable" : "disable", rc);
5610 		return (rc);
5611 	}
5612 
5613 	if (enable) {
5614 		sc->flags |= KERN_TLS_ON;
5615 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5616 		    C_HARDCLOCK);
5617 	} else {
5618 		sc->flags &= ~KERN_TLS_ON;
5619 		callout_stop(&sc->ktls_tick);
5620 	}
5621 
5622 	return (rc);
5623 }
5624 #endif
5625 
5626 static int
5627 set_params__post_init(struct adapter *sc)
5628 {
5629 	uint32_t mask, param, val;
5630 #ifdef TCP_OFFLOAD
5631 	int i, v, shift;
5632 #endif
5633 
5634 	/* ask for encapsulated CPLs */
5635 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5636 	val = 1;
5637 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5638 
5639 	/* Enable 32b port caps if the firmware supports it. */
5640 	param = FW_PARAM_PFVF(PORT_CAPS32);
5641 	val = 1;
5642 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5643 		sc->params.port_caps32 = 1;
5644 
5645 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5646 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5647 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5648 	    V_MASKFILTER(val - 1));
5649 
5650 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5651 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5652 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5653 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5654 	val = 0;
5655 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5656 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5657 		    F_ATTACKFILTERENABLE);
5658 		val |= F_DROPERRORATTACK;
5659 	}
5660 	if (t4_drop_ip_fragments != 0) {
5661 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5662 		    F_FRAGMENTDROP);
5663 		val |= F_DROPERRORFRAG;
5664 	}
5665 	if (t4_drop_pkts_with_l2_errors != 0)
5666 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5667 	if (t4_drop_pkts_with_l3_errors != 0) {
5668 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5669 		    F_DROPERRORCSUMIP;
5670 	}
5671 	if (t4_drop_pkts_with_l4_errors != 0) {
5672 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5673 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5674 	}
5675 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5676 
5677 #ifdef TCP_OFFLOAD
5678 	/*
5679 	 * Override the TOE timers with user provided tunables.  This is not the
5680 	 * recommended way to change the timers (the firmware config file is) so
5681 	 * these tunables are not documented.
5682 	 *
5683 	 * All the timer tunables are in microseconds.
5684 	 */
5685 	if (t4_toe_keepalive_idle != 0) {
5686 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5687 		v &= M_KEEPALIVEIDLE;
5688 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5689 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5690 	}
5691 	if (t4_toe_keepalive_interval != 0) {
5692 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5693 		v &= M_KEEPALIVEINTVL;
5694 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5695 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5696 	}
5697 	if (t4_toe_keepalive_count != 0) {
5698 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5699 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5700 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5701 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5702 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5703 	}
5704 	if (t4_toe_rexmt_min != 0) {
5705 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5706 		v &= M_RXTMIN;
5707 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5708 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5709 	}
5710 	if (t4_toe_rexmt_max != 0) {
5711 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5712 		v &= M_RXTMAX;
5713 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5714 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5715 	}
5716 	if (t4_toe_rexmt_count != 0) {
5717 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5718 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5719 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5720 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5721 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5722 	}
5723 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5724 		if (t4_toe_rexmt_backoff[i] != -1) {
5725 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5726 			shift = (i & 3) << 3;
5727 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5728 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5729 		}
5730 	}
5731 #endif
5732 
5733 #ifdef KERN_TLS
5734 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS &&
5735 	    sc->toecaps & FW_CAPS_CONFIG_TOE) {
5736 		/*
5737 		 * Limit TOE connections to 2 reassembly "islands".
5738 		 * This is required to permit migrating TOE
5739 		 * connections to UPL_MODE_TLS.
5740 		 */
5741 		t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG,
5742 		    V_PASSMODE(M_PASSMODE), V_PASSMODE(2));
5743 	}
5744 
5745 	if (is_ktls(sc)) {
5746 		sc->tlst.inline_keys = t4_tls_inline_keys;
5747 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5748 		if (t4_kern_tls != 0 && is_t6(sc))
5749 			t6_config_kern_tls(sc, true);
5750 	}
5751 #endif
5752 	return (0);
5753 }
5754 
5755 #undef FW_PARAM_PFVF
5756 #undef FW_PARAM_DEV
5757 
5758 static void
5759 t4_set_desc(struct adapter *sc)
5760 {
5761 	char buf[128];
5762 	struct adapter_params *p = &sc->params;
5763 
5764 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5765 
5766 	device_set_desc_copy(sc->dev, buf);
5767 }
5768 
5769 static inline void
5770 ifmedia_add4(struct ifmedia *ifm, int m)
5771 {
5772 
5773 	ifmedia_add(ifm, m, 0, NULL);
5774 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5775 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5776 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5777 }
5778 
5779 /*
5780  * This is the selected media, which is not quite the same as the active media.
5781  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5782  * and active are not the same, and "media: Ethernet selected" otherwise.
5783  */
5784 static void
5785 set_current_media(struct port_info *pi)
5786 {
5787 	struct link_config *lc;
5788 	struct ifmedia *ifm;
5789 	int mword;
5790 	u_int speed;
5791 
5792 	PORT_LOCK_ASSERT_OWNED(pi);
5793 
5794 	/* Leave current media alone if it's already set to IFM_NONE. */
5795 	ifm = &pi->media;
5796 	if (ifm->ifm_cur != NULL &&
5797 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5798 		return;
5799 
5800 	lc = &pi->link_cfg;
5801 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5802 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5803 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5804 		return;
5805 	}
5806 	mword = IFM_ETHER | IFM_FDX;
5807 	if (lc->requested_fc & PAUSE_TX)
5808 		mword |= IFM_ETH_TXPAUSE;
5809 	if (lc->requested_fc & PAUSE_RX)
5810 		mword |= IFM_ETH_RXPAUSE;
5811 	if (lc->requested_speed == 0)
5812 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5813 	else
5814 		speed = lc->requested_speed;
5815 	mword |= port_mword(pi, speed_to_fwcap(speed));
5816 	ifmedia_set(ifm, mword);
5817 }
5818 
5819 /*
5820  * Returns true if the ifmedia list for the port cannot change.
5821  */
5822 static bool
5823 fixed_ifmedia(struct port_info *pi)
5824 {
5825 
5826 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5827 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5828 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5829 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5830 	    pi->port_type == FW_PORT_TYPE_KX ||
5831 	    pi->port_type == FW_PORT_TYPE_KR ||
5832 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5833 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5834 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5835 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5836 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5837 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5838 }
5839 
5840 static void
5841 build_medialist(struct port_info *pi)
5842 {
5843 	uint32_t ss, speed;
5844 	int unknown, mword, bit;
5845 	struct link_config *lc;
5846 	struct ifmedia *ifm;
5847 
5848 	PORT_LOCK_ASSERT_OWNED(pi);
5849 
5850 	if (pi->flags & FIXED_IFMEDIA)
5851 		return;
5852 
5853 	/*
5854 	 * Rebuild the ifmedia list.
5855 	 */
5856 	ifm = &pi->media;
5857 	ifmedia_removeall(ifm);
5858 	lc = &pi->link_cfg;
5859 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5860 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5861 		MPASS(ss != 0);
5862 no_media:
5863 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5864 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5865 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5866 		return;
5867 	}
5868 
5869 	unknown = 0;
5870 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5871 		speed = 1 << bit;
5872 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5873 		if (ss & speed) {
5874 			mword = port_mword(pi, speed);
5875 			if (mword == IFM_NONE) {
5876 				goto no_media;
5877 			} else if (mword == IFM_UNKNOWN)
5878 				unknown++;
5879 			else
5880 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5881 		}
5882 	}
5883 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5884 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5885 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5886 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5887 
5888 	set_current_media(pi);
5889 }
5890 
5891 /*
5892  * Initialize the requested fields in the link config based on driver tunables.
5893  */
5894 static void
5895 init_link_config(struct port_info *pi)
5896 {
5897 	struct link_config *lc = &pi->link_cfg;
5898 
5899 	PORT_LOCK_ASSERT_OWNED(pi);
5900 
5901 	lc->requested_caps = 0;
5902 	lc->requested_speed = 0;
5903 
5904 	if (t4_autoneg == 0)
5905 		lc->requested_aneg = AUTONEG_DISABLE;
5906 	else if (t4_autoneg == 1)
5907 		lc->requested_aneg = AUTONEG_ENABLE;
5908 	else
5909 		lc->requested_aneg = AUTONEG_AUTO;
5910 
5911 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5912 	    PAUSE_AUTONEG);
5913 
5914 	if (t4_fec & FEC_AUTO)
5915 		lc->requested_fec = FEC_AUTO;
5916 	else if (t4_fec == 0)
5917 		lc->requested_fec = FEC_NONE;
5918 	else {
5919 		/* -1 is handled by the FEC_AUTO block above and not here. */
5920 		lc->requested_fec = t4_fec &
5921 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5922 		if (lc->requested_fec == 0)
5923 			lc->requested_fec = FEC_AUTO;
5924 	}
5925 	if (t4_force_fec < 0)
5926 		lc->force_fec = -1;
5927 	else if (t4_force_fec > 0)
5928 		lc->force_fec = 1;
5929 	else
5930 		lc->force_fec = 0;
5931 }
5932 
5933 /*
5934  * Makes sure that all requested settings comply with what's supported by the
5935  * port.  Returns the number of settings that were invalid and had to be fixed.
5936  */
5937 static int
5938 fixup_link_config(struct port_info *pi)
5939 {
5940 	int n = 0;
5941 	struct link_config *lc = &pi->link_cfg;
5942 	uint32_t fwspeed;
5943 
5944 	PORT_LOCK_ASSERT_OWNED(pi);
5945 
5946 	/* Speed (when not autonegotiating) */
5947 	if (lc->requested_speed != 0) {
5948 		fwspeed = speed_to_fwcap(lc->requested_speed);
5949 		if ((fwspeed & lc->pcaps) == 0) {
5950 			n++;
5951 			lc->requested_speed = 0;
5952 		}
5953 	}
5954 
5955 	/* Link autonegotiation */
5956 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5957 	    lc->requested_aneg == AUTONEG_DISABLE ||
5958 	    lc->requested_aneg == AUTONEG_AUTO);
5959 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5960 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5961 		n++;
5962 		lc->requested_aneg = AUTONEG_AUTO;
5963 	}
5964 
5965 	/* Flow control */
5966 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5967 	if (lc->requested_fc & PAUSE_TX &&
5968 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5969 		n++;
5970 		lc->requested_fc &= ~PAUSE_TX;
5971 	}
5972 	if (lc->requested_fc & PAUSE_RX &&
5973 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5974 		n++;
5975 		lc->requested_fc &= ~PAUSE_RX;
5976 	}
5977 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5978 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5979 		n++;
5980 		lc->requested_fc |= PAUSE_AUTONEG;
5981 	}
5982 
5983 	/* FEC */
5984 	if ((lc->requested_fec & FEC_RS &&
5985 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5986 	    (lc->requested_fec & FEC_BASER_RS &&
5987 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5988 		n++;
5989 		lc->requested_fec = FEC_AUTO;
5990 	}
5991 
5992 	return (n);
5993 }
5994 
5995 /*
5996  * Apply the requested L1 settings, which are expected to be valid, to the
5997  * hardware.
5998  */
5999 static int
6000 apply_link_config(struct port_info *pi)
6001 {
6002 	struct adapter *sc = pi->adapter;
6003 	struct link_config *lc = &pi->link_cfg;
6004 	int rc;
6005 
6006 #ifdef INVARIANTS
6007 	ASSERT_SYNCHRONIZED_OP(sc);
6008 	PORT_LOCK_ASSERT_OWNED(pi);
6009 
6010 	if (lc->requested_aneg == AUTONEG_ENABLE)
6011 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6012 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6013 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6014 	if (lc->requested_fc & PAUSE_TX)
6015 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6016 	if (lc->requested_fc & PAUSE_RX)
6017 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6018 	if (lc->requested_fec & FEC_RS)
6019 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6020 	if (lc->requested_fec & FEC_BASER_RS)
6021 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6022 #endif
6023 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6024 	if (rc != 0) {
6025 		/* Don't complain if the VF driver gets back an EPERM. */
6026 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
6027 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6028 	} else {
6029 		/*
6030 		 * An L1_CFG will almost always result in a link-change event if
6031 		 * the link is up, and the driver will refresh the actual
6032 		 * fec/fc/etc. when the notification is processed.  If the link
6033 		 * is down then the actual settings are meaningless.
6034 		 *
6035 		 * This takes care of the case where a change in the L1 settings
6036 		 * may not result in a notification.
6037 		 */
6038 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6039 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6040 	}
6041 	return (rc);
6042 }
6043 
6044 #define FW_MAC_EXACT_CHUNK	7
6045 struct mcaddr_ctx {
6046 	if_t ifp;
6047 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6048 	uint64_t hash;
6049 	int i;
6050 	int del;
6051 	int rc;
6052 };
6053 
6054 static u_int
6055 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6056 {
6057 	struct mcaddr_ctx *ctx = arg;
6058 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6059 	struct port_info *pi = vi->pi;
6060 	struct adapter *sc = pi->adapter;
6061 
6062 	if (ctx->rc < 0)
6063 		return (0);
6064 
6065 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6066 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6067 	ctx->i++;
6068 
6069 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6070 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6071 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6072 		if (ctx->rc < 0) {
6073 			int j;
6074 
6075 			for (j = 0; j < ctx->i; j++) {
6076 				if_printf(ctx->ifp,
6077 				    "failed to add mc address"
6078 				    " %02x:%02x:%02x:"
6079 				    "%02x:%02x:%02x rc=%d\n",
6080 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6081 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6082 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6083 				    -ctx->rc);
6084 			}
6085 			return (0);
6086 		}
6087 		ctx->del = 0;
6088 		ctx->i = 0;
6089 	}
6090 
6091 	return (1);
6092 }
6093 
6094 /*
6095  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6096  * indicates which parameters should be programmed (the rest are left alone).
6097  */
6098 int
6099 update_mac_settings(if_t ifp, int flags)
6100 {
6101 	int rc = 0;
6102 	struct vi_info *vi = if_getsoftc(ifp);
6103 	struct port_info *pi = vi->pi;
6104 	struct adapter *sc = pi->adapter;
6105 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6106 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6107 
6108 	ASSERT_SYNCHRONIZED_OP(sc);
6109 	KASSERT(flags, ("%s: not told what to update.", __func__));
6110 
6111 	if (flags & XGMAC_MTU)
6112 		mtu = if_getmtu(ifp);
6113 
6114 	if (flags & XGMAC_PROMISC)
6115 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6116 
6117 	if (flags & XGMAC_ALLMULTI)
6118 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6119 
6120 	if (flags & XGMAC_VLANEX)
6121 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6122 
6123 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6124 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6125 		    allmulti, 1, vlanex, false);
6126 		if (rc) {
6127 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6128 			    rc);
6129 			return (rc);
6130 		}
6131 	}
6132 
6133 	if (flags & XGMAC_UCADDR) {
6134 		uint8_t ucaddr[ETHER_ADDR_LEN];
6135 
6136 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6137 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6138 		    ucaddr, true, &vi->smt_idx);
6139 		if (rc < 0) {
6140 			rc = -rc;
6141 			if_printf(ifp, "change_mac failed: %d\n", rc);
6142 			return (rc);
6143 		} else {
6144 			vi->xact_addr_filt = rc;
6145 			rc = 0;
6146 		}
6147 	}
6148 
6149 	if (flags & XGMAC_MCADDRS) {
6150 		struct epoch_tracker et;
6151 		struct mcaddr_ctx ctx;
6152 		int j;
6153 
6154 		ctx.ifp = ifp;
6155 		ctx.hash = 0;
6156 		ctx.i = 0;
6157 		ctx.del = 1;
6158 		ctx.rc = 0;
6159 		/*
6160 		 * Unlike other drivers, we accumulate list of pointers into
6161 		 * interface address lists and we need to keep it safe even
6162 		 * after if_foreach_llmaddr() returns, thus we must enter the
6163 		 * network epoch.
6164 		 */
6165 		NET_EPOCH_ENTER(et);
6166 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6167 		if (ctx.rc < 0) {
6168 			NET_EPOCH_EXIT(et);
6169 			rc = -ctx.rc;
6170 			return (rc);
6171 		}
6172 		if (ctx.i > 0) {
6173 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6174 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6175 			NET_EPOCH_EXIT(et);
6176 			if (rc < 0) {
6177 				rc = -rc;
6178 				for (j = 0; j < ctx.i; j++) {
6179 					if_printf(ifp,
6180 					    "failed to add mcast address"
6181 					    " %02x:%02x:%02x:"
6182 					    "%02x:%02x:%02x rc=%d\n",
6183 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6184 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6185 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6186 					    rc);
6187 				}
6188 				return (rc);
6189 			}
6190 			ctx.del = 0;
6191 		} else
6192 			NET_EPOCH_EXIT(et);
6193 
6194 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6195 		if (rc != 0)
6196 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6197 			    rc);
6198 		if (ctx.del == 0) {
6199 			/* We clobbered the VXLAN entry if there was one. */
6200 			pi->vxlan_tcam_entry = false;
6201 		}
6202 	}
6203 
6204 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6205 	    pi->vxlan_tcam_entry == false) {
6206 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6207 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6208 		    true);
6209 		if (rc < 0) {
6210 			rc = -rc;
6211 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6212 			    rc);
6213 		} else {
6214 			MPASS(rc == sc->rawf_base + pi->port_id);
6215 			rc = 0;
6216 			pi->vxlan_tcam_entry = true;
6217 		}
6218 	}
6219 
6220 	return (rc);
6221 }
6222 
6223 /*
6224  * {begin|end}_synchronized_op must be called from the same thread.
6225  */
6226 int
6227 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6228     char *wmesg)
6229 {
6230 	int rc, pri;
6231 
6232 #ifdef WITNESS
6233 	/* the caller thinks it's ok to sleep, but is it really? */
6234 	if (flags & SLEEP_OK)
6235 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6236 		    "begin_synchronized_op");
6237 #endif
6238 
6239 	if (INTR_OK)
6240 		pri = PCATCH;
6241 	else
6242 		pri = 0;
6243 
6244 	ADAPTER_LOCK(sc);
6245 	for (;;) {
6246 
6247 		if (vi && IS_DOOMED(vi)) {
6248 			rc = ENXIO;
6249 			goto done;
6250 		}
6251 
6252 		if (!IS_BUSY(sc)) {
6253 			rc = 0;
6254 			break;
6255 		}
6256 
6257 		if (!(flags & SLEEP_OK)) {
6258 			rc = EBUSY;
6259 			goto done;
6260 		}
6261 
6262 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6263 			rc = EINTR;
6264 			goto done;
6265 		}
6266 	}
6267 
6268 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6269 	SET_BUSY(sc);
6270 #ifdef INVARIANTS
6271 	sc->last_op = wmesg;
6272 	sc->last_op_thr = curthread;
6273 	sc->last_op_flags = flags;
6274 #endif
6275 
6276 done:
6277 	if (!(flags & HOLD_LOCK) || rc)
6278 		ADAPTER_UNLOCK(sc);
6279 
6280 	return (rc);
6281 }
6282 
6283 /*
6284  * Tell if_ioctl and if_init that the VI is going away.  This is
6285  * special variant of begin_synchronized_op and must be paired with a
6286  * call to end_synchronized_op.
6287  */
6288 void
6289 doom_vi(struct adapter *sc, struct vi_info *vi)
6290 {
6291 
6292 	ADAPTER_LOCK(sc);
6293 	SET_DOOMED(vi);
6294 	wakeup(&sc->flags);
6295 	while (IS_BUSY(sc))
6296 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6297 	SET_BUSY(sc);
6298 #ifdef INVARIANTS
6299 	sc->last_op = "t4detach";
6300 	sc->last_op_thr = curthread;
6301 	sc->last_op_flags = 0;
6302 #endif
6303 	ADAPTER_UNLOCK(sc);
6304 }
6305 
6306 /*
6307  * {begin|end}_synchronized_op must be called from the same thread.
6308  */
6309 void
6310 end_synchronized_op(struct adapter *sc, int flags)
6311 {
6312 
6313 	if (flags & LOCK_HELD)
6314 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6315 	else
6316 		ADAPTER_LOCK(sc);
6317 
6318 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6319 	CLR_BUSY(sc);
6320 	wakeup(&sc->flags);
6321 	ADAPTER_UNLOCK(sc);
6322 }
6323 
6324 static int
6325 cxgbe_init_synchronized(struct vi_info *vi)
6326 {
6327 	struct port_info *pi = vi->pi;
6328 	struct adapter *sc = pi->adapter;
6329 	if_t ifp = vi->ifp;
6330 	int rc = 0, i;
6331 	struct sge_txq *txq;
6332 
6333 	ASSERT_SYNCHRONIZED_OP(sc);
6334 
6335 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6336 		return (0);	/* already running */
6337 
6338 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6339 		return (rc);	/* error message displayed already */
6340 
6341 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6342 		return (rc); /* error message displayed already */
6343 
6344 	rc = update_mac_settings(ifp, XGMAC_ALL);
6345 	if (rc)
6346 		goto done;	/* error message displayed already */
6347 
6348 	PORT_LOCK(pi);
6349 	if (pi->up_vis == 0) {
6350 		t4_update_port_info(pi);
6351 		fixup_link_config(pi);
6352 		build_medialist(pi);
6353 		apply_link_config(pi);
6354 	}
6355 
6356 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6357 	if (rc != 0) {
6358 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6359 		PORT_UNLOCK(pi);
6360 		goto done;
6361 	}
6362 
6363 	/*
6364 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6365 	 * if this changes.
6366 	 */
6367 
6368 	for_each_txq(vi, i, txq) {
6369 		TXQ_LOCK(txq);
6370 		txq->eq.flags |= EQ_ENABLED;
6371 		TXQ_UNLOCK(txq);
6372 	}
6373 
6374 	/*
6375 	 * The first iq of the first port to come up is used for tracing.
6376 	 */
6377 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6378 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6379 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6380 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6381 		    V_QUEUENUMBER(sc->traceq));
6382 		pi->flags |= HAS_TRACEQ;
6383 	}
6384 
6385 	/* all ok */
6386 	pi->up_vis++;
6387 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6388 	if (pi->link_cfg.link_ok)
6389 		t4_os_link_changed(pi);
6390 	PORT_UNLOCK(pi);
6391 
6392 	mtx_lock(&vi->tick_mtx);
6393 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6394 		callout_reset(&vi->tick, hz, vi_tick, vi);
6395 	else
6396 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6397 	mtx_unlock(&vi->tick_mtx);
6398 done:
6399 	if (rc != 0)
6400 		cxgbe_uninit_synchronized(vi);
6401 
6402 	return (rc);
6403 }
6404 
6405 /*
6406  * Idempotent.
6407  */
6408 static int
6409 cxgbe_uninit_synchronized(struct vi_info *vi)
6410 {
6411 	struct port_info *pi = vi->pi;
6412 	struct adapter *sc = pi->adapter;
6413 	if_t ifp = vi->ifp;
6414 	int rc, i;
6415 	struct sge_txq *txq;
6416 
6417 	ASSERT_SYNCHRONIZED_OP(sc);
6418 
6419 	if (!(vi->flags & VI_INIT_DONE)) {
6420 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6421 			KASSERT(0, ("uninited VI is running"));
6422 			if_printf(ifp, "uninited VI with running ifnet.  "
6423 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6424 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6425 			    if_getdrvflags(ifp));
6426 		}
6427 		return (0);
6428 	}
6429 
6430 	/*
6431 	 * Disable the VI so that all its data in either direction is discarded
6432 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6433 	 * tick) intact as the TP can deliver negative advice or data that it's
6434 	 * holding in its RAM (for an offloaded connection) even after the VI is
6435 	 * disabled.
6436 	 */
6437 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6438 	if (rc) {
6439 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6440 		return (rc);
6441 	}
6442 
6443 	for_each_txq(vi, i, txq) {
6444 		TXQ_LOCK(txq);
6445 		txq->eq.flags &= ~EQ_ENABLED;
6446 		TXQ_UNLOCK(txq);
6447 	}
6448 
6449 	mtx_lock(&vi->tick_mtx);
6450 	callout_stop(&vi->tick);
6451 	mtx_unlock(&vi->tick_mtx);
6452 
6453 	PORT_LOCK(pi);
6454 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6455 		PORT_UNLOCK(pi);
6456 		return (0);
6457 	}
6458 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6459 	pi->up_vis--;
6460 	if (pi->up_vis > 0) {
6461 		PORT_UNLOCK(pi);
6462 		return (0);
6463 	}
6464 
6465 	pi->link_cfg.link_ok = false;
6466 	pi->link_cfg.speed = 0;
6467 	pi->link_cfg.link_down_rc = 255;
6468 	t4_os_link_changed(pi);
6469 	PORT_UNLOCK(pi);
6470 
6471 	return (0);
6472 }
6473 
6474 /*
6475  * It is ok for this function to fail midway and return right away.  t4_detach
6476  * will walk the entire sc->irq list and clean up whatever is valid.
6477  */
6478 int
6479 t4_setup_intr_handlers(struct adapter *sc)
6480 {
6481 	int rc, rid, p, q, v;
6482 	char s[8];
6483 	struct irq *irq;
6484 	struct port_info *pi;
6485 	struct vi_info *vi;
6486 	struct sge *sge = &sc->sge;
6487 	struct sge_rxq *rxq;
6488 #ifdef TCP_OFFLOAD
6489 	struct sge_ofld_rxq *ofld_rxq;
6490 #endif
6491 #ifdef DEV_NETMAP
6492 	struct sge_nm_rxq *nm_rxq;
6493 #endif
6494 #ifdef RSS
6495 	int nbuckets = rss_getnumbuckets();
6496 #endif
6497 
6498 	/*
6499 	 * Setup interrupts.
6500 	 */
6501 	irq = &sc->irq[0];
6502 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6503 	if (forwarding_intr_to_fwq(sc))
6504 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6505 
6506 	/* Multiple interrupts. */
6507 	if (sc->flags & IS_VF)
6508 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6509 		    ("%s: too few intr.", __func__));
6510 	else
6511 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6512 		    ("%s: too few intr.", __func__));
6513 
6514 	/* The first one is always error intr on PFs */
6515 	if (!(sc->flags & IS_VF)) {
6516 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6517 		if (rc != 0)
6518 			return (rc);
6519 		irq++;
6520 		rid++;
6521 	}
6522 
6523 	/* The second one is always the firmware event queue (first on VFs) */
6524 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6525 	if (rc != 0)
6526 		return (rc);
6527 	irq++;
6528 	rid++;
6529 
6530 	for_each_port(sc, p) {
6531 		pi = sc->port[p];
6532 		for_each_vi(pi, v, vi) {
6533 			vi->first_intr = rid - 1;
6534 
6535 			if (vi->nnmrxq > 0) {
6536 				int n = max(vi->nrxq, vi->nnmrxq);
6537 
6538 				rxq = &sge->rxq[vi->first_rxq];
6539 #ifdef DEV_NETMAP
6540 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6541 #endif
6542 				for (q = 0; q < n; q++) {
6543 					snprintf(s, sizeof(s), "%x%c%x", p,
6544 					    'a' + v, q);
6545 					if (q < vi->nrxq)
6546 						irq->rxq = rxq++;
6547 #ifdef DEV_NETMAP
6548 					if (q < vi->nnmrxq)
6549 						irq->nm_rxq = nm_rxq++;
6550 
6551 					if (irq->nm_rxq != NULL &&
6552 					    irq->rxq == NULL) {
6553 						/* Netmap rx only */
6554 						rc = t4_alloc_irq(sc, irq, rid,
6555 						    t4_nm_intr, irq->nm_rxq, s);
6556 					}
6557 					if (irq->nm_rxq != NULL &&
6558 					    irq->rxq != NULL) {
6559 						/* NIC and Netmap rx */
6560 						rc = t4_alloc_irq(sc, irq, rid,
6561 						    t4_vi_intr, irq, s);
6562 					}
6563 #endif
6564 					if (irq->rxq != NULL &&
6565 					    irq->nm_rxq == NULL) {
6566 						/* NIC rx only */
6567 						rc = t4_alloc_irq(sc, irq, rid,
6568 						    t4_intr, irq->rxq, s);
6569 					}
6570 					if (rc != 0)
6571 						return (rc);
6572 #ifdef RSS
6573 					if (q < vi->nrxq) {
6574 						bus_bind_intr(sc->dev, irq->res,
6575 						    rss_getcpu(q % nbuckets));
6576 					}
6577 #endif
6578 					irq++;
6579 					rid++;
6580 					vi->nintr++;
6581 				}
6582 			} else {
6583 				for_each_rxq(vi, q, rxq) {
6584 					snprintf(s, sizeof(s), "%x%c%x", p,
6585 					    'a' + v, q);
6586 					rc = t4_alloc_irq(sc, irq, rid,
6587 					    t4_intr, rxq, s);
6588 					if (rc != 0)
6589 						return (rc);
6590 #ifdef RSS
6591 					bus_bind_intr(sc->dev, irq->res,
6592 					    rss_getcpu(q % nbuckets));
6593 #endif
6594 					irq++;
6595 					rid++;
6596 					vi->nintr++;
6597 				}
6598 			}
6599 #ifdef TCP_OFFLOAD
6600 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6601 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6602 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6603 				    ofld_rxq, s);
6604 				if (rc != 0)
6605 					return (rc);
6606 				irq++;
6607 				rid++;
6608 				vi->nintr++;
6609 			}
6610 #endif
6611 		}
6612 	}
6613 	MPASS(irq == &sc->irq[sc->intr_count]);
6614 
6615 	return (0);
6616 }
6617 
6618 static void
6619 write_global_rss_key(struct adapter *sc)
6620 {
6621 #ifdef RSS
6622 	int i;
6623 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6624 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6625 
6626 	CTASSERT(RSS_KEYSIZE == 40);
6627 
6628 	rss_getkey((void *)&raw_rss_key[0]);
6629 	for (i = 0; i < nitems(rss_key); i++) {
6630 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6631 	}
6632 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6633 #endif
6634 }
6635 
6636 /*
6637  * Idempotent.
6638  */
6639 static int
6640 adapter_full_init(struct adapter *sc)
6641 {
6642 	int rc, i;
6643 
6644 	ASSERT_SYNCHRONIZED_OP(sc);
6645 
6646 	/*
6647 	 * queues that belong to the adapter (not any particular port).
6648 	 */
6649 	rc = t4_setup_adapter_queues(sc);
6650 	if (rc != 0)
6651 		return (rc);
6652 
6653 	for (i = 0; i < nitems(sc->tq); i++) {
6654 		if (sc->tq[i] != NULL)
6655 			continue;
6656 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6657 		    taskqueue_thread_enqueue, &sc->tq[i]);
6658 		if (sc->tq[i] == NULL) {
6659 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6660 			return (ENOMEM);
6661 		}
6662 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6663 		    device_get_nameunit(sc->dev), i);
6664 	}
6665 
6666 	if (!(sc->flags & IS_VF)) {
6667 		write_global_rss_key(sc);
6668 		t4_intr_enable(sc);
6669 	}
6670 	return (0);
6671 }
6672 
6673 int
6674 adapter_init(struct adapter *sc)
6675 {
6676 	int rc;
6677 
6678 	ASSERT_SYNCHRONIZED_OP(sc);
6679 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6680 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6681 	    ("%s: FULL_INIT_DONE already", __func__));
6682 
6683 	rc = adapter_full_init(sc);
6684 	if (rc != 0)
6685 		adapter_full_uninit(sc);
6686 	else
6687 		sc->flags |= FULL_INIT_DONE;
6688 
6689 	return (rc);
6690 }
6691 
6692 /*
6693  * Idempotent.
6694  */
6695 static void
6696 adapter_full_uninit(struct adapter *sc)
6697 {
6698 	int i;
6699 
6700 	t4_teardown_adapter_queues(sc);
6701 
6702 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6703 		taskqueue_free(sc->tq[i]);
6704 		sc->tq[i] = NULL;
6705 	}
6706 
6707 	sc->flags &= ~FULL_INIT_DONE;
6708 }
6709 
6710 #ifdef RSS
6711 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6712     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6713     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6714     RSS_HASHTYPE_RSS_UDP_IPV6)
6715 
6716 /* Translates kernel hash types to hardware. */
6717 static int
6718 hashconfig_to_hashen(int hashconfig)
6719 {
6720 	int hashen = 0;
6721 
6722 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6723 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6724 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6725 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6726 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6727 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6728 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6729 	}
6730 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6731 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6732 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6733 	}
6734 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6735 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6736 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6737 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6738 
6739 	return (hashen);
6740 }
6741 
6742 /* Translates hardware hash types to kernel. */
6743 static int
6744 hashen_to_hashconfig(int hashen)
6745 {
6746 	int hashconfig = 0;
6747 
6748 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6749 		/*
6750 		 * If UDP hashing was enabled it must have been enabled for
6751 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6752 		 * enabling any 4-tuple hash is nonsense configuration.
6753 		 */
6754 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6755 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6756 
6757 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6758 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6759 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6760 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6761 	}
6762 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6763 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6764 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6765 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6766 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6767 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6768 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6769 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6770 
6771 	return (hashconfig);
6772 }
6773 #endif
6774 
6775 /*
6776  * Idempotent.
6777  */
6778 static int
6779 vi_full_init(struct vi_info *vi)
6780 {
6781 	struct adapter *sc = vi->adapter;
6782 	struct sge_rxq *rxq;
6783 	int rc, i, j;
6784 #ifdef RSS
6785 	int nbuckets = rss_getnumbuckets();
6786 	int hashconfig = rss_gethashconfig();
6787 	int extra;
6788 #endif
6789 
6790 	ASSERT_SYNCHRONIZED_OP(sc);
6791 
6792 	/*
6793 	 * Allocate tx/rx/fl queues for this VI.
6794 	 */
6795 	rc = t4_setup_vi_queues(vi);
6796 	if (rc != 0)
6797 		return (rc);
6798 
6799 	/*
6800 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6801 	 */
6802 	if (vi->nrxq > vi->rss_size) {
6803 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6804 		    "some queues will never receive traffic.\n", vi->nrxq,
6805 		    vi->rss_size);
6806 	} else if (vi->rss_size % vi->nrxq) {
6807 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6808 		    "expect uneven traffic distribution.\n", vi->nrxq,
6809 		    vi->rss_size);
6810 	}
6811 #ifdef RSS
6812 	if (vi->nrxq != nbuckets) {
6813 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6814 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6815 	}
6816 #endif
6817 	if (vi->rss == NULL)
6818 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6819 		    M_ZERO | M_WAITOK);
6820 	for (i = 0; i < vi->rss_size;) {
6821 #ifdef RSS
6822 		j = rss_get_indirection_to_bucket(i);
6823 		j %= vi->nrxq;
6824 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6825 		vi->rss[i++] = rxq->iq.abs_id;
6826 #else
6827 		for_each_rxq(vi, j, rxq) {
6828 			vi->rss[i++] = rxq->iq.abs_id;
6829 			if (i == vi->rss_size)
6830 				break;
6831 		}
6832 #endif
6833 	}
6834 
6835 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6836 	    vi->rss, vi->rss_size);
6837 	if (rc != 0) {
6838 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6839 		return (rc);
6840 	}
6841 
6842 #ifdef RSS
6843 	vi->hashen = hashconfig_to_hashen(hashconfig);
6844 
6845 	/*
6846 	 * We may have had to enable some hashes even though the global config
6847 	 * wants them disabled.  This is a potential problem that must be
6848 	 * reported to the user.
6849 	 */
6850 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6851 
6852 	/*
6853 	 * If we consider only the supported hash types, then the enabled hashes
6854 	 * are a superset of the requested hashes.  In other words, there cannot
6855 	 * be any supported hash that was requested but not enabled, but there
6856 	 * can be hashes that were not requested but had to be enabled.
6857 	 */
6858 	extra &= SUPPORTED_RSS_HASHTYPES;
6859 	MPASS((extra & hashconfig) == 0);
6860 
6861 	if (extra) {
6862 		CH_ALERT(vi,
6863 		    "global RSS config (0x%x) cannot be accommodated.\n",
6864 		    hashconfig);
6865 	}
6866 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6867 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6868 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6869 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6870 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6871 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6872 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6873 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6874 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6875 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6876 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6877 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6878 #else
6879 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6880 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6881 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6882 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6883 #endif
6884 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6885 	    0, 0);
6886 	if (rc != 0) {
6887 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6888 		return (rc);
6889 	}
6890 
6891 	return (0);
6892 }
6893 
6894 int
6895 vi_init(struct vi_info *vi)
6896 {
6897 	int rc;
6898 
6899 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6900 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6901 	    ("%s: VI_INIT_DONE already", __func__));
6902 
6903 	rc = vi_full_init(vi);
6904 	if (rc != 0)
6905 		vi_full_uninit(vi);
6906 	else
6907 		vi->flags |= VI_INIT_DONE;
6908 
6909 	return (rc);
6910 }
6911 
6912 /*
6913  * Idempotent.
6914  */
6915 static void
6916 vi_full_uninit(struct vi_info *vi)
6917 {
6918 
6919 	if (vi->flags & VI_INIT_DONE) {
6920 		quiesce_vi(vi);
6921 		free(vi->rss, M_CXGBE);
6922 		free(vi->nm_rss, M_CXGBE);
6923 	}
6924 
6925 	t4_teardown_vi_queues(vi);
6926 	vi->flags &= ~VI_INIT_DONE;
6927 }
6928 
6929 static void
6930 quiesce_txq(struct sge_txq *txq)
6931 {
6932 	struct sge_eq *eq = &txq->eq;
6933 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6934 
6935 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6936 	MPASS(!(eq->flags & EQ_ENABLED));
6937 
6938 	/* Wait for the mp_ring to empty. */
6939 	while (!mp_ring_is_idle(txq->r)) {
6940 		mp_ring_check_drainage(txq->r, 4096);
6941 		pause("rquiesce", 1);
6942 	}
6943 	MPASS(txq->txp.npkt == 0);
6944 
6945 	if (eq->flags & EQ_HW_ALLOCATED) {
6946 		/*
6947 		 * Hardware is alive and working normally.  Wait for it to
6948 		 * finish and then wait for the driver to catch up and reclaim
6949 		 * all descriptors.
6950 		 */
6951 		while (spg->cidx != htobe16(eq->pidx))
6952 			pause("equiesce", 1);
6953 		while (eq->cidx != eq->pidx)
6954 			pause("dquiesce", 1);
6955 	} else {
6956 		/*
6957 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6958 		 * descriptors directly.
6959 		 */
6960 		TXQ_LOCK(txq);
6961 		while (eq->cidx != eq->pidx) {
6962 			struct mbuf *m, *nextpkt;
6963 			struct tx_sdesc *txsd;
6964 
6965 			txsd = &txq->sdesc[eq->cidx];
6966 			for (m = txsd->m; m != NULL; m = nextpkt) {
6967 				nextpkt = m->m_nextpkt;
6968 				m->m_nextpkt = NULL;
6969 				m_freem(m);
6970 			}
6971 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6972 		}
6973 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6974 		TXQ_UNLOCK(txq);
6975 	}
6976 }
6977 
6978 static void
6979 quiesce_wrq(struct sge_wrq *wrq)
6980 {
6981 
6982 	/* XXXTX */
6983 }
6984 
6985 static void
6986 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6987 {
6988 	/* Synchronize with the interrupt handler */
6989 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
6990 		pause("iqfree", 1);
6991 
6992 	if (fl != NULL) {
6993 		MPASS(iq->flags & IQ_HAS_FL);
6994 
6995 		mtx_lock(&sc->sfl_lock);
6996 		FL_LOCK(fl);
6997 		fl->flags |= FL_DOOMED;
6998 		FL_UNLOCK(fl);
6999 		callout_stop(&sc->sfl_callout);
7000 		mtx_unlock(&sc->sfl_lock);
7001 
7002 		KASSERT((fl->flags & FL_STARVING) == 0,
7003 		    ("%s: still starving", __func__));
7004 
7005 		/* Release all buffers if hardware is no longer available. */
7006 		if (!(iq->flags & IQ_HW_ALLOCATED))
7007 			free_fl_buffers(sc, fl);
7008 	}
7009 }
7010 
7011 /*
7012  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7013  * that no new work is being enqueued by the hardware or the driver.  That part
7014  * should be arranged before calling this function.
7015  */
7016 static void
7017 quiesce_vi(struct vi_info *vi)
7018 {
7019 	int i;
7020 	struct adapter *sc = vi->adapter;
7021 	struct sge_rxq *rxq;
7022 	struct sge_txq *txq;
7023 #ifdef TCP_OFFLOAD
7024 	struct sge_ofld_rxq *ofld_rxq;
7025 #endif
7026 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7027 	struct sge_ofld_txq *ofld_txq;
7028 #endif
7029 
7030 	if (!(vi->flags & VI_INIT_DONE))
7031 		return;
7032 
7033 	for_each_txq(vi, i, txq) {
7034 		quiesce_txq(txq);
7035 	}
7036 
7037 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7038 	for_each_ofld_txq(vi, i, ofld_txq) {
7039 		quiesce_wrq(&ofld_txq->wrq);
7040 	}
7041 #endif
7042 
7043 	for_each_rxq(vi, i, rxq) {
7044 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7045 	}
7046 
7047 #ifdef TCP_OFFLOAD
7048 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7049 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7050 	}
7051 #endif
7052 }
7053 
7054 static int
7055 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7056     driver_intr_t *handler, void *arg, char *name)
7057 {
7058 	int rc;
7059 
7060 	irq->rid = rid;
7061 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7062 	    RF_SHAREABLE | RF_ACTIVE);
7063 	if (irq->res == NULL) {
7064 		device_printf(sc->dev,
7065 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7066 		return (ENOMEM);
7067 	}
7068 
7069 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7070 	    NULL, handler, arg, &irq->tag);
7071 	if (rc != 0) {
7072 		device_printf(sc->dev,
7073 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7074 		    rid, name, rc);
7075 	} else if (name)
7076 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7077 
7078 	return (rc);
7079 }
7080 
7081 static int
7082 t4_free_irq(struct adapter *sc, struct irq *irq)
7083 {
7084 	if (irq->tag)
7085 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7086 	if (irq->res)
7087 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7088 
7089 	bzero(irq, sizeof(*irq));
7090 
7091 	return (0);
7092 }
7093 
7094 static void
7095 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7096 {
7097 
7098 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7099 	t4_get_regs(sc, buf, regs->len);
7100 }
7101 
7102 #define	A_PL_INDIR_CMD	0x1f8
7103 
7104 #define	S_PL_AUTOINC	31
7105 #define	M_PL_AUTOINC	0x1U
7106 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7107 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7108 
7109 #define	S_PL_VFID	20
7110 #define	M_PL_VFID	0xffU
7111 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7112 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7113 
7114 #define	S_PL_ADDR	0
7115 #define	M_PL_ADDR	0xfffffU
7116 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7117 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7118 
7119 #define	A_PL_INDIR_DATA	0x1fc
7120 
7121 static uint64_t
7122 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7123 {
7124 	u32 stats[2];
7125 
7126 	if (sc->flags & IS_VF) {
7127 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7128 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7129 	} else {
7130 		mtx_assert(&sc->reg_lock, MA_OWNED);
7131 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7132 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7133 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7134 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7135 	}
7136 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7137 }
7138 
7139 static void
7140 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7141 {
7142 
7143 #define GET_STAT(name) \
7144 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7145 
7146 	if (!(sc->flags & IS_VF))
7147 		mtx_lock(&sc->reg_lock);
7148 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7149 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7150 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7151 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7152 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7153 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7154 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7155 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7156 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7157 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7158 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7159 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7160 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7161 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7162 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7163 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7164 	if (!(sc->flags & IS_VF))
7165 		mtx_unlock(&sc->reg_lock);
7166 
7167 #undef GET_STAT
7168 }
7169 
7170 static void
7171 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7172 {
7173 	int reg;
7174 
7175 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7176 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7177 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7178 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7179 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7180 }
7181 
7182 static void
7183 vi_refresh_stats(struct vi_info *vi)
7184 {
7185 	struct timeval tv;
7186 	const struct timeval interval = {0, 250000};	/* 250ms */
7187 
7188 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7189 
7190 	if (vi->flags & VI_SKIP_STATS)
7191 		return;
7192 
7193 	getmicrotime(&tv);
7194 	timevalsub(&tv, &interval);
7195 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7196 		return;
7197 
7198 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7199 	getmicrotime(&vi->last_refreshed);
7200 }
7201 
7202 static void
7203 cxgbe_refresh_stats(struct vi_info *vi)
7204 {
7205 	u_int i, v, tnl_cong_drops, chan_map;
7206 	struct timeval tv;
7207 	const struct timeval interval = {0, 250000};	/* 250ms */
7208 	struct port_info *pi;
7209 	struct adapter *sc;
7210 
7211 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7212 
7213 	if (vi->flags & VI_SKIP_STATS)
7214 		return;
7215 
7216 	getmicrotime(&tv);
7217 	timevalsub(&tv, &interval);
7218 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7219 		return;
7220 
7221 	pi = vi->pi;
7222 	sc = vi->adapter;
7223 	tnl_cong_drops = 0;
7224 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7225 	chan_map = pi->rx_e_chan_map;
7226 	while (chan_map) {
7227 		i = ffs(chan_map) - 1;
7228 		mtx_lock(&sc->reg_lock);
7229 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7230 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7231 		mtx_unlock(&sc->reg_lock);
7232 		tnl_cong_drops += v;
7233 		chan_map &= ~(1 << i);
7234 	}
7235 	pi->tnl_cong_drops = tnl_cong_drops;
7236 	getmicrotime(&vi->last_refreshed);
7237 }
7238 
7239 static void
7240 cxgbe_tick(void *arg)
7241 {
7242 	struct vi_info *vi = arg;
7243 
7244 	MPASS(IS_MAIN_VI(vi));
7245 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7246 
7247 	cxgbe_refresh_stats(vi);
7248 	callout_schedule(&vi->tick, hz);
7249 }
7250 
7251 static void
7252 vi_tick(void *arg)
7253 {
7254 	struct vi_info *vi = arg;
7255 
7256 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7257 
7258 	vi_refresh_stats(vi);
7259 	callout_schedule(&vi->tick, hz);
7260 }
7261 
7262 /*
7263  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7264  */
7265 static char *caps_decoder[] = {
7266 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7267 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7268 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7269 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7270 	    "\006HASHFILTER\007ETHOFLD",
7271 	"\20\001TOE",					/* 4: TOE */
7272 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7273 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7274 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7275 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7276 	    "\007T10DIF"
7277 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7278 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7279 	    "\004TLS_HW",
7280 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7281 		    "\004PO_INITIATOR\005PO_TARGET",
7282 };
7283 
7284 void
7285 t4_sysctls(struct adapter *sc)
7286 {
7287 	struct sysctl_ctx_list *ctx = &sc->ctx;
7288 	struct sysctl_oid *oid;
7289 	struct sysctl_oid_list *children, *c0;
7290 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7291 
7292 	/*
7293 	 * dev.t4nex.X.
7294 	 */
7295 	oid = device_get_sysctl_tree(sc->dev);
7296 	c0 = children = SYSCTL_CHILDREN(oid);
7297 
7298 	sc->sc_do_rxcopy = 1;
7299 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7300 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7301 
7302 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7303 	    sc->params.nports, "# of ports");
7304 
7305 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7306 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7307 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7308 	    "available doorbells");
7309 
7310 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7311 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7312 
7313 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7314 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7315 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7316 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7317 
7318 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7319 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7320 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7321 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7322 
7323 	t4_sge_sysctls(sc, ctx, children);
7324 
7325 	sc->lro_timeout = 100;
7326 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7327 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7328 
7329 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7330 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7331 
7332 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7333 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7334 
7335 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7336 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7337 
7338 	if (sc->flags & IS_VF)
7339 		return;
7340 
7341 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7342 	    NULL, chip_rev(sc), "chip hardware revision");
7343 
7344 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7345 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7346 
7347 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7348 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7349 
7350 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7351 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7352 
7353 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7354 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7355 
7356 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7357 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7358 
7359 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7360 	    sc->er_version, 0, "expansion ROM version");
7361 
7362 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7363 	    sc->bs_version, 0, "bootstrap firmware version");
7364 
7365 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7366 	    NULL, sc->params.scfg_vers, "serial config version");
7367 
7368 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7369 	    NULL, sc->params.vpd_vers, "VPD version");
7370 
7371 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7372 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7373 
7374 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7375 	    sc->cfcsum, "config file checksum");
7376 
7377 #define SYSCTL_CAP(name, n, text) \
7378 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7379 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7380 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7381 	    "available " text " capabilities")
7382 
7383 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7384 	SYSCTL_CAP(linkcaps, 1, "link");
7385 	SYSCTL_CAP(switchcaps, 2, "switch");
7386 	SYSCTL_CAP(niccaps, 3, "NIC");
7387 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7388 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7389 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7390 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7391 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7392 #undef SYSCTL_CAP
7393 
7394 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7395 	    NULL, sc->tids.nftids, "number of filters");
7396 
7397 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7398 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7399 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7400 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7401 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7402 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7403 
7404 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7405 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7406 	    sysctl_loadavg, "A",
7407 	    "microprocessor load averages (debug firmwares only)");
7408 
7409 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7410 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7411 	    "I", "core Vdd (in mV)");
7412 
7413 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7414 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7415 	    sysctl_cpus, "A", "local CPUs");
7416 
7417 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7418 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7419 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7420 
7421 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7422 	    &sc->swintr, 0, "software triggered interrupts");
7423 
7424 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7425 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7426 	    "1 = reset adapter, 0 = zero reset counter");
7427 
7428 	/*
7429 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7430 	 */
7431 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7432 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7433 	    "logs and miscellaneous information");
7434 	children = SYSCTL_CHILDREN(oid);
7435 
7436 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7437 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7438 	    sysctl_cctrl, "A", "congestion control");
7439 
7440 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7441 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7442 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7443 
7444 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7445 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7446 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7447 
7448 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7449 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7450 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7451 
7452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7453 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7454 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7455 
7456 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7457 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7458 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7459 
7460 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7461 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7462 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7463 
7464 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7465 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7466 	    sysctl_cim_la, "A", "CIM logic analyzer");
7467 
7468 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7469 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7470 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7471 
7472 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7473 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7474 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7475 
7476 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7477 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7478 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7479 
7480 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7481 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7482 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7483 
7484 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7485 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7486 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7487 
7488 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7489 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7490 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7491 
7492 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7493 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7494 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7495 
7496 	if (chip_id(sc) > CHELSIO_T4) {
7497 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7498 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7499 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7500 		    "CIM OBQ 6 (SGE0-RX)");
7501 
7502 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7503 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7504 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7505 		    "CIM OBQ 7 (SGE1-RX)");
7506 	}
7507 
7508 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7509 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7510 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7511 
7512 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7513 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7514 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7515 
7516 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7517 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7518 	    sysctl_cpl_stats, "A", "CPL statistics");
7519 
7520 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7521 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7522 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7523 
7524 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7525 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7526 	    sysctl_tid_stats, "A", "tid stats");
7527 
7528 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7529 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7530 	    sysctl_devlog, "A", "firmware's device log");
7531 
7532 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7533 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7534 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7535 
7536 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7537 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7538 	    sysctl_hw_sched, "A", "hardware scheduler ");
7539 
7540 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7541 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7542 	    sysctl_l2t, "A", "hardware L2 table");
7543 
7544 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7545 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7546 	    sysctl_smt, "A", "hardware source MAC table");
7547 
7548 #ifdef INET6
7549 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7550 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7551 	    sysctl_clip, "A", "active CLIP table entries");
7552 #endif
7553 
7554 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7555 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7556 	    sysctl_lb_stats, "A", "loopback statistics");
7557 
7558 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7559 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7560 	    sysctl_meminfo, "A", "memory regions");
7561 
7562 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7563 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7564 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7565 	    "A", "MPS TCAM entries");
7566 
7567 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7568 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7569 	    sysctl_path_mtus, "A", "path MTUs");
7570 
7571 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7572 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7573 	    sysctl_pm_stats, "A", "PM statistics");
7574 
7575 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7576 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7577 	    sysctl_rdma_stats, "A", "RDMA statistics");
7578 
7579 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7580 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7581 	    sysctl_tcp_stats, "A", "TCP statistics");
7582 
7583 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7584 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7585 	    sysctl_tids, "A", "TID information");
7586 
7587 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7588 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7589 	    sysctl_tp_err_stats, "A", "TP error statistics");
7590 
7591 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7592 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7593 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7594 
7595 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7596 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7597 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7598 
7599 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7600 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7601 	    sysctl_tp_la, "A", "TP logic analyzer");
7602 
7603 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7604 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7605 	    sysctl_tx_rate, "A", "Tx rate");
7606 
7607 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7608 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7609 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7610 
7611 	if (chip_id(sc) >= CHELSIO_T5) {
7612 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7613 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7614 		    sysctl_wcwr_stats, "A", "write combined work requests");
7615 	}
7616 
7617 #ifdef KERN_TLS
7618 	if (is_ktls(sc)) {
7619 		/*
7620 		 * dev.t4nex.0.tls.
7621 		 */
7622 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7623 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7624 		children = SYSCTL_CHILDREN(oid);
7625 
7626 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7627 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7628 		    "keys in work requests (1) or attempt to store TLS keys "
7629 		    "in card memory.");
7630 
7631 		if (is_t6(sc))
7632 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7633 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7634 			    "combine TCB field updates with TLS record work "
7635 			    "requests.");
7636 	}
7637 #endif
7638 
7639 #ifdef TCP_OFFLOAD
7640 	if (is_offload(sc)) {
7641 		int i;
7642 		char s[4];
7643 
7644 		/*
7645 		 * dev.t4nex.X.toe.
7646 		 */
7647 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7648 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7649 		children = SYSCTL_CHILDREN(oid);
7650 
7651 		sc->tt.cong_algorithm = -1;
7652 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7653 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7654 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7655 		    "3 = highspeed)");
7656 
7657 		sc->tt.sndbuf = -1;
7658 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7659 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7660 
7661 		sc->tt.ddp = 0;
7662 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7663 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7664 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7665 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7666 
7667 		sc->tt.rx_coalesce = -1;
7668 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7669 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7670 
7671 		sc->tt.tls = 0;
7672 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7673 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7674 		    "Inline TLS allowed");
7675 
7676 		sc->tt.tx_align = -1;
7677 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7678 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7679 
7680 		sc->tt.tx_zcopy = 0;
7681 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7682 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7683 		    "Enable zero-copy aio_write(2)");
7684 
7685 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7686 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7687 		    "cop_managed_offloading", CTLFLAG_RW,
7688 		    &sc->tt.cop_managed_offloading, 0,
7689 		    "COP (Connection Offload Policy) controls all TOE offload");
7690 
7691 		sc->tt.autorcvbuf_inc = 16 * 1024;
7692 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7693 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7694 		    "autorcvbuf increment");
7695 
7696 		sc->tt.update_hc_on_pmtu_change = 1;
7697 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7698 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7699 		    &sc->tt.update_hc_on_pmtu_change, 0,
7700 		    "Update hostcache entry if the PMTU changes");
7701 
7702 		sc->tt.iso = 1;
7703 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7704 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7705 
7706 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7707 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7708 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7709 
7710 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7711 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7712 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7713 
7714 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7715 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7716 		    sysctl_tp_tick, "A", "DACK tick (us)");
7717 
7718 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7719 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7720 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7721 
7722 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7723 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7724 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7725 		    "Minimum retransmit interval (us)");
7726 
7727 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7728 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7729 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7730 		    "Maximum retransmit interval (us)");
7731 
7732 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7733 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7734 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7735 		    "Persist timer min (us)");
7736 
7737 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7738 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7739 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7740 		    "Persist timer max (us)");
7741 
7742 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7743 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7744 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7745 		    "Keepalive idle timer (us)");
7746 
7747 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7748 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7749 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7750 		    "Keepalive interval timer (us)");
7751 
7752 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7753 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7754 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7755 
7756 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7757 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7758 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7759 		    "FINWAIT2 timer (us)");
7760 
7761 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7762 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7763 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7764 		    "Number of SYN retransmissions before abort");
7765 
7766 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7767 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7768 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7769 		    "Number of retransmissions before abort");
7770 
7771 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7772 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7773 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7774 		    "Number of keepalive probes before abort");
7775 
7776 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7777 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7778 		    "TOE retransmit backoffs");
7779 		children = SYSCTL_CHILDREN(oid);
7780 		for (i = 0; i < 16; i++) {
7781 			snprintf(s, sizeof(s), "%u", i);
7782 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7783 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7784 			    i, sysctl_tp_backoff, "IU",
7785 			    "TOE retransmit backoff");
7786 		}
7787 	}
7788 #endif
7789 }
7790 
7791 void
7792 vi_sysctls(struct vi_info *vi)
7793 {
7794 	struct sysctl_ctx_list *ctx = &vi->ctx;
7795 	struct sysctl_oid *oid;
7796 	struct sysctl_oid_list *children;
7797 
7798 	/*
7799 	 * dev.v?(cxgbe|cxl).X.
7800 	 */
7801 	oid = device_get_sysctl_tree(vi->dev);
7802 	children = SYSCTL_CHILDREN(oid);
7803 
7804 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7805 	    vi->viid, "VI identifer");
7806 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7807 	    &vi->nrxq, 0, "# of rx queues");
7808 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7809 	    &vi->ntxq, 0, "# of tx queues");
7810 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7811 	    &vi->first_rxq, 0, "index of first rx queue");
7812 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7813 	    &vi->first_txq, 0, "index of first tx queue");
7814 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7815 	    vi->rss_base, "start of RSS indirection table");
7816 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7817 	    vi->rss_size, "size of RSS indirection table");
7818 
7819 	if (IS_MAIN_VI(vi)) {
7820 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7821 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7822 		    sysctl_noflowq, "IU",
7823 		    "Reserve queue 0 for non-flowid packets");
7824 	}
7825 
7826 	if (vi->adapter->flags & IS_VF) {
7827 		MPASS(vi->flags & TX_USES_VM_WR);
7828 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7829 		    NULL, 1, "use VM work requests for transmit");
7830 	} else {
7831 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7832 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7833 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7834 	}
7835 
7836 #ifdef TCP_OFFLOAD
7837 	if (vi->nofldrxq != 0) {
7838 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7839 		    &vi->nofldrxq, 0,
7840 		    "# of rx queues for offloaded TCP connections");
7841 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7842 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7843 		    "index of first TOE rx queue");
7844 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7845 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7846 		    sysctl_holdoff_tmr_idx_ofld, "I",
7847 		    "holdoff timer index for TOE queues");
7848 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7849 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7850 		    sysctl_holdoff_pktc_idx_ofld, "I",
7851 		    "holdoff packet counter index for TOE queues");
7852 	}
7853 #endif
7854 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7855 	if (vi->nofldtxq != 0) {
7856 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7857 		    &vi->nofldtxq, 0,
7858 		    "# of tx queues for TOE/ETHOFLD");
7859 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7860 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7861 		    "index of first TOE/ETHOFLD tx queue");
7862 	}
7863 #endif
7864 #ifdef DEV_NETMAP
7865 	if (vi->nnmrxq != 0) {
7866 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7867 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7868 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7869 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7870 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7871 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7872 		    "index of first netmap rx queue");
7873 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7874 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7875 		    "index of first netmap tx queue");
7876 	}
7877 #endif
7878 
7879 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7880 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7881 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7882 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7883 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7884 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7885 
7886 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7887 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7888 	    sysctl_qsize_rxq, "I", "rx queue size");
7889 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7890 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7891 	    sysctl_qsize_txq, "I", "tx queue size");
7892 }
7893 
7894 static void
7895 cxgbe_sysctls(struct port_info *pi)
7896 {
7897 	struct sysctl_ctx_list *ctx = &pi->ctx;
7898 	struct sysctl_oid *oid;
7899 	struct sysctl_oid_list *children, *children2;
7900 	struct adapter *sc = pi->adapter;
7901 	int i;
7902 	char name[16];
7903 	static char *tc_flags = {"\20\1USER"};
7904 
7905 	/*
7906 	 * dev.cxgbe.X.
7907 	 */
7908 	oid = device_get_sysctl_tree(pi->dev);
7909 	children = SYSCTL_CHILDREN(oid);
7910 
7911 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7912 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7913 	    sysctl_linkdnrc, "A", "reason why link is down");
7914 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7915 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7916 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7917 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7918 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7919 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7920 		    sysctl_btphy, "I", "PHY firmware version");
7921 	}
7922 
7923 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7924 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7925 	    sysctl_pause_settings, "A",
7926 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7927 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7928 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7929 	    "FEC in use on the link");
7930 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7931 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7932 	    sysctl_requested_fec, "A",
7933 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7934 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7935 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7936 	    "FEC recommended by the cable/transceiver");
7937 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7938 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7939 	    sysctl_autoneg, "I",
7940 	    "autonegotiation (-1 = not supported)");
7941 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7942 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7943 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7944 
7945 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7946 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7947 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7948 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7949 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7950 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7951 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7952 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7953 
7954 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7955 	    port_top_speed(pi), "max speed (in Gbps)");
7956 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7957 	    pi->mps_bg_map, "MPS buffer group map");
7958 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7959 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7960 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7961 	    pi->rx_c_chan, "TP rx c-channel");
7962 
7963 	if (sc->flags & IS_VF)
7964 		return;
7965 
7966 	/*
7967 	 * dev.(cxgbe|cxl).X.tc.
7968 	 */
7969 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7970 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7971 	    "Tx scheduler traffic classes (cl_rl)");
7972 	children2 = SYSCTL_CHILDREN(oid);
7973 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7974 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7975 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7976 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7977 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7978 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7979 	for (i = 0; i < sc->params.nsched_cls; i++) {
7980 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7981 
7982 		snprintf(name, sizeof(name), "%d", i);
7983 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7984 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7985 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7986 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7987 		    CTLFLAG_RD, &tc->state, 0, "current state");
7988 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
7989 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
7990 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
7991 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
7992 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
7993 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
7994 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7995 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
7996 		    "traffic class parameters");
7997 	}
7998 
7999 	/*
8000 	 * dev.cxgbe.X.stats.
8001 	 */
8002 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8003 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8004 	children = SYSCTL_CHILDREN(oid);
8005 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8006 	    &pi->tx_parse_error, 0,
8007 	    "# of tx packets with invalid length or # of segments");
8008 
8009 #define T4_REGSTAT(name, stat, desc) \
8010     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8011         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8012 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
8013 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
8014         sysctl_handle_t4_reg64, "QU", desc)
8015 
8016 /* We get these from port_stats and they may be stale by up to 1s */
8017 #define T4_PORTSTAT(name, desc) \
8018 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8019 	    &pi->stats.name, desc)
8020 
8021 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8022 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8023 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8024 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8025 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8026 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8027 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8028 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8029 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8030 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8031 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8032 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8033 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8034 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8035 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8036 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8037 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8038 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8039 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8040 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8041 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8042 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8043 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8044 
8045 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8046 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8047 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8048 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8049 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8050 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8051 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8052 	if (is_t6(sc)) {
8053 		T4_PORTSTAT(rx_fcs_err,
8054 		    "# of frames received with bad FCS since last link up");
8055 	} else {
8056 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8057 		    "# of frames received with bad FCS");
8058 	}
8059 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8060 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8061 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8062 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8063 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8064 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8065 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8066 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8067 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8068 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8069 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8070 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8071 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8072 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8073 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8074 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8075 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8076 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8077 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8078 
8079 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8080 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8081 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8082 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8083 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8084 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8085 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8086 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8087 
8088 #undef T4_REGSTAT
8089 #undef T4_PORTSTAT
8090 }
8091 
8092 static int
8093 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8094 {
8095 	int rc, *i, space = 0;
8096 	struct sbuf sb;
8097 
8098 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8099 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8100 		if (space)
8101 			sbuf_printf(&sb, " ");
8102 		sbuf_printf(&sb, "%d", *i);
8103 		space = 1;
8104 	}
8105 	rc = sbuf_finish(&sb);
8106 	sbuf_delete(&sb);
8107 	return (rc);
8108 }
8109 
8110 static int
8111 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8112 {
8113 	int rc;
8114 	struct sbuf *sb;
8115 
8116 	rc = sysctl_wire_old_buffer(req, 0);
8117 	if (rc != 0)
8118 		return(rc);
8119 
8120 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8121 	if (sb == NULL)
8122 		return (ENOMEM);
8123 
8124 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8125 	rc = sbuf_finish(sb);
8126 	sbuf_delete(sb);
8127 
8128 	return (rc);
8129 }
8130 
8131 static int
8132 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8133 {
8134 	int rc;
8135 	struct sbuf *sb;
8136 
8137 	rc = sysctl_wire_old_buffer(req, 0);
8138 	if (rc != 0)
8139 		return(rc);
8140 
8141 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8142 	if (sb == NULL)
8143 		return (ENOMEM);
8144 
8145 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8146 	rc = sbuf_finish(sb);
8147 	sbuf_delete(sb);
8148 
8149 	return (rc);
8150 }
8151 
8152 static int
8153 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8154 {
8155 	struct port_info *pi = arg1;
8156 	int op = arg2;
8157 	struct adapter *sc = pi->adapter;
8158 	u_int v;
8159 	int rc;
8160 
8161 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8162 	if (rc)
8163 		return (rc);
8164 	if (hw_off_limits(sc))
8165 		rc = ENXIO;
8166 	else {
8167 		/* XXX: magic numbers */
8168 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8169 		    op ? 0x20 : 0xc820, &v);
8170 	}
8171 	end_synchronized_op(sc, 0);
8172 	if (rc)
8173 		return (rc);
8174 	if (op == 0)
8175 		v /= 256;
8176 
8177 	rc = sysctl_handle_int(oidp, &v, 0, req);
8178 	return (rc);
8179 }
8180 
8181 static int
8182 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8183 {
8184 	struct vi_info *vi = arg1;
8185 	int rc, val;
8186 
8187 	val = vi->rsrv_noflowq;
8188 	rc = sysctl_handle_int(oidp, &val, 0, req);
8189 	if (rc != 0 || req->newptr == NULL)
8190 		return (rc);
8191 
8192 	if ((val >= 1) && (vi->ntxq > 1))
8193 		vi->rsrv_noflowq = 1;
8194 	else
8195 		vi->rsrv_noflowq = 0;
8196 
8197 	return (rc);
8198 }
8199 
8200 static int
8201 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8202 {
8203 	struct vi_info *vi = arg1;
8204 	struct adapter *sc = vi->adapter;
8205 	int rc, val, i;
8206 
8207 	MPASS(!(sc->flags & IS_VF));
8208 
8209 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8210 	rc = sysctl_handle_int(oidp, &val, 0, req);
8211 	if (rc != 0 || req->newptr == NULL)
8212 		return (rc);
8213 
8214 	if (val != 0 && val != 1)
8215 		return (EINVAL);
8216 
8217 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8218 	    "t4txvm");
8219 	if (rc)
8220 		return (rc);
8221 	if (hw_off_limits(sc))
8222 		rc = ENXIO;
8223 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8224 		/*
8225 		 * We don't want parse_pkt to run with one setting (VF or PF)
8226 		 * and then eth_tx to see a different setting but still use
8227 		 * stale information calculated by parse_pkt.
8228 		 */
8229 		rc = EBUSY;
8230 	} else {
8231 		struct port_info *pi = vi->pi;
8232 		struct sge_txq *txq;
8233 		uint32_t ctrl0;
8234 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8235 
8236 		if (val) {
8237 			vi->flags |= TX_USES_VM_WR;
8238 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8239 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8240 			    V_TXPKT_INTF(pi->tx_chan));
8241 			if (!(sc->flags & IS_VF))
8242 				npkt--;
8243 		} else {
8244 			vi->flags &= ~TX_USES_VM_WR;
8245 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8246 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8247 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8248 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8249 		}
8250 		for_each_txq(vi, i, txq) {
8251 			txq->cpl_ctrl0 = ctrl0;
8252 			txq->txp.max_npkt = npkt;
8253 		}
8254 	}
8255 	end_synchronized_op(sc, LOCK_HELD);
8256 	return (rc);
8257 }
8258 
8259 static int
8260 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8261 {
8262 	struct vi_info *vi = arg1;
8263 	struct adapter *sc = vi->adapter;
8264 	int idx, rc, i;
8265 	struct sge_rxq *rxq;
8266 	uint8_t v;
8267 
8268 	idx = vi->tmr_idx;
8269 
8270 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8271 	if (rc != 0 || req->newptr == NULL)
8272 		return (rc);
8273 
8274 	if (idx < 0 || idx >= SGE_NTIMERS)
8275 		return (EINVAL);
8276 
8277 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8278 	    "t4tmr");
8279 	if (rc)
8280 		return (rc);
8281 
8282 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8283 	for_each_rxq(vi, i, rxq) {
8284 #ifdef atomic_store_rel_8
8285 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8286 #else
8287 		rxq->iq.intr_params = v;
8288 #endif
8289 	}
8290 	vi->tmr_idx = idx;
8291 
8292 	end_synchronized_op(sc, LOCK_HELD);
8293 	return (0);
8294 }
8295 
8296 static int
8297 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8298 {
8299 	struct vi_info *vi = arg1;
8300 	struct adapter *sc = vi->adapter;
8301 	int idx, rc;
8302 
8303 	idx = vi->pktc_idx;
8304 
8305 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8306 	if (rc != 0 || req->newptr == NULL)
8307 		return (rc);
8308 
8309 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8310 		return (EINVAL);
8311 
8312 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8313 	    "t4pktc");
8314 	if (rc)
8315 		return (rc);
8316 
8317 	if (vi->flags & VI_INIT_DONE)
8318 		rc = EBUSY; /* cannot be changed once the queues are created */
8319 	else
8320 		vi->pktc_idx = idx;
8321 
8322 	end_synchronized_op(sc, LOCK_HELD);
8323 	return (rc);
8324 }
8325 
8326 static int
8327 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8328 {
8329 	struct vi_info *vi = arg1;
8330 	struct adapter *sc = vi->adapter;
8331 	int qsize, rc;
8332 
8333 	qsize = vi->qsize_rxq;
8334 
8335 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8336 	if (rc != 0 || req->newptr == NULL)
8337 		return (rc);
8338 
8339 	if (qsize < 128 || (qsize & 7))
8340 		return (EINVAL);
8341 
8342 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8343 	    "t4rxqs");
8344 	if (rc)
8345 		return (rc);
8346 
8347 	if (vi->flags & VI_INIT_DONE)
8348 		rc = EBUSY; /* cannot be changed once the queues are created */
8349 	else
8350 		vi->qsize_rxq = qsize;
8351 
8352 	end_synchronized_op(sc, LOCK_HELD);
8353 	return (rc);
8354 }
8355 
8356 static int
8357 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8358 {
8359 	struct vi_info *vi = arg1;
8360 	struct adapter *sc = vi->adapter;
8361 	int qsize, rc;
8362 
8363 	qsize = vi->qsize_txq;
8364 
8365 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8366 	if (rc != 0 || req->newptr == NULL)
8367 		return (rc);
8368 
8369 	if (qsize < 128 || qsize > 65536)
8370 		return (EINVAL);
8371 
8372 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8373 	    "t4txqs");
8374 	if (rc)
8375 		return (rc);
8376 
8377 	if (vi->flags & VI_INIT_DONE)
8378 		rc = EBUSY; /* cannot be changed once the queues are created */
8379 	else
8380 		vi->qsize_txq = qsize;
8381 
8382 	end_synchronized_op(sc, LOCK_HELD);
8383 	return (rc);
8384 }
8385 
8386 static int
8387 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8388 {
8389 	struct port_info *pi = arg1;
8390 	struct adapter *sc = pi->adapter;
8391 	struct link_config *lc = &pi->link_cfg;
8392 	int rc;
8393 
8394 	if (req->newptr == NULL) {
8395 		struct sbuf *sb;
8396 		static char *bits = "\20\1RX\2TX\3AUTO";
8397 
8398 		rc = sysctl_wire_old_buffer(req, 0);
8399 		if (rc != 0)
8400 			return(rc);
8401 
8402 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8403 		if (sb == NULL)
8404 			return (ENOMEM);
8405 
8406 		if (lc->link_ok) {
8407 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8408 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8409 		} else {
8410 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8411 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8412 		}
8413 		rc = sbuf_finish(sb);
8414 		sbuf_delete(sb);
8415 	} else {
8416 		char s[2];
8417 		int n;
8418 
8419 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8420 		    PAUSE_AUTONEG));
8421 		s[1] = 0;
8422 
8423 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8424 		if (rc != 0)
8425 			return(rc);
8426 
8427 		if (s[1] != 0)
8428 			return (EINVAL);
8429 		if (s[0] < '0' || s[0] > '9')
8430 			return (EINVAL);	/* not a number */
8431 		n = s[0] - '0';
8432 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8433 			return (EINVAL);	/* some other bit is set too */
8434 
8435 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8436 		    "t4PAUSE");
8437 		if (rc)
8438 			return (rc);
8439 		if (!hw_off_limits(sc)) {
8440 			PORT_LOCK(pi);
8441 			lc->requested_fc = n;
8442 			fixup_link_config(pi);
8443 			if (pi->up_vis > 0)
8444 				rc = apply_link_config(pi);
8445 			set_current_media(pi);
8446 			PORT_UNLOCK(pi);
8447 		}
8448 		end_synchronized_op(sc, 0);
8449 	}
8450 
8451 	return (rc);
8452 }
8453 
8454 static int
8455 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8456 {
8457 	struct port_info *pi = arg1;
8458 	struct link_config *lc = &pi->link_cfg;
8459 	int rc;
8460 	struct sbuf *sb;
8461 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8462 
8463 	rc = sysctl_wire_old_buffer(req, 0);
8464 	if (rc != 0)
8465 		return(rc);
8466 
8467 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8468 	if (sb == NULL)
8469 		return (ENOMEM);
8470 	if (lc->link_ok)
8471 		sbuf_printf(sb, "%b", lc->fec, bits);
8472 	else
8473 		sbuf_printf(sb, "no link");
8474 	rc = sbuf_finish(sb);
8475 	sbuf_delete(sb);
8476 
8477 	return (rc);
8478 }
8479 
8480 static int
8481 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8482 {
8483 	struct port_info *pi = arg1;
8484 	struct adapter *sc = pi->adapter;
8485 	struct link_config *lc = &pi->link_cfg;
8486 	int rc;
8487 	int8_t old;
8488 
8489 	if (req->newptr == NULL) {
8490 		struct sbuf *sb;
8491 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8492 		    "\5RSVD3\6auto\7module";
8493 
8494 		rc = sysctl_wire_old_buffer(req, 0);
8495 		if (rc != 0)
8496 			return(rc);
8497 
8498 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8499 		if (sb == NULL)
8500 			return (ENOMEM);
8501 
8502 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8503 		rc = sbuf_finish(sb);
8504 		sbuf_delete(sb);
8505 	} else {
8506 		char s[8];
8507 		int n;
8508 
8509 		snprintf(s, sizeof(s), "%d",
8510 		    lc->requested_fec == FEC_AUTO ? -1 :
8511 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8512 
8513 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8514 		if (rc != 0)
8515 			return(rc);
8516 
8517 		n = strtol(&s[0], NULL, 0);
8518 		if (n < 0 || n & FEC_AUTO)
8519 			n = FEC_AUTO;
8520 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8521 			return (EINVAL);/* some other bit is set too */
8522 
8523 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8524 		    "t4reqf");
8525 		if (rc)
8526 			return (rc);
8527 		PORT_LOCK(pi);
8528 		old = lc->requested_fec;
8529 		if (n == FEC_AUTO)
8530 			lc->requested_fec = FEC_AUTO;
8531 		else if (n == 0 || n == FEC_NONE)
8532 			lc->requested_fec = FEC_NONE;
8533 		else {
8534 			if ((lc->pcaps |
8535 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8536 			    lc->pcaps) {
8537 				rc = ENOTSUP;
8538 				goto done;
8539 			}
8540 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8541 			    FEC_MODULE);
8542 		}
8543 		if (!hw_off_limits(sc)) {
8544 			fixup_link_config(pi);
8545 			if (pi->up_vis > 0) {
8546 				rc = apply_link_config(pi);
8547 				if (rc != 0) {
8548 					lc->requested_fec = old;
8549 					if (rc == FW_EPROTO)
8550 						rc = ENOTSUP;
8551 				}
8552 			}
8553 		}
8554 done:
8555 		PORT_UNLOCK(pi);
8556 		end_synchronized_op(sc, 0);
8557 	}
8558 
8559 	return (rc);
8560 }
8561 
8562 static int
8563 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8564 {
8565 	struct port_info *pi = arg1;
8566 	struct adapter *sc = pi->adapter;
8567 	struct link_config *lc = &pi->link_cfg;
8568 	int rc;
8569 	int8_t fec;
8570 	struct sbuf *sb;
8571 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8572 
8573 	rc = sysctl_wire_old_buffer(req, 0);
8574 	if (rc != 0)
8575 		return (rc);
8576 
8577 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8578 	if (sb == NULL)
8579 		return (ENOMEM);
8580 
8581 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8582 		rc = EBUSY;
8583 		goto done;
8584 	}
8585 	if (hw_off_limits(sc)) {
8586 		rc = ENXIO;
8587 		goto done;
8588 	}
8589 	PORT_LOCK(pi);
8590 	if (pi->up_vis == 0) {
8591 		/*
8592 		 * If all the interfaces are administratively down the firmware
8593 		 * does not report transceiver changes.  Refresh port info here.
8594 		 * This is the only reason we have a synchronized op in this
8595 		 * function.  Just PORT_LOCK would have been enough otherwise.
8596 		 */
8597 		t4_update_port_info(pi);
8598 	}
8599 
8600 	fec = lc->fec_hint;
8601 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8602 	    !fec_supported(lc->pcaps)) {
8603 		sbuf_printf(sb, "n/a");
8604 	} else {
8605 		if (fec == 0)
8606 			fec = FEC_NONE;
8607 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8608 	}
8609 	rc = sbuf_finish(sb);
8610 	PORT_UNLOCK(pi);
8611 done:
8612 	sbuf_delete(sb);
8613 	end_synchronized_op(sc, 0);
8614 
8615 	return (rc);
8616 }
8617 
8618 static int
8619 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8620 {
8621 	struct port_info *pi = arg1;
8622 	struct adapter *sc = pi->adapter;
8623 	struct link_config *lc = &pi->link_cfg;
8624 	int rc, val;
8625 
8626 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8627 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8628 	else
8629 		val = -1;
8630 	rc = sysctl_handle_int(oidp, &val, 0, req);
8631 	if (rc != 0 || req->newptr == NULL)
8632 		return (rc);
8633 	if (val == 0)
8634 		val = AUTONEG_DISABLE;
8635 	else if (val == 1)
8636 		val = AUTONEG_ENABLE;
8637 	else
8638 		val = AUTONEG_AUTO;
8639 
8640 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8641 	    "t4aneg");
8642 	if (rc)
8643 		return (rc);
8644 	PORT_LOCK(pi);
8645 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8646 		rc = ENOTSUP;
8647 		goto done;
8648 	}
8649 	lc->requested_aneg = val;
8650 	if (!hw_off_limits(sc)) {
8651 		fixup_link_config(pi);
8652 		if (pi->up_vis > 0)
8653 			rc = apply_link_config(pi);
8654 		set_current_media(pi);
8655 	}
8656 done:
8657 	PORT_UNLOCK(pi);
8658 	end_synchronized_op(sc, 0);
8659 	return (rc);
8660 }
8661 
8662 static int
8663 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8664 {
8665 	struct port_info *pi = arg1;
8666 	struct adapter *sc = pi->adapter;
8667 	struct link_config *lc = &pi->link_cfg;
8668 	int rc, val;
8669 
8670 	val = lc->force_fec;
8671 	MPASS(val >= -1 && val <= 1);
8672 	rc = sysctl_handle_int(oidp, &val, 0, req);
8673 	if (rc != 0 || req->newptr == NULL)
8674 		return (rc);
8675 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8676 		return (ENOTSUP);
8677 	if (val < -1 || val > 1)
8678 		return (EINVAL);
8679 
8680 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8681 	if (rc)
8682 		return (rc);
8683 	PORT_LOCK(pi);
8684 	lc->force_fec = val;
8685 	if (!hw_off_limits(sc)) {
8686 		fixup_link_config(pi);
8687 		if (pi->up_vis > 0)
8688 			rc = apply_link_config(pi);
8689 	}
8690 	PORT_UNLOCK(pi);
8691 	end_synchronized_op(sc, 0);
8692 	return (rc);
8693 }
8694 
8695 static int
8696 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8697 {
8698 	struct adapter *sc = arg1;
8699 	int rc, reg = arg2;
8700 	uint64_t val;
8701 
8702 	mtx_lock(&sc->reg_lock);
8703 	if (hw_off_limits(sc))
8704 		rc = ENXIO;
8705 	else {
8706 		rc = 0;
8707 		val = t4_read_reg64(sc, reg);
8708 	}
8709 	mtx_unlock(&sc->reg_lock);
8710 	if (rc == 0)
8711 		rc = sysctl_handle_64(oidp, &val, 0, req);
8712 	return (rc);
8713 }
8714 
8715 static int
8716 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8717 {
8718 	struct adapter *sc = arg1;
8719 	int rc, t;
8720 	uint32_t param, val;
8721 
8722 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8723 	if (rc)
8724 		return (rc);
8725 	if (hw_off_limits(sc))
8726 		rc = ENXIO;
8727 	else {
8728 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8729 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8730 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8731 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8732 	}
8733 	end_synchronized_op(sc, 0);
8734 	if (rc)
8735 		return (rc);
8736 
8737 	/* unknown is returned as 0 but we display -1 in that case */
8738 	t = val == 0 ? -1 : val;
8739 
8740 	rc = sysctl_handle_int(oidp, &t, 0, req);
8741 	return (rc);
8742 }
8743 
8744 static int
8745 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8746 {
8747 	struct adapter *sc = arg1;
8748 	int rc;
8749 	uint32_t param, val;
8750 
8751 	if (sc->params.core_vdd == 0) {
8752 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8753 		    "t4vdd");
8754 		if (rc)
8755 			return (rc);
8756 		if (hw_off_limits(sc))
8757 			rc = ENXIO;
8758 		else {
8759 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8760 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8761 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8762 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8763 			    &param, &val);
8764 		}
8765 		end_synchronized_op(sc, 0);
8766 		if (rc)
8767 			return (rc);
8768 		sc->params.core_vdd = val;
8769 	}
8770 
8771 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8772 }
8773 
8774 static int
8775 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8776 {
8777 	struct adapter *sc = arg1;
8778 	int rc, v;
8779 	uint32_t param, val;
8780 
8781 	v = sc->sensor_resets;
8782 	rc = sysctl_handle_int(oidp, &v, 0, req);
8783 	if (rc != 0 || req->newptr == NULL || v <= 0)
8784 		return (rc);
8785 
8786 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8787 	    chip_id(sc) < CHELSIO_T5)
8788 		return (ENOTSUP);
8789 
8790 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8791 	if (rc)
8792 		return (rc);
8793 	if (hw_off_limits(sc))
8794 		rc = ENXIO;
8795 	else {
8796 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8797 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8798 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8799 		val = 1;
8800 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8801 	}
8802 	end_synchronized_op(sc, 0);
8803 	if (rc == 0)
8804 		sc->sensor_resets++;
8805 	return (rc);
8806 }
8807 
8808 static int
8809 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8810 {
8811 	struct adapter *sc = arg1;
8812 	struct sbuf *sb;
8813 	int rc;
8814 	uint32_t param, val;
8815 
8816 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8817 	if (rc)
8818 		return (rc);
8819 	if (hw_off_limits(sc))
8820 		rc = ENXIO;
8821 	else {
8822 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8823 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8824 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8825 	}
8826 	end_synchronized_op(sc, 0);
8827 	if (rc)
8828 		return (rc);
8829 
8830 	rc = sysctl_wire_old_buffer(req, 0);
8831 	if (rc != 0)
8832 		return (rc);
8833 
8834 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8835 	if (sb == NULL)
8836 		return (ENOMEM);
8837 
8838 	if (val == 0xffffffff) {
8839 		/* Only debug and custom firmwares report load averages. */
8840 		sbuf_printf(sb, "not available");
8841 	} else {
8842 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8843 		    (val >> 16) & 0xff);
8844 	}
8845 	rc = sbuf_finish(sb);
8846 	sbuf_delete(sb);
8847 
8848 	return (rc);
8849 }
8850 
8851 static int
8852 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8853 {
8854 	struct adapter *sc = arg1;
8855 	struct sbuf *sb;
8856 	int rc, i;
8857 	uint16_t incr[NMTUS][NCCTRL_WIN];
8858 	static const char *dec_fac[] = {
8859 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8860 		"0.9375"
8861 	};
8862 
8863 	rc = sysctl_wire_old_buffer(req, 0);
8864 	if (rc != 0)
8865 		return (rc);
8866 
8867 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8868 	if (sb == NULL)
8869 		return (ENOMEM);
8870 
8871 	mtx_lock(&sc->reg_lock);
8872 	if (hw_off_limits(sc))
8873 		rc = ENXIO;
8874 	else
8875 		t4_read_cong_tbl(sc, incr);
8876 	mtx_unlock(&sc->reg_lock);
8877 	if (rc)
8878 		goto done;
8879 
8880 	for (i = 0; i < NCCTRL_WIN; ++i) {
8881 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8882 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8883 		    incr[5][i], incr[6][i], incr[7][i]);
8884 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8885 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8886 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8887 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8888 	}
8889 
8890 	rc = sbuf_finish(sb);
8891 done:
8892 	sbuf_delete(sb);
8893 	return (rc);
8894 }
8895 
8896 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8897 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8898 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8899 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8900 };
8901 
8902 static int
8903 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8904 {
8905 	struct adapter *sc = arg1;
8906 	struct sbuf *sb;
8907 	int rc, i, n, qid = arg2;
8908 	uint32_t *buf, *p;
8909 	char *qtype;
8910 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8911 
8912 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8913 	    ("%s: bad qid %d\n", __func__, qid));
8914 
8915 	if (qid < CIM_NUM_IBQ) {
8916 		/* inbound queue */
8917 		qtype = "IBQ";
8918 		n = 4 * CIM_IBQ_SIZE;
8919 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8920 		mtx_lock(&sc->reg_lock);
8921 		if (hw_off_limits(sc))
8922 			rc = -ENXIO;
8923 		else
8924 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8925 		mtx_unlock(&sc->reg_lock);
8926 	} else {
8927 		/* outbound queue */
8928 		qtype = "OBQ";
8929 		qid -= CIM_NUM_IBQ;
8930 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8931 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8932 		mtx_lock(&sc->reg_lock);
8933 		if (hw_off_limits(sc))
8934 			rc = -ENXIO;
8935 		else
8936 			rc = t4_read_cim_obq(sc, qid, buf, n);
8937 		mtx_unlock(&sc->reg_lock);
8938 	}
8939 
8940 	if (rc < 0) {
8941 		rc = -rc;
8942 		goto done;
8943 	}
8944 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8945 
8946 	rc = sysctl_wire_old_buffer(req, 0);
8947 	if (rc != 0)
8948 		goto done;
8949 
8950 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8951 	if (sb == NULL) {
8952 		rc = ENOMEM;
8953 		goto done;
8954 	}
8955 
8956 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8957 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8958 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8959 		    p[2], p[3]);
8960 
8961 	rc = sbuf_finish(sb);
8962 	sbuf_delete(sb);
8963 done:
8964 	free(buf, M_CXGBE);
8965 	return (rc);
8966 }
8967 
8968 static void
8969 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8970 {
8971 	uint32_t *p;
8972 
8973 	sbuf_printf(sb, "Status   Data      PC%s",
8974 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8975 	    "     LS0Stat  LS0Addr             LS0Data");
8976 
8977 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8978 		if (cfg & F_UPDBGLACAPTPCONLY) {
8979 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8980 			    p[6], p[7]);
8981 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8982 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8983 			    p[4] & 0xff, p[5] >> 8);
8984 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8985 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8986 			    p[1] & 0xf, p[2] >> 4);
8987 		} else {
8988 			sbuf_printf(sb,
8989 			    "\n  %02x   %x%07x %x%07x %08x %08x "
8990 			    "%08x%08x%08x%08x",
8991 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8992 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
8993 			    p[6], p[7]);
8994 		}
8995 	}
8996 }
8997 
8998 static void
8999 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9000 {
9001 	uint32_t *p;
9002 
9003 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9004 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9005 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9006 
9007 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9008 		if (cfg & F_UPDBGLACAPTPCONLY) {
9009 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9010 			    p[3] & 0xff, p[2], p[1], p[0]);
9011 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9012 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9013 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9014 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9015 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9016 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9017 			    p[6] >> 16);
9018 		} else {
9019 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9020 			    "%08x %08x %08x %08x %08x %08x",
9021 			    (p[9] >> 16) & 0xff,
9022 			    p[9] & 0xffff, p[8] >> 16,
9023 			    p[8] & 0xffff, p[7] >> 16,
9024 			    p[7] & 0xffff, p[6] >> 16,
9025 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9026 		}
9027 	}
9028 }
9029 
9030 static int
9031 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9032 {
9033 	uint32_t cfg, *buf;
9034 	int rc;
9035 
9036 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9037 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9038 	    M_ZERO | flags);
9039 	if (buf == NULL)
9040 		return (ENOMEM);
9041 
9042 	mtx_lock(&sc->reg_lock);
9043 	if (hw_off_limits(sc))
9044 		rc = ENXIO;
9045 	else {
9046 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9047 		if (rc == 0)
9048 			rc = -t4_cim_read_la(sc, buf, NULL);
9049 	}
9050 	mtx_unlock(&sc->reg_lock);
9051 	if (rc == 0) {
9052 		if (chip_id(sc) < CHELSIO_T6)
9053 			sbuf_cim_la4(sc, sb, buf, cfg);
9054 		else
9055 			sbuf_cim_la6(sc, sb, buf, cfg);
9056 	}
9057 	free(buf, M_CXGBE);
9058 	return (rc);
9059 }
9060 
9061 static int
9062 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9063 {
9064 	struct adapter *sc = arg1;
9065 	struct sbuf *sb;
9066 	int rc;
9067 
9068 	rc = sysctl_wire_old_buffer(req, 0);
9069 	if (rc != 0)
9070 		return (rc);
9071 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9072 	if (sb == NULL)
9073 		return (ENOMEM);
9074 
9075 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9076 	if (rc == 0)
9077 		rc = sbuf_finish(sb);
9078 	sbuf_delete(sb);
9079 	return (rc);
9080 }
9081 
9082 static void
9083 dump_cim_regs(struct adapter *sc)
9084 {
9085 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9086 	    device_get_nameunit(sc->dev),
9087 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9088 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9089 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9090 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9091 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9092 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9093 	    device_get_nameunit(sc->dev),
9094 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9095 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9096 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9097 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9098 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9099 }
9100 
9101 static void
9102 dump_cimla(struct adapter *sc)
9103 {
9104 	struct sbuf sb;
9105 	int rc;
9106 
9107 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9108 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9109 		    device_get_nameunit(sc->dev));
9110 		return;
9111 	}
9112 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9113 	if (rc == 0) {
9114 		rc = sbuf_finish(&sb);
9115 		if (rc == 0) {
9116 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9117 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9118 		}
9119 	}
9120 	sbuf_delete(&sb);
9121 }
9122 
9123 void
9124 t4_os_cim_err(struct adapter *sc)
9125 {
9126 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9127 }
9128 
9129 static int
9130 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9131 {
9132 	struct adapter *sc = arg1;
9133 	u_int i;
9134 	struct sbuf *sb;
9135 	uint32_t *buf, *p;
9136 	int rc;
9137 
9138 	rc = sysctl_wire_old_buffer(req, 0);
9139 	if (rc != 0)
9140 		return (rc);
9141 
9142 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9143 	if (sb == NULL)
9144 		return (ENOMEM);
9145 
9146 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9147 	    M_ZERO | M_WAITOK);
9148 
9149 	mtx_lock(&sc->reg_lock);
9150 	if (hw_off_limits(sc))
9151 		rc = ENXIO;
9152 	else
9153 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9154 	mtx_unlock(&sc->reg_lock);
9155 	if (rc)
9156 		goto done;
9157 
9158 	p = buf;
9159 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9160 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9161 		    p[1], p[0]);
9162 	}
9163 
9164 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9165 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9166 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9167 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9168 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9169 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9170 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9171 		    p[0] & 1);
9172 	}
9173 	rc = sbuf_finish(sb);
9174 done:
9175 	sbuf_delete(sb);
9176 	free(buf, M_CXGBE);
9177 	return (rc);
9178 }
9179 
9180 static int
9181 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9182 {
9183 	struct adapter *sc = arg1;
9184 	u_int i;
9185 	struct sbuf *sb;
9186 	uint32_t *buf, *p;
9187 	int rc;
9188 
9189 	rc = sysctl_wire_old_buffer(req, 0);
9190 	if (rc != 0)
9191 		return (rc);
9192 
9193 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9194 	if (sb == NULL)
9195 		return (ENOMEM);
9196 
9197 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9198 	    M_ZERO | M_WAITOK);
9199 
9200 	mtx_lock(&sc->reg_lock);
9201 	if (hw_off_limits(sc))
9202 		rc = ENXIO;
9203 	else
9204 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9205 	mtx_unlock(&sc->reg_lock);
9206 	if (rc)
9207 		goto done;
9208 
9209 	p = buf;
9210 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9211 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9212 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9213 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9214 		    p[4], p[3], p[2], p[1], p[0]);
9215 	}
9216 
9217 	sbuf_printf(sb, "\n\nCntl ID               Data");
9218 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9219 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9220 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9221 	}
9222 
9223 	rc = sbuf_finish(sb);
9224 done:
9225 	sbuf_delete(sb);
9226 	free(buf, M_CXGBE);
9227 	return (rc);
9228 }
9229 
9230 static int
9231 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9232 {
9233 	struct adapter *sc = arg1;
9234 	struct sbuf *sb;
9235 	int rc, i;
9236 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9237 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9238 	uint16_t thres[CIM_NUM_IBQ];
9239 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9240 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9241 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9242 
9243 	cim_num_obq = sc->chip_params->cim_num_obq;
9244 	if (is_t4(sc)) {
9245 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9246 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9247 	} else {
9248 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9249 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9250 	}
9251 	nq = CIM_NUM_IBQ + cim_num_obq;
9252 
9253 	mtx_lock(&sc->reg_lock);
9254 	if (hw_off_limits(sc))
9255 		rc = ENXIO;
9256 	else {
9257 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9258 		if (rc == 0) {
9259 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9260 			    obq_wr);
9261 			if (rc == 0)
9262 				t4_read_cimq_cfg(sc, base, size, thres);
9263 		}
9264 	}
9265 	mtx_unlock(&sc->reg_lock);
9266 	if (rc)
9267 		return (rc);
9268 
9269 	rc = sysctl_wire_old_buffer(req, 0);
9270 	if (rc != 0)
9271 		return (rc);
9272 
9273 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9274 	if (sb == NULL)
9275 		return (ENOMEM);
9276 
9277 	sbuf_printf(sb,
9278 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9279 
9280 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9281 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9282 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9283 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9284 		    G_QUEREMFLITS(p[2]) * 16);
9285 	for ( ; i < nq; i++, p += 4, wr += 2)
9286 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9287 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9288 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9289 		    G_QUEREMFLITS(p[2]) * 16);
9290 
9291 	rc = sbuf_finish(sb);
9292 	sbuf_delete(sb);
9293 
9294 	return (rc);
9295 }
9296 
9297 static int
9298 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9299 {
9300 	struct adapter *sc = arg1;
9301 	struct sbuf *sb;
9302 	int rc;
9303 	struct tp_cpl_stats stats;
9304 
9305 	rc = sysctl_wire_old_buffer(req, 0);
9306 	if (rc != 0)
9307 		return (rc);
9308 
9309 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9310 	if (sb == NULL)
9311 		return (ENOMEM);
9312 
9313 	mtx_lock(&sc->reg_lock);
9314 	if (hw_off_limits(sc))
9315 		rc = ENXIO;
9316 	else
9317 		t4_tp_get_cpl_stats(sc, &stats, 0);
9318 	mtx_unlock(&sc->reg_lock);
9319 	if (rc)
9320 		goto done;
9321 
9322 	if (sc->chip_params->nchan > 2) {
9323 		sbuf_printf(sb, "                 channel 0  channel 1"
9324 		    "  channel 2  channel 3");
9325 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9326 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9327 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9328 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9329 	} else {
9330 		sbuf_printf(sb, "                 channel 0  channel 1");
9331 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9332 		    stats.req[0], stats.req[1]);
9333 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9334 		    stats.rsp[0], stats.rsp[1]);
9335 	}
9336 
9337 	rc = sbuf_finish(sb);
9338 done:
9339 	sbuf_delete(sb);
9340 	return (rc);
9341 }
9342 
9343 static int
9344 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9345 {
9346 	struct adapter *sc = arg1;
9347 	struct sbuf *sb;
9348 	int rc;
9349 	struct tp_usm_stats stats;
9350 
9351 	rc = sysctl_wire_old_buffer(req, 0);
9352 	if (rc != 0)
9353 		return(rc);
9354 
9355 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9356 	if (sb == NULL)
9357 		return (ENOMEM);
9358 
9359 	mtx_lock(&sc->reg_lock);
9360 	if (hw_off_limits(sc))
9361 		rc = ENXIO;
9362 	else
9363 		t4_get_usm_stats(sc, &stats, 1);
9364 	mtx_unlock(&sc->reg_lock);
9365 	if (rc == 0) {
9366 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9367 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9368 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9369 		rc = sbuf_finish(sb);
9370 	}
9371 	sbuf_delete(sb);
9372 
9373 	return (rc);
9374 }
9375 
9376 static int
9377 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9378 {
9379 	struct adapter *sc = arg1;
9380 	struct sbuf *sb;
9381 	int rc;
9382 	struct tp_tid_stats stats;
9383 
9384 	rc = sysctl_wire_old_buffer(req, 0);
9385 	if (rc != 0)
9386 		return(rc);
9387 
9388 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9389 	if (sb == NULL)
9390 		return (ENOMEM);
9391 
9392 	mtx_lock(&sc->reg_lock);
9393 	if (hw_off_limits(sc))
9394 		rc = ENXIO;
9395 	else
9396 		t4_tp_get_tid_stats(sc, &stats, 1);
9397 	mtx_unlock(&sc->reg_lock);
9398 	if (rc == 0) {
9399 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9400 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9401 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9402 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9403 		rc = sbuf_finish(sb);
9404 	}
9405 	sbuf_delete(sb);
9406 
9407 	return (rc);
9408 }
9409 
9410 static const char * const devlog_level_strings[] = {
9411 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9412 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9413 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9414 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9415 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9416 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9417 };
9418 
9419 static const char * const devlog_facility_strings[] = {
9420 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9421 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9422 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9423 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9424 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9425 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9426 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9427 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9428 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9429 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9430 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9431 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9432 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9433 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9434 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9435 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9436 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9437 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9438 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9439 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9440 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9441 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9442 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9443 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9444 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9445 };
9446 
9447 static int
9448 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9449 {
9450 	int i, j, rc, nentries, first = 0;
9451 	struct devlog_params *dparams = &sc->params.devlog;
9452 	struct fw_devlog_e *buf, *e;
9453 	uint64_t ftstamp = UINT64_MAX;
9454 
9455 	if (dparams->addr == 0)
9456 		return (ENXIO);
9457 
9458 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9459 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9460 	if (buf == NULL)
9461 		return (ENOMEM);
9462 
9463 	mtx_lock(&sc->reg_lock);
9464 	if (hw_off_limits(sc))
9465 		rc = ENXIO;
9466 	else
9467 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9468 		    dparams->size);
9469 	mtx_unlock(&sc->reg_lock);
9470 	if (rc != 0)
9471 		goto done;
9472 
9473 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9474 	for (i = 0; i < nentries; i++) {
9475 		e = &buf[i];
9476 
9477 		if (e->timestamp == 0)
9478 			break;	/* end */
9479 
9480 		e->timestamp = be64toh(e->timestamp);
9481 		e->seqno = be32toh(e->seqno);
9482 		for (j = 0; j < 8; j++)
9483 			e->params[j] = be32toh(e->params[j]);
9484 
9485 		if (e->timestamp < ftstamp) {
9486 			ftstamp = e->timestamp;
9487 			first = i;
9488 		}
9489 	}
9490 
9491 	if (buf[first].timestamp == 0)
9492 		goto done;	/* nothing in the log */
9493 
9494 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9495 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9496 
9497 	i = first;
9498 	do {
9499 		e = &buf[i];
9500 		if (e->timestamp == 0)
9501 			break;	/* end */
9502 
9503 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9504 		    e->seqno, e->timestamp,
9505 		    (e->level < nitems(devlog_level_strings) ?
9506 			devlog_level_strings[e->level] : "UNKNOWN"),
9507 		    (e->facility < nitems(devlog_facility_strings) ?
9508 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9509 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9510 		    e->params[2], e->params[3], e->params[4],
9511 		    e->params[5], e->params[6], e->params[7]);
9512 
9513 		if (++i == nentries)
9514 			i = 0;
9515 	} while (i != first);
9516 done:
9517 	free(buf, M_CXGBE);
9518 	return (rc);
9519 }
9520 
9521 static int
9522 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9523 {
9524 	struct adapter *sc = arg1;
9525 	int rc;
9526 	struct sbuf *sb;
9527 
9528 	rc = sysctl_wire_old_buffer(req, 0);
9529 	if (rc != 0)
9530 		return (rc);
9531 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9532 	if (sb == NULL)
9533 		return (ENOMEM);
9534 
9535 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9536 	if (rc == 0)
9537 		rc = sbuf_finish(sb);
9538 	sbuf_delete(sb);
9539 	return (rc);
9540 }
9541 
9542 static void
9543 dump_devlog(struct adapter *sc)
9544 {
9545 	int rc;
9546 	struct sbuf sb;
9547 
9548 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9549 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9550 		    device_get_nameunit(sc->dev));
9551 		return;
9552 	}
9553 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9554 	if (rc == 0) {
9555 		rc = sbuf_finish(&sb);
9556 		if (rc == 0) {
9557 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9558 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9559 		}
9560 	}
9561 	sbuf_delete(&sb);
9562 }
9563 
9564 static int
9565 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9566 {
9567 	struct adapter *sc = arg1;
9568 	struct sbuf *sb;
9569 	int rc;
9570 	struct tp_fcoe_stats stats[MAX_NCHAN];
9571 	int i, nchan = sc->chip_params->nchan;
9572 
9573 	rc = sysctl_wire_old_buffer(req, 0);
9574 	if (rc != 0)
9575 		return (rc);
9576 
9577 	mtx_lock(&sc->reg_lock);
9578 	if (hw_off_limits(sc))
9579 		rc = ENXIO;
9580 	else {
9581 		for (i = 0; i < nchan; i++)
9582 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9583 	}
9584 	mtx_unlock(&sc->reg_lock);
9585 	if (rc != 0)
9586 		return (rc);
9587 
9588 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9589 	if (sb == NULL)
9590 		return (ENOMEM);
9591 
9592 	if (nchan > 2) {
9593 		sbuf_printf(sb, "                   channel 0        channel 1"
9594 		    "        channel 2        channel 3");
9595 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9596 		    stats[0].octets_ddp, stats[1].octets_ddp,
9597 		    stats[2].octets_ddp, stats[3].octets_ddp);
9598 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9599 		    stats[0].frames_ddp, stats[1].frames_ddp,
9600 		    stats[2].frames_ddp, stats[3].frames_ddp);
9601 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9602 		    stats[0].frames_drop, stats[1].frames_drop,
9603 		    stats[2].frames_drop, stats[3].frames_drop);
9604 	} else {
9605 		sbuf_printf(sb, "                   channel 0        channel 1");
9606 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9607 		    stats[0].octets_ddp, stats[1].octets_ddp);
9608 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9609 		    stats[0].frames_ddp, stats[1].frames_ddp);
9610 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9611 		    stats[0].frames_drop, stats[1].frames_drop);
9612 	}
9613 
9614 	rc = sbuf_finish(sb);
9615 	sbuf_delete(sb);
9616 
9617 	return (rc);
9618 }
9619 
9620 static int
9621 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9622 {
9623 	struct adapter *sc = arg1;
9624 	struct sbuf *sb;
9625 	int rc, i;
9626 	unsigned int map, kbps, ipg, mode;
9627 	unsigned int pace_tab[NTX_SCHED];
9628 
9629 	rc = sysctl_wire_old_buffer(req, 0);
9630 	if (rc != 0)
9631 		return (rc);
9632 
9633 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9634 	if (sb == NULL)
9635 		return (ENOMEM);
9636 
9637 	mtx_lock(&sc->reg_lock);
9638 	if (hw_off_limits(sc)) {
9639 		rc = ENXIO;
9640 		goto done;
9641 	}
9642 
9643 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9644 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9645 	t4_read_pace_tbl(sc, pace_tab);
9646 
9647 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9648 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9649 
9650 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9651 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9652 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9653 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9654 		if (kbps)
9655 			sbuf_printf(sb, "%9u     ", kbps);
9656 		else
9657 			sbuf_printf(sb, " disabled     ");
9658 
9659 		if (ipg)
9660 			sbuf_printf(sb, "%13u        ", ipg);
9661 		else
9662 			sbuf_printf(sb, "     disabled        ");
9663 
9664 		if (pace_tab[i])
9665 			sbuf_printf(sb, "%10u", pace_tab[i]);
9666 		else
9667 			sbuf_printf(sb, "  disabled");
9668 	}
9669 	rc = sbuf_finish(sb);
9670 done:
9671 	mtx_unlock(&sc->reg_lock);
9672 	sbuf_delete(sb);
9673 	return (rc);
9674 }
9675 
9676 static int
9677 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9678 {
9679 	struct adapter *sc = arg1;
9680 	struct sbuf *sb;
9681 	int rc, i, j;
9682 	uint64_t *p0, *p1;
9683 	struct lb_port_stats s[2];
9684 	static const char *stat_name[] = {
9685 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9686 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9687 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9688 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9689 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9690 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9691 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9692 	};
9693 
9694 	rc = sysctl_wire_old_buffer(req, 0);
9695 	if (rc != 0)
9696 		return (rc);
9697 
9698 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9699 	if (sb == NULL)
9700 		return (ENOMEM);
9701 
9702 	memset(s, 0, sizeof(s));
9703 
9704 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9705 		mtx_lock(&sc->reg_lock);
9706 		if (hw_off_limits(sc))
9707 			rc = ENXIO;
9708 		else {
9709 			t4_get_lb_stats(sc, i, &s[0]);
9710 			t4_get_lb_stats(sc, i + 1, &s[1]);
9711 		}
9712 		mtx_unlock(&sc->reg_lock);
9713 		if (rc != 0)
9714 			break;
9715 
9716 		p0 = &s[0].octets;
9717 		p1 = &s[1].octets;
9718 		sbuf_printf(sb, "%s                       Loopback %u"
9719 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9720 
9721 		for (j = 0; j < nitems(stat_name); j++)
9722 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9723 				   *p0++, *p1++);
9724 	}
9725 
9726 	rc = sbuf_finish(sb);
9727 	sbuf_delete(sb);
9728 
9729 	return (rc);
9730 }
9731 
9732 static int
9733 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9734 {
9735 	int rc = 0;
9736 	struct port_info *pi = arg1;
9737 	struct link_config *lc = &pi->link_cfg;
9738 	struct sbuf *sb;
9739 
9740 	rc = sysctl_wire_old_buffer(req, 0);
9741 	if (rc != 0)
9742 		return(rc);
9743 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9744 	if (sb == NULL)
9745 		return (ENOMEM);
9746 
9747 	if (lc->link_ok || lc->link_down_rc == 255)
9748 		sbuf_printf(sb, "n/a");
9749 	else
9750 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9751 
9752 	rc = sbuf_finish(sb);
9753 	sbuf_delete(sb);
9754 
9755 	return (rc);
9756 }
9757 
9758 struct mem_desc {
9759 	u_int base;
9760 	u_int limit;
9761 	u_int idx;
9762 };
9763 
9764 static int
9765 mem_desc_cmp(const void *a, const void *b)
9766 {
9767 	const u_int v1 = ((const struct mem_desc *)a)->base;
9768 	const u_int v2 = ((const struct mem_desc *)b)->base;
9769 
9770 	if (v1 < v2)
9771 		return (-1);
9772 	else if (v1 > v2)
9773 		return (1);
9774 
9775 	return (0);
9776 }
9777 
9778 static void
9779 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9780     unsigned int to)
9781 {
9782 	unsigned int size;
9783 
9784 	if (from == to)
9785 		return;
9786 
9787 	size = to - from + 1;
9788 	if (size == 0)
9789 		return;
9790 
9791 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9792 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9793 }
9794 
9795 static int
9796 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9797 {
9798 	struct adapter *sc = arg1;
9799 	struct sbuf *sb;
9800 	int rc, i, n;
9801 	uint32_t lo, hi, used, free, alloc;
9802 	static const char *memory[] = {
9803 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9804 	};
9805 	static const char *region[] = {
9806 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9807 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9808 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9809 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9810 		"RQUDP region:", "PBL region:", "TXPBL region:",
9811 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9812 		"ULPTX state:", "On-chip queues:",
9813 	};
9814 	struct mem_desc avail[4];
9815 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9816 	struct mem_desc *md = mem;
9817 
9818 	rc = sysctl_wire_old_buffer(req, 0);
9819 	if (rc != 0)
9820 		return (rc);
9821 
9822 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9823 	if (sb == NULL)
9824 		return (ENOMEM);
9825 
9826 	for (i = 0; i < nitems(mem); i++) {
9827 		mem[i].limit = 0;
9828 		mem[i].idx = i;
9829 	}
9830 
9831 	mtx_lock(&sc->reg_lock);
9832 	if (hw_off_limits(sc)) {
9833 		rc = ENXIO;
9834 		goto done;
9835 	}
9836 
9837 	/* Find and sort the populated memory ranges */
9838 	i = 0;
9839 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9840 	if (lo & F_EDRAM0_ENABLE) {
9841 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9842 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9843 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9844 		avail[i].idx = 0;
9845 		i++;
9846 	}
9847 	if (lo & F_EDRAM1_ENABLE) {
9848 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9849 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9850 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9851 		avail[i].idx = 1;
9852 		i++;
9853 	}
9854 	if (lo & F_EXT_MEM_ENABLE) {
9855 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9856 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9857 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9858 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9859 		i++;
9860 	}
9861 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9862 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9863 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9864 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9865 		avail[i].idx = 4;
9866 		i++;
9867 	}
9868 	if (is_t6(sc) && lo & F_HMA_MUX) {
9869 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9870 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9871 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9872 		avail[i].idx = 5;
9873 		i++;
9874 	}
9875 	MPASS(i <= nitems(avail));
9876 	if (!i)                                    /* no memory available */
9877 		goto done;
9878 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9879 
9880 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9881 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9882 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9883 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9884 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9885 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9886 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9887 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9888 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9889 
9890 	/* the next few have explicit upper bounds */
9891 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9892 	md->limit = md->base - 1 +
9893 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9894 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9895 	md++;
9896 
9897 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9898 	md->limit = md->base - 1 +
9899 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9900 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9901 	md++;
9902 
9903 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9904 		if (chip_id(sc) <= CHELSIO_T5)
9905 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9906 		else
9907 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9908 		md->limit = 0;
9909 	} else {
9910 		md->base = 0;
9911 		md->idx = nitems(region);  /* hide it */
9912 	}
9913 	md++;
9914 
9915 #define ulp_region(reg) \
9916 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9917 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9918 
9919 	ulp_region(RX_ISCSI);
9920 	ulp_region(RX_TDDP);
9921 	ulp_region(TX_TPT);
9922 	ulp_region(RX_STAG);
9923 	ulp_region(RX_RQ);
9924 	ulp_region(RX_RQUDP);
9925 	ulp_region(RX_PBL);
9926 	ulp_region(TX_PBL);
9927 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9928 		ulp_region(RX_TLS_KEY);
9929 	}
9930 #undef ulp_region
9931 
9932 	md->base = 0;
9933 	if (is_t4(sc))
9934 		md->idx = nitems(region);
9935 	else {
9936 		uint32_t size = 0;
9937 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9938 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9939 
9940 		if (is_t5(sc)) {
9941 			if (sge_ctrl & F_VFIFO_ENABLE)
9942 				size = fifo_size << 2;
9943 		} else
9944 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9945 
9946 		if (size) {
9947 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9948 			md->limit = md->base + size - 1;
9949 		} else
9950 			md->idx = nitems(region);
9951 	}
9952 	md++;
9953 
9954 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9955 	md->limit = 0;
9956 	md++;
9957 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9958 	md->limit = 0;
9959 	md++;
9960 
9961 	md->base = sc->vres.ocq.start;
9962 	if (sc->vres.ocq.size)
9963 		md->limit = md->base + sc->vres.ocq.size - 1;
9964 	else
9965 		md->idx = nitems(region);  /* hide it */
9966 	md++;
9967 
9968 	/* add any address-space holes, there can be up to 3 */
9969 	for (n = 0; n < i - 1; n++)
9970 		if (avail[n].limit < avail[n + 1].base)
9971 			(md++)->base = avail[n].limit;
9972 	if (avail[n].limit)
9973 		(md++)->base = avail[n].limit;
9974 
9975 	n = md - mem;
9976 	MPASS(n <= nitems(mem));
9977 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9978 
9979 	for (lo = 0; lo < i; lo++)
9980 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9981 				avail[lo].limit - 1);
9982 
9983 	sbuf_printf(sb, "\n");
9984 	for (i = 0; i < n; i++) {
9985 		if (mem[i].idx >= nitems(region))
9986 			continue;                        /* skip holes */
9987 		if (!mem[i].limit)
9988 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9989 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9990 				mem[i].limit);
9991 	}
9992 
9993 	sbuf_printf(sb, "\n");
9994 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9995 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9996 	mem_region_show(sb, "uP RAM:", lo, hi);
9997 
9998 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9999 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10000 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10001 
10002 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10003 	for (i = 0, free = 0; i < 2; i++)
10004 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10005 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10006 		   G_PMRXMAXPAGE(lo), free,
10007 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10008 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10009 
10010 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10011 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10012 	for (i = 0, free = 0; i < 4; i++)
10013 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10014 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10015 		   G_PMTXMAXPAGE(lo), free,
10016 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10017 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10018 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10019 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10020 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10021 
10022 	for (i = 0; i < 4; i++) {
10023 		if (chip_id(sc) > CHELSIO_T5)
10024 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10025 		else
10026 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10027 		if (is_t5(sc)) {
10028 			used = G_T5_USED(lo);
10029 			alloc = G_T5_ALLOC(lo);
10030 		} else {
10031 			used = G_USED(lo);
10032 			alloc = G_ALLOC(lo);
10033 		}
10034 		/* For T6 these are MAC buffer groups */
10035 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10036 		    i, used, alloc);
10037 	}
10038 	for (i = 0; i < sc->chip_params->nchan; i++) {
10039 		if (chip_id(sc) > CHELSIO_T5)
10040 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10041 		else
10042 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10043 		if (is_t5(sc)) {
10044 			used = G_T5_USED(lo);
10045 			alloc = G_T5_ALLOC(lo);
10046 		} else {
10047 			used = G_USED(lo);
10048 			alloc = G_ALLOC(lo);
10049 		}
10050 		/* For T6 these are MAC buffer groups */
10051 		sbuf_printf(sb,
10052 		    "\nLoopback %d using %u pages out of %u allocated",
10053 		    i, used, alloc);
10054 	}
10055 done:
10056 	mtx_unlock(&sc->reg_lock);
10057 	if (rc == 0)
10058 		rc = sbuf_finish(sb);
10059 	sbuf_delete(sb);
10060 	return (rc);
10061 }
10062 
10063 static inline void
10064 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10065 {
10066 	*mask = x | y;
10067 	y = htobe64(y);
10068 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10069 }
10070 
10071 static int
10072 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10073 {
10074 	struct adapter *sc = arg1;
10075 	struct sbuf *sb;
10076 	int rc, i;
10077 
10078 	MPASS(chip_id(sc) <= CHELSIO_T5);
10079 
10080 	rc = sysctl_wire_old_buffer(req, 0);
10081 	if (rc != 0)
10082 		return (rc);
10083 
10084 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10085 	if (sb == NULL)
10086 		return (ENOMEM);
10087 
10088 	sbuf_printf(sb,
10089 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10090 	    "  VF              Replication             P0 P1 P2 P3  ML");
10091 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10092 		uint64_t tcamx, tcamy, mask;
10093 		uint32_t cls_lo, cls_hi;
10094 		uint8_t addr[ETHER_ADDR_LEN];
10095 
10096 		mtx_lock(&sc->reg_lock);
10097 		if (hw_off_limits(sc))
10098 			rc = ENXIO;
10099 		else {
10100 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10101 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10102 		}
10103 		mtx_unlock(&sc->reg_lock);
10104 		if (rc != 0)
10105 			break;
10106 		if (tcamx & tcamy)
10107 			continue;
10108 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10109 		mtx_lock(&sc->reg_lock);
10110 		if (hw_off_limits(sc))
10111 			rc = ENXIO;
10112 		else {
10113 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10114 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10115 		}
10116 		mtx_unlock(&sc->reg_lock);
10117 		if (rc != 0)
10118 			break;
10119 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10120 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10121 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10122 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10123 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10124 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10125 
10126 		if (cls_lo & F_REPLICATE) {
10127 			struct fw_ldst_cmd ldst_cmd;
10128 
10129 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10130 			ldst_cmd.op_to_addrspace =
10131 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10132 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10133 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10134 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10135 			ldst_cmd.u.mps.rplc.fid_idx =
10136 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10137 				V_FW_LDST_CMD_IDX(i));
10138 
10139 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10140 			    "t4mps");
10141 			if (rc)
10142 				break;
10143 			if (hw_off_limits(sc))
10144 				rc = ENXIO;
10145 			else
10146 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10147 				    sizeof(ldst_cmd), &ldst_cmd);
10148 			end_synchronized_op(sc, 0);
10149 			if (rc != 0)
10150 				break;
10151 			else {
10152 				sbuf_printf(sb, " %08x %08x %08x %08x",
10153 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10154 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10155 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10156 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10157 			}
10158 		} else
10159 			sbuf_printf(sb, "%36s", "");
10160 
10161 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10162 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10163 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10164 	}
10165 
10166 	if (rc)
10167 		(void) sbuf_finish(sb);
10168 	else
10169 		rc = sbuf_finish(sb);
10170 	sbuf_delete(sb);
10171 
10172 	return (rc);
10173 }
10174 
10175 static int
10176 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10177 {
10178 	struct adapter *sc = arg1;
10179 	struct sbuf *sb;
10180 	int rc, i;
10181 
10182 	MPASS(chip_id(sc) > CHELSIO_T5);
10183 
10184 	rc = sysctl_wire_old_buffer(req, 0);
10185 	if (rc != 0)
10186 		return (rc);
10187 
10188 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10189 	if (sb == NULL)
10190 		return (ENOMEM);
10191 
10192 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10193 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10194 	    "                           Replication"
10195 	    "                                    P0 P1 P2 P3  ML\n");
10196 
10197 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10198 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10199 		uint16_t ivlan;
10200 		uint64_t tcamx, tcamy, val, mask;
10201 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10202 		uint8_t addr[ETHER_ADDR_LEN];
10203 
10204 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10205 		if (i < 256)
10206 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10207 		else
10208 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10209 		mtx_lock(&sc->reg_lock);
10210 		if (hw_off_limits(sc))
10211 			rc = ENXIO;
10212 		else {
10213 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10214 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10215 			tcamy = G_DMACH(val) << 32;
10216 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10217 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10218 		}
10219 		mtx_unlock(&sc->reg_lock);
10220 		if (rc != 0)
10221 			break;
10222 
10223 		lookup_type = G_DATALKPTYPE(data2);
10224 		port_num = G_DATAPORTNUM(data2);
10225 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10226 			/* Inner header VNI */
10227 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10228 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10229 			dip_hit = data2 & F_DATADIPHIT;
10230 			vlan_vld = 0;
10231 		} else {
10232 			vniy = 0;
10233 			dip_hit = 0;
10234 			vlan_vld = data2 & F_DATAVIDH2;
10235 			ivlan = G_VIDL(val);
10236 		}
10237 
10238 		ctl |= V_CTLXYBITSEL(1);
10239 		mtx_lock(&sc->reg_lock);
10240 		if (hw_off_limits(sc))
10241 			rc = ENXIO;
10242 		else {
10243 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10244 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10245 			tcamx = G_DMACH(val) << 32;
10246 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10247 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10248 		}
10249 		mtx_unlock(&sc->reg_lock);
10250 		if (rc != 0)
10251 			break;
10252 
10253 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10254 			/* Inner header VNI mask */
10255 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10256 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10257 		} else
10258 			vnix = 0;
10259 
10260 		if (tcamx & tcamy)
10261 			continue;
10262 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10263 
10264 		mtx_lock(&sc->reg_lock);
10265 		if (hw_off_limits(sc))
10266 			rc = ENXIO;
10267 		else {
10268 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10269 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10270 		}
10271 		mtx_unlock(&sc->reg_lock);
10272 		if (rc != 0)
10273 			break;
10274 
10275 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10276 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10277 			    "%012jx %06x %06x    -    -   %3c"
10278 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10279 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10280 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10281 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10282 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10283 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10284 		} else {
10285 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10286 			    "%012jx    -       -   ", i, addr[0], addr[1],
10287 			    addr[2], addr[3], addr[4], addr[5],
10288 			    (uintmax_t)mask);
10289 
10290 			if (vlan_vld)
10291 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10292 			else
10293 				sbuf_printf(sb, "  -    N     ");
10294 
10295 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10296 			    lookup_type ? 'I' : 'O', port_num,
10297 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10298 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10299 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10300 		}
10301 
10302 
10303 		if (cls_lo & F_T6_REPLICATE) {
10304 			struct fw_ldst_cmd ldst_cmd;
10305 
10306 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10307 			ldst_cmd.op_to_addrspace =
10308 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10309 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10310 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10311 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10312 			ldst_cmd.u.mps.rplc.fid_idx =
10313 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10314 				V_FW_LDST_CMD_IDX(i));
10315 
10316 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10317 			    "t6mps");
10318 			if (rc)
10319 				break;
10320 			if (hw_off_limits(sc))
10321 				rc = ENXIO;
10322 			else
10323 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10324 				    sizeof(ldst_cmd), &ldst_cmd);
10325 			end_synchronized_op(sc, 0);
10326 			if (rc != 0)
10327 				break;
10328 			else {
10329 				sbuf_printf(sb, " %08x %08x %08x %08x"
10330 				    " %08x %08x %08x %08x",
10331 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10332 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10333 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10334 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10335 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10336 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10337 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10338 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10339 			}
10340 		} else
10341 			sbuf_printf(sb, "%72s", "");
10342 
10343 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10344 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10345 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10346 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10347 	}
10348 
10349 	if (rc)
10350 		(void) sbuf_finish(sb);
10351 	else
10352 		rc = sbuf_finish(sb);
10353 	sbuf_delete(sb);
10354 
10355 	return (rc);
10356 }
10357 
10358 static int
10359 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10360 {
10361 	struct adapter *sc = arg1;
10362 	struct sbuf *sb;
10363 	int rc;
10364 	uint16_t mtus[NMTUS];
10365 
10366 	rc = sysctl_wire_old_buffer(req, 0);
10367 	if (rc != 0)
10368 		return (rc);
10369 
10370 	mtx_lock(&sc->reg_lock);
10371 	if (hw_off_limits(sc))
10372 		rc = ENXIO;
10373 	else
10374 		t4_read_mtu_tbl(sc, mtus, NULL);
10375 	mtx_unlock(&sc->reg_lock);
10376 	if (rc != 0)
10377 		return (rc);
10378 
10379 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10380 	if (sb == NULL)
10381 		return (ENOMEM);
10382 
10383 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10384 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10385 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10386 	    mtus[14], mtus[15]);
10387 
10388 	rc = sbuf_finish(sb);
10389 	sbuf_delete(sb);
10390 
10391 	return (rc);
10392 }
10393 
10394 static int
10395 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10396 {
10397 	struct adapter *sc = arg1;
10398 	struct sbuf *sb;
10399 	int rc, i;
10400 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10401 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10402 	static const char *tx_stats[MAX_PM_NSTATS] = {
10403 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10404 		"Tx FIFO wait", NULL, "Tx latency"
10405 	};
10406 	static const char *rx_stats[MAX_PM_NSTATS] = {
10407 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10408 		"Rx FIFO wait", NULL, "Rx latency"
10409 	};
10410 
10411 	rc = sysctl_wire_old_buffer(req, 0);
10412 	if (rc != 0)
10413 		return (rc);
10414 
10415 	mtx_lock(&sc->reg_lock);
10416 	if (hw_off_limits(sc))
10417 		rc = ENXIO;
10418 	else {
10419 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10420 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10421 	}
10422 	mtx_unlock(&sc->reg_lock);
10423 	if (rc != 0)
10424 		return (rc);
10425 
10426 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10427 	if (sb == NULL)
10428 		return (ENOMEM);
10429 
10430 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10431 	for (i = 0; i < 4; i++) {
10432 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10433 		    tx_cyc[i]);
10434 	}
10435 
10436 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10437 	for (i = 0; i < 4; i++) {
10438 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10439 		    rx_cyc[i]);
10440 	}
10441 
10442 	if (chip_id(sc) > CHELSIO_T5) {
10443 		sbuf_printf(sb,
10444 		    "\n              Total wait      Total occupancy");
10445 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10446 		    tx_cyc[i]);
10447 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10448 		    rx_cyc[i]);
10449 
10450 		i += 2;
10451 		MPASS(i < nitems(tx_stats));
10452 
10453 		sbuf_printf(sb,
10454 		    "\n                   Reads           Total wait");
10455 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10456 		    tx_cyc[i]);
10457 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10458 		    rx_cyc[i]);
10459 	}
10460 
10461 	rc = sbuf_finish(sb);
10462 	sbuf_delete(sb);
10463 
10464 	return (rc);
10465 }
10466 
10467 static int
10468 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10469 {
10470 	struct adapter *sc = arg1;
10471 	struct sbuf *sb;
10472 	int rc;
10473 	struct tp_rdma_stats stats;
10474 
10475 	rc = sysctl_wire_old_buffer(req, 0);
10476 	if (rc != 0)
10477 		return (rc);
10478 
10479 	mtx_lock(&sc->reg_lock);
10480 	if (hw_off_limits(sc))
10481 		rc = ENXIO;
10482 	else
10483 		t4_tp_get_rdma_stats(sc, &stats, 0);
10484 	mtx_unlock(&sc->reg_lock);
10485 	if (rc != 0)
10486 		return (rc);
10487 
10488 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10489 	if (sb == NULL)
10490 		return (ENOMEM);
10491 
10492 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10493 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10494 
10495 	rc = sbuf_finish(sb);
10496 	sbuf_delete(sb);
10497 
10498 	return (rc);
10499 }
10500 
10501 static int
10502 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10503 {
10504 	struct adapter *sc = arg1;
10505 	struct sbuf *sb;
10506 	int rc;
10507 	struct tp_tcp_stats v4, v6;
10508 
10509 	rc = sysctl_wire_old_buffer(req, 0);
10510 	if (rc != 0)
10511 		return (rc);
10512 
10513 	mtx_lock(&sc->reg_lock);
10514 	if (hw_off_limits(sc))
10515 		rc = ENXIO;
10516 	else
10517 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10518 	mtx_unlock(&sc->reg_lock);
10519 	if (rc != 0)
10520 		return (rc);
10521 
10522 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10523 	if (sb == NULL)
10524 		return (ENOMEM);
10525 
10526 	sbuf_printf(sb,
10527 	    "                                IP                 IPv6\n");
10528 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10529 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10530 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10531 	    v4.tcp_in_segs, v6.tcp_in_segs);
10532 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10533 	    v4.tcp_out_segs, v6.tcp_out_segs);
10534 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10535 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10536 
10537 	rc = sbuf_finish(sb);
10538 	sbuf_delete(sb);
10539 
10540 	return (rc);
10541 }
10542 
10543 static int
10544 sysctl_tids(SYSCTL_HANDLER_ARGS)
10545 {
10546 	struct adapter *sc = arg1;
10547 	struct sbuf *sb;
10548 	int rc;
10549 	uint32_t x, y;
10550 	struct tid_info *t = &sc->tids;
10551 
10552 	rc = sysctl_wire_old_buffer(req, 0);
10553 	if (rc != 0)
10554 		return (rc);
10555 
10556 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10557 	if (sb == NULL)
10558 		return (ENOMEM);
10559 
10560 	if (t->natids) {
10561 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10562 		    t->atids_in_use);
10563 	}
10564 
10565 	if (t->nhpftids) {
10566 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10567 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10568 	}
10569 
10570 	if (t->ntids) {
10571 		bool hashen = false;
10572 
10573 		mtx_lock(&sc->reg_lock);
10574 		if (hw_off_limits(sc))
10575 			rc = ENXIO;
10576 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10577 			hashen = true;
10578 			if (chip_id(sc) <= CHELSIO_T5) {
10579 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10580 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10581 			} else {
10582 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10583 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10584 			}
10585 		}
10586 		mtx_unlock(&sc->reg_lock);
10587 		if (rc != 0)
10588 			goto done;
10589 
10590 		sbuf_printf(sb, "TID range: ");
10591 		if (hashen) {
10592 			if (x)
10593 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10594 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10595 		} else {
10596 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10597 			    t->ntids - 1);
10598 		}
10599 		sbuf_printf(sb, ", in use: %u\n",
10600 		    atomic_load_acq_int(&t->tids_in_use));
10601 	}
10602 
10603 	if (t->nstids) {
10604 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10605 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10606 	}
10607 
10608 	if (t->nftids) {
10609 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10610 		    t->ftid_end, t->ftids_in_use);
10611 	}
10612 
10613 	if (t->netids) {
10614 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10615 		    t->etid_base + t->netids - 1, t->etids_in_use);
10616 	}
10617 
10618 	mtx_lock(&sc->reg_lock);
10619 	if (hw_off_limits(sc))
10620 		rc = ENXIO;
10621 	else {
10622 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10623 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10624 	}
10625 	mtx_unlock(&sc->reg_lock);
10626 	if (rc != 0)
10627 		goto done;
10628 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10629 done:
10630 	if (rc == 0)
10631 		rc = sbuf_finish(sb);
10632 	else
10633 		(void)sbuf_finish(sb);
10634 	sbuf_delete(sb);
10635 
10636 	return (rc);
10637 }
10638 
10639 static int
10640 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10641 {
10642 	struct adapter *sc = arg1;
10643 	struct sbuf *sb;
10644 	int rc;
10645 	struct tp_err_stats stats;
10646 
10647 	rc = sysctl_wire_old_buffer(req, 0);
10648 	if (rc != 0)
10649 		return (rc);
10650 
10651 	mtx_lock(&sc->reg_lock);
10652 	if (hw_off_limits(sc))
10653 		rc = ENXIO;
10654 	else
10655 		t4_tp_get_err_stats(sc, &stats, 0);
10656 	mtx_unlock(&sc->reg_lock);
10657 	if (rc != 0)
10658 		return (rc);
10659 
10660 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10661 	if (sb == NULL)
10662 		return (ENOMEM);
10663 
10664 	if (sc->chip_params->nchan > 2) {
10665 		sbuf_printf(sb, "                 channel 0  channel 1"
10666 		    "  channel 2  channel 3\n");
10667 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10668 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10669 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10670 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10671 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10672 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10673 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10674 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10675 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10676 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10677 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10678 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10679 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10680 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10681 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10682 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10683 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10684 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10685 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10686 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10687 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10688 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10689 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10690 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10691 	} else {
10692 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10693 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10694 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10695 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10696 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10697 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10698 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10699 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10700 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10701 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10702 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10703 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10704 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10705 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10706 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10707 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10708 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10709 	}
10710 
10711 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10712 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10713 
10714 	rc = sbuf_finish(sb);
10715 	sbuf_delete(sb);
10716 
10717 	return (rc);
10718 }
10719 
10720 static int
10721 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10722 {
10723 	struct adapter *sc = arg1;
10724 	struct sbuf *sb;
10725 	int rc;
10726 	struct tp_tnl_stats stats;
10727 
10728 	rc = sysctl_wire_old_buffer(req, 0);
10729 	if (rc != 0)
10730 		return(rc);
10731 
10732 	mtx_lock(&sc->reg_lock);
10733 	if (hw_off_limits(sc))
10734 		rc = ENXIO;
10735 	else
10736 		t4_tp_get_tnl_stats(sc, &stats, 1);
10737 	mtx_unlock(&sc->reg_lock);
10738 	if (rc != 0)
10739 		return (rc);
10740 
10741 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10742 	if (sb == NULL)
10743 		return (ENOMEM);
10744 
10745 	if (sc->chip_params->nchan > 2) {
10746 		sbuf_printf(sb, "           channel 0  channel 1"
10747 		    "  channel 2  channel 3\n");
10748 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10749 		    stats.out_pkt[0], stats.out_pkt[1],
10750 		    stats.out_pkt[2], stats.out_pkt[3]);
10751 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10752 		    stats.in_pkt[0], stats.in_pkt[1],
10753 		    stats.in_pkt[2], stats.in_pkt[3]);
10754 	} else {
10755 		sbuf_printf(sb, "           channel 0  channel 1\n");
10756 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10757 		    stats.out_pkt[0], stats.out_pkt[1]);
10758 		sbuf_printf(sb, "InPkts:   %10u %10u",
10759 		    stats.in_pkt[0], stats.in_pkt[1]);
10760 	}
10761 
10762 	rc = sbuf_finish(sb);
10763 	sbuf_delete(sb);
10764 
10765 	return (rc);
10766 }
10767 
10768 static int
10769 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10770 {
10771 	struct adapter *sc = arg1;
10772 	struct tp_params *tpp = &sc->params.tp;
10773 	u_int mask;
10774 	int rc;
10775 
10776 	mask = tpp->la_mask >> 16;
10777 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10778 	if (rc != 0 || req->newptr == NULL)
10779 		return (rc);
10780 	if (mask > 0xffff)
10781 		return (EINVAL);
10782 	mtx_lock(&sc->reg_lock);
10783 	if (hw_off_limits(sc))
10784 		rc = ENXIO;
10785 	else {
10786 		tpp->la_mask = mask << 16;
10787 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10788 		    tpp->la_mask);
10789 	}
10790 	mtx_unlock(&sc->reg_lock);
10791 
10792 	return (rc);
10793 }
10794 
10795 struct field_desc {
10796 	const char *name;
10797 	u_int start;
10798 	u_int width;
10799 };
10800 
10801 static void
10802 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10803 {
10804 	char buf[32];
10805 	int line_size = 0;
10806 
10807 	while (f->name) {
10808 		uint64_t mask = (1ULL << f->width) - 1;
10809 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10810 		    ((uintmax_t)v >> f->start) & mask);
10811 
10812 		if (line_size + len >= 79) {
10813 			line_size = 8;
10814 			sbuf_printf(sb, "\n        ");
10815 		}
10816 		sbuf_printf(sb, "%s ", buf);
10817 		line_size += len + 1;
10818 		f++;
10819 	}
10820 	sbuf_printf(sb, "\n");
10821 }
10822 
10823 static const struct field_desc tp_la0[] = {
10824 	{ "RcfOpCodeOut", 60, 4 },
10825 	{ "State", 56, 4 },
10826 	{ "WcfState", 52, 4 },
10827 	{ "RcfOpcSrcOut", 50, 2 },
10828 	{ "CRxError", 49, 1 },
10829 	{ "ERxError", 48, 1 },
10830 	{ "SanityFailed", 47, 1 },
10831 	{ "SpuriousMsg", 46, 1 },
10832 	{ "FlushInputMsg", 45, 1 },
10833 	{ "FlushInputCpl", 44, 1 },
10834 	{ "RssUpBit", 43, 1 },
10835 	{ "RssFilterHit", 42, 1 },
10836 	{ "Tid", 32, 10 },
10837 	{ "InitTcb", 31, 1 },
10838 	{ "LineNumber", 24, 7 },
10839 	{ "Emsg", 23, 1 },
10840 	{ "EdataOut", 22, 1 },
10841 	{ "Cmsg", 21, 1 },
10842 	{ "CdataOut", 20, 1 },
10843 	{ "EreadPdu", 19, 1 },
10844 	{ "CreadPdu", 18, 1 },
10845 	{ "TunnelPkt", 17, 1 },
10846 	{ "RcfPeerFin", 16, 1 },
10847 	{ "RcfReasonOut", 12, 4 },
10848 	{ "TxCchannel", 10, 2 },
10849 	{ "RcfTxChannel", 8, 2 },
10850 	{ "RxEchannel", 6, 2 },
10851 	{ "RcfRxChannel", 5, 1 },
10852 	{ "RcfDataOutSrdy", 4, 1 },
10853 	{ "RxDvld", 3, 1 },
10854 	{ "RxOoDvld", 2, 1 },
10855 	{ "RxCongestion", 1, 1 },
10856 	{ "TxCongestion", 0, 1 },
10857 	{ NULL }
10858 };
10859 
10860 static const struct field_desc tp_la1[] = {
10861 	{ "CplCmdIn", 56, 8 },
10862 	{ "CplCmdOut", 48, 8 },
10863 	{ "ESynOut", 47, 1 },
10864 	{ "EAckOut", 46, 1 },
10865 	{ "EFinOut", 45, 1 },
10866 	{ "ERstOut", 44, 1 },
10867 	{ "SynIn", 43, 1 },
10868 	{ "AckIn", 42, 1 },
10869 	{ "FinIn", 41, 1 },
10870 	{ "RstIn", 40, 1 },
10871 	{ "DataIn", 39, 1 },
10872 	{ "DataInVld", 38, 1 },
10873 	{ "PadIn", 37, 1 },
10874 	{ "RxBufEmpty", 36, 1 },
10875 	{ "RxDdp", 35, 1 },
10876 	{ "RxFbCongestion", 34, 1 },
10877 	{ "TxFbCongestion", 33, 1 },
10878 	{ "TxPktSumSrdy", 32, 1 },
10879 	{ "RcfUlpType", 28, 4 },
10880 	{ "Eread", 27, 1 },
10881 	{ "Ebypass", 26, 1 },
10882 	{ "Esave", 25, 1 },
10883 	{ "Static0", 24, 1 },
10884 	{ "Cread", 23, 1 },
10885 	{ "Cbypass", 22, 1 },
10886 	{ "Csave", 21, 1 },
10887 	{ "CPktOut", 20, 1 },
10888 	{ "RxPagePoolFull", 18, 2 },
10889 	{ "RxLpbkPkt", 17, 1 },
10890 	{ "TxLpbkPkt", 16, 1 },
10891 	{ "RxVfValid", 15, 1 },
10892 	{ "SynLearned", 14, 1 },
10893 	{ "SetDelEntry", 13, 1 },
10894 	{ "SetInvEntry", 12, 1 },
10895 	{ "CpcmdDvld", 11, 1 },
10896 	{ "CpcmdSave", 10, 1 },
10897 	{ "RxPstructsFull", 8, 2 },
10898 	{ "EpcmdDvld", 7, 1 },
10899 	{ "EpcmdFlush", 6, 1 },
10900 	{ "EpcmdTrimPrefix", 5, 1 },
10901 	{ "EpcmdTrimPostfix", 4, 1 },
10902 	{ "ERssIp4Pkt", 3, 1 },
10903 	{ "ERssIp6Pkt", 2, 1 },
10904 	{ "ERssTcpUdpPkt", 1, 1 },
10905 	{ "ERssFceFipPkt", 0, 1 },
10906 	{ NULL }
10907 };
10908 
10909 static const struct field_desc tp_la2[] = {
10910 	{ "CplCmdIn", 56, 8 },
10911 	{ "MpsVfVld", 55, 1 },
10912 	{ "MpsPf", 52, 3 },
10913 	{ "MpsVf", 44, 8 },
10914 	{ "SynIn", 43, 1 },
10915 	{ "AckIn", 42, 1 },
10916 	{ "FinIn", 41, 1 },
10917 	{ "RstIn", 40, 1 },
10918 	{ "DataIn", 39, 1 },
10919 	{ "DataInVld", 38, 1 },
10920 	{ "PadIn", 37, 1 },
10921 	{ "RxBufEmpty", 36, 1 },
10922 	{ "RxDdp", 35, 1 },
10923 	{ "RxFbCongestion", 34, 1 },
10924 	{ "TxFbCongestion", 33, 1 },
10925 	{ "TxPktSumSrdy", 32, 1 },
10926 	{ "RcfUlpType", 28, 4 },
10927 	{ "Eread", 27, 1 },
10928 	{ "Ebypass", 26, 1 },
10929 	{ "Esave", 25, 1 },
10930 	{ "Static0", 24, 1 },
10931 	{ "Cread", 23, 1 },
10932 	{ "Cbypass", 22, 1 },
10933 	{ "Csave", 21, 1 },
10934 	{ "CPktOut", 20, 1 },
10935 	{ "RxPagePoolFull", 18, 2 },
10936 	{ "RxLpbkPkt", 17, 1 },
10937 	{ "TxLpbkPkt", 16, 1 },
10938 	{ "RxVfValid", 15, 1 },
10939 	{ "SynLearned", 14, 1 },
10940 	{ "SetDelEntry", 13, 1 },
10941 	{ "SetInvEntry", 12, 1 },
10942 	{ "CpcmdDvld", 11, 1 },
10943 	{ "CpcmdSave", 10, 1 },
10944 	{ "RxPstructsFull", 8, 2 },
10945 	{ "EpcmdDvld", 7, 1 },
10946 	{ "EpcmdFlush", 6, 1 },
10947 	{ "EpcmdTrimPrefix", 5, 1 },
10948 	{ "EpcmdTrimPostfix", 4, 1 },
10949 	{ "ERssIp4Pkt", 3, 1 },
10950 	{ "ERssIp6Pkt", 2, 1 },
10951 	{ "ERssTcpUdpPkt", 1, 1 },
10952 	{ "ERssFceFipPkt", 0, 1 },
10953 	{ NULL }
10954 };
10955 
10956 static void
10957 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10958 {
10959 
10960 	field_desc_show(sb, *p, tp_la0);
10961 }
10962 
10963 static void
10964 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10965 {
10966 
10967 	if (idx)
10968 		sbuf_printf(sb, "\n");
10969 	field_desc_show(sb, p[0], tp_la0);
10970 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10971 		field_desc_show(sb, p[1], tp_la0);
10972 }
10973 
10974 static void
10975 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10976 {
10977 
10978 	if (idx)
10979 		sbuf_printf(sb, "\n");
10980 	field_desc_show(sb, p[0], tp_la0);
10981 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10982 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10983 }
10984 
10985 static int
10986 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10987 {
10988 	struct adapter *sc = arg1;
10989 	struct sbuf *sb;
10990 	uint64_t *buf, *p;
10991 	int rc;
10992 	u_int i, inc;
10993 	void (*show_func)(struct sbuf *, uint64_t *, int);
10994 
10995 	rc = sysctl_wire_old_buffer(req, 0);
10996 	if (rc != 0)
10997 		return (rc);
10998 
10999 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11000 	if (sb == NULL)
11001 		return (ENOMEM);
11002 
11003 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11004 
11005 	mtx_lock(&sc->reg_lock);
11006 	if (hw_off_limits(sc))
11007 		rc = ENXIO;
11008 	else {
11009 		t4_tp_read_la(sc, buf, NULL);
11010 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11011 		case 2:
11012 			inc = 2;
11013 			show_func = tp_la_show2;
11014 			break;
11015 		case 3:
11016 			inc = 2;
11017 			show_func = tp_la_show3;
11018 			break;
11019 		default:
11020 			inc = 1;
11021 			show_func = tp_la_show;
11022 		}
11023 	}
11024 	mtx_unlock(&sc->reg_lock);
11025 	if (rc != 0)
11026 		goto done;
11027 
11028 	p = buf;
11029 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11030 		(*show_func)(sb, p, i);
11031 	rc = sbuf_finish(sb);
11032 done:
11033 	sbuf_delete(sb);
11034 	free(buf, M_CXGBE);
11035 	return (rc);
11036 }
11037 
11038 static int
11039 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11040 {
11041 	struct adapter *sc = arg1;
11042 	struct sbuf *sb;
11043 	int rc;
11044 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11045 
11046 	rc = sysctl_wire_old_buffer(req, 0);
11047 	if (rc != 0)
11048 		return (rc);
11049 
11050 	mtx_lock(&sc->reg_lock);
11051 	if (hw_off_limits(sc))
11052 		rc = ENXIO;
11053 	else
11054 		t4_get_chan_txrate(sc, nrate, orate);
11055 	mtx_unlock(&sc->reg_lock);
11056 	if (rc != 0)
11057 		return (rc);
11058 
11059 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11060 	if (sb == NULL)
11061 		return (ENOMEM);
11062 
11063 	if (sc->chip_params->nchan > 2) {
11064 		sbuf_printf(sb, "              channel 0   channel 1"
11065 		    "   channel 2   channel 3\n");
11066 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11067 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11068 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11069 		    orate[0], orate[1], orate[2], orate[3]);
11070 	} else {
11071 		sbuf_printf(sb, "              channel 0   channel 1\n");
11072 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11073 		    nrate[0], nrate[1]);
11074 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11075 		    orate[0], orate[1]);
11076 	}
11077 
11078 	rc = sbuf_finish(sb);
11079 	sbuf_delete(sb);
11080 
11081 	return (rc);
11082 }
11083 
11084 static int
11085 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11086 {
11087 	struct adapter *sc = arg1;
11088 	struct sbuf *sb;
11089 	uint32_t *buf, *p;
11090 	int rc, i;
11091 
11092 	rc = sysctl_wire_old_buffer(req, 0);
11093 	if (rc != 0)
11094 		return (rc);
11095 
11096 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11097 	if (sb == NULL)
11098 		return (ENOMEM);
11099 
11100 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11101 	    M_ZERO | M_WAITOK);
11102 
11103 	mtx_lock(&sc->reg_lock);
11104 	if (hw_off_limits(sc))
11105 		rc = ENXIO;
11106 	else
11107 		t4_ulprx_read_la(sc, buf);
11108 	mtx_unlock(&sc->reg_lock);
11109 	if (rc != 0)
11110 		goto done;
11111 
11112 	p = buf;
11113 	sbuf_printf(sb, "      Pcmd        Type   Message"
11114 	    "                Data");
11115 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11116 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11117 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11118 	}
11119 	rc = sbuf_finish(sb);
11120 done:
11121 	sbuf_delete(sb);
11122 	free(buf, M_CXGBE);
11123 	return (rc);
11124 }
11125 
11126 static int
11127 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11128 {
11129 	struct adapter *sc = arg1;
11130 	struct sbuf *sb;
11131 	int rc;
11132 	uint32_t cfg, s1, s2;
11133 
11134 	MPASS(chip_id(sc) >= CHELSIO_T5);
11135 
11136 	rc = sysctl_wire_old_buffer(req, 0);
11137 	if (rc != 0)
11138 		return (rc);
11139 
11140 	mtx_lock(&sc->reg_lock);
11141 	if (hw_off_limits(sc))
11142 		rc = ENXIO;
11143 	else {
11144 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11145 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11146 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11147 	}
11148 	mtx_unlock(&sc->reg_lock);
11149 	if (rc != 0)
11150 		return (rc);
11151 
11152 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11153 	if (sb == NULL)
11154 		return (ENOMEM);
11155 
11156 	if (G_STATSOURCE_T5(cfg) == 7) {
11157 		int mode;
11158 
11159 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11160 		if (mode == 0)
11161 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11162 		else if (mode == 1)
11163 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11164 		else
11165 			sbuf_printf(sb, "unknown mode %d", mode);
11166 	}
11167 	rc = sbuf_finish(sb);
11168 	sbuf_delete(sb);
11169 
11170 	return (rc);
11171 }
11172 
11173 static int
11174 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11175 {
11176 	struct adapter *sc = arg1;
11177 	enum cpu_sets op = arg2;
11178 	cpuset_t cpuset;
11179 	struct sbuf *sb;
11180 	int i, rc;
11181 
11182 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11183 
11184 	CPU_ZERO(&cpuset);
11185 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11186 	if (rc != 0)
11187 		return (rc);
11188 
11189 	rc = sysctl_wire_old_buffer(req, 0);
11190 	if (rc != 0)
11191 		return (rc);
11192 
11193 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11194 	if (sb == NULL)
11195 		return (ENOMEM);
11196 
11197 	CPU_FOREACH(i)
11198 		sbuf_printf(sb, "%d ", i);
11199 	rc = sbuf_finish(sb);
11200 	sbuf_delete(sb);
11201 
11202 	return (rc);
11203 }
11204 
11205 static int
11206 sysctl_reset(SYSCTL_HANDLER_ARGS)
11207 {
11208 	struct adapter *sc = arg1;
11209 	u_int val;
11210 	int rc;
11211 
11212 	val = atomic_load_int(&sc->num_resets);
11213 	rc = sysctl_handle_int(oidp, &val, 0, req);
11214 	if (rc != 0 || req->newptr == NULL)
11215 		return (rc);
11216 
11217 	if (val == 0) {
11218 		/* Zero out the counter that tracks reset. */
11219 		atomic_store_int(&sc->num_resets, 0);
11220 		return (0);
11221 	}
11222 
11223 	if (val != 1)
11224 		return (EINVAL);	/* 0 or 1 are the only legal values */
11225 
11226 	if (hw_off_limits(sc))		/* harmless race */
11227 		return (EALREADY);
11228 
11229 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11230 	return (0);
11231 }
11232 
11233 #ifdef TCP_OFFLOAD
11234 static int
11235 sysctl_tls(SYSCTL_HANDLER_ARGS)
11236 {
11237 	struct adapter *sc = arg1;
11238 	int i, j, v, rc;
11239 	struct vi_info *vi;
11240 
11241 	v = sc->tt.tls;
11242 	rc = sysctl_handle_int(oidp, &v, 0, req);
11243 	if (rc != 0 || req->newptr == NULL)
11244 		return (rc);
11245 
11246 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11247 		return (ENOTSUP);
11248 
11249 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11250 	if (rc)
11251 		return (rc);
11252 	if (hw_off_limits(sc))
11253 		rc = ENXIO;
11254 	else {
11255 		sc->tt.tls = !!v;
11256 		for_each_port(sc, i) {
11257 			for_each_vi(sc->port[i], j, vi) {
11258 				if (vi->flags & VI_INIT_DONE)
11259 					t4_update_fl_bufsize(vi->ifp);
11260 			}
11261 		}
11262 	}
11263 	end_synchronized_op(sc, 0);
11264 
11265 	return (rc);
11266 
11267 }
11268 
11269 static void
11270 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11271 {
11272 	u_int rem = val % factor;
11273 
11274 	if (rem == 0)
11275 		snprintf(buf, len, "%u", val / factor);
11276 	else {
11277 		while (rem % 10 == 0)
11278 			rem /= 10;
11279 		snprintf(buf, len, "%u.%u", val / factor, rem);
11280 	}
11281 }
11282 
11283 static int
11284 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11285 {
11286 	struct adapter *sc = arg1;
11287 	char buf[16];
11288 	u_int res, re;
11289 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11290 
11291 	mtx_lock(&sc->reg_lock);
11292 	if (hw_off_limits(sc))
11293 		res = (u_int)-1;
11294 	else
11295 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11296 	mtx_unlock(&sc->reg_lock);
11297 	if (res == (u_int)-1)
11298 		return (ENXIO);
11299 
11300 	switch (arg2) {
11301 	case 0:
11302 		/* timer_tick */
11303 		re = G_TIMERRESOLUTION(res);
11304 		break;
11305 	case 1:
11306 		/* TCP timestamp tick */
11307 		re = G_TIMESTAMPRESOLUTION(res);
11308 		break;
11309 	case 2:
11310 		/* DACK tick */
11311 		re = G_DELAYEDACKRESOLUTION(res);
11312 		break;
11313 	default:
11314 		return (EDOOFUS);
11315 	}
11316 
11317 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11318 
11319 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11320 }
11321 
11322 static int
11323 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11324 {
11325 	struct adapter *sc = arg1;
11326 	int rc;
11327 	u_int dack_tmr, dack_re, v;
11328 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11329 
11330 	mtx_lock(&sc->reg_lock);
11331 	if (hw_off_limits(sc))
11332 		rc = ENXIO;
11333 	else {
11334 		rc = 0;
11335 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11336 		    A_TP_TIMER_RESOLUTION));
11337 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11338 	}
11339 	mtx_unlock(&sc->reg_lock);
11340 	if (rc != 0)
11341 		return (rc);
11342 
11343 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11344 
11345 	return (sysctl_handle_int(oidp, &v, 0, req));
11346 }
11347 
11348 static int
11349 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11350 {
11351 	struct adapter *sc = arg1;
11352 	int rc, reg = arg2;
11353 	u_int tre;
11354 	u_long tp_tick_us, v;
11355 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11356 
11357 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11358 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11359 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11360 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11361 
11362 	mtx_lock(&sc->reg_lock);
11363 	if (hw_off_limits(sc))
11364 		rc = ENXIO;
11365 	else {
11366 		rc = 0;
11367 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11368 		tp_tick_us = (cclk_ps << tre) / 1000000;
11369 		if (reg == A_TP_INIT_SRTT)
11370 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11371 		else
11372 			v = tp_tick_us * t4_read_reg(sc, reg);
11373 	}
11374 	mtx_unlock(&sc->reg_lock);
11375 	if (rc != 0)
11376 		return (rc);
11377 	else
11378 		return (sysctl_handle_long(oidp, &v, 0, req));
11379 }
11380 
11381 /*
11382  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11383  * passed to this function.
11384  */
11385 static int
11386 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11387 {
11388 	struct adapter *sc = arg1;
11389 	int rc, idx = arg2;
11390 	u_int v;
11391 
11392 	MPASS(idx >= 0 && idx <= 24);
11393 
11394 	mtx_lock(&sc->reg_lock);
11395 	if (hw_off_limits(sc))
11396 		rc = ENXIO;
11397 	else {
11398 		rc = 0;
11399 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11400 	}
11401 	mtx_unlock(&sc->reg_lock);
11402 	if (rc != 0)
11403 		return (rc);
11404 	else
11405 		return (sysctl_handle_int(oidp, &v, 0, req));
11406 }
11407 
11408 static int
11409 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11410 {
11411 	struct adapter *sc = arg1;
11412 	int rc, idx = arg2;
11413 	u_int shift, v, r;
11414 
11415 	MPASS(idx >= 0 && idx < 16);
11416 
11417 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11418 	shift = (idx & 3) << 3;
11419 	mtx_lock(&sc->reg_lock);
11420 	if (hw_off_limits(sc))
11421 		rc = ENXIO;
11422 	else {
11423 		rc = 0;
11424 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11425 	}
11426 	mtx_unlock(&sc->reg_lock);
11427 	if (rc != 0)
11428 		return (rc);
11429 	else
11430 		return (sysctl_handle_int(oidp, &v, 0, req));
11431 }
11432 
11433 static int
11434 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11435 {
11436 	struct vi_info *vi = arg1;
11437 	struct adapter *sc = vi->adapter;
11438 	int idx, rc, i;
11439 	struct sge_ofld_rxq *ofld_rxq;
11440 	uint8_t v;
11441 
11442 	idx = vi->ofld_tmr_idx;
11443 
11444 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11445 	if (rc != 0 || req->newptr == NULL)
11446 		return (rc);
11447 
11448 	if (idx < 0 || idx >= SGE_NTIMERS)
11449 		return (EINVAL);
11450 
11451 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11452 	    "t4otmr");
11453 	if (rc)
11454 		return (rc);
11455 
11456 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11457 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11458 #ifdef atomic_store_rel_8
11459 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11460 #else
11461 		ofld_rxq->iq.intr_params = v;
11462 #endif
11463 	}
11464 	vi->ofld_tmr_idx = idx;
11465 
11466 	end_synchronized_op(sc, LOCK_HELD);
11467 	return (0);
11468 }
11469 
11470 static int
11471 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11472 {
11473 	struct vi_info *vi = arg1;
11474 	struct adapter *sc = vi->adapter;
11475 	int idx, rc;
11476 
11477 	idx = vi->ofld_pktc_idx;
11478 
11479 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11480 	if (rc != 0 || req->newptr == NULL)
11481 		return (rc);
11482 
11483 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11484 		return (EINVAL);
11485 
11486 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11487 	    "t4opktc");
11488 	if (rc)
11489 		return (rc);
11490 
11491 	if (vi->flags & VI_INIT_DONE)
11492 		rc = EBUSY; /* cannot be changed once the queues are created */
11493 	else
11494 		vi->ofld_pktc_idx = idx;
11495 
11496 	end_synchronized_op(sc, LOCK_HELD);
11497 	return (rc);
11498 }
11499 #endif
11500 
11501 static int
11502 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11503 {
11504 	int rc;
11505 
11506 	if (cntxt->cid > M_CTXTQID)
11507 		return (EINVAL);
11508 
11509 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11510 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11511 		return (EINVAL);
11512 
11513 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11514 	if (rc)
11515 		return (rc);
11516 
11517 	if (hw_off_limits(sc)) {
11518 		rc = ENXIO;
11519 		goto done;
11520 	}
11521 
11522 	if (sc->flags & FW_OK) {
11523 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11524 		    &cntxt->data[0]);
11525 		if (rc == 0)
11526 			goto done;
11527 	}
11528 
11529 	/*
11530 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11531 	 * the backdoor.
11532 	 */
11533 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11534 done:
11535 	end_synchronized_op(sc, 0);
11536 	return (rc);
11537 }
11538 
11539 static int
11540 load_fw(struct adapter *sc, struct t4_data *fw)
11541 {
11542 	int rc;
11543 	uint8_t *fw_data;
11544 
11545 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11546 	if (rc)
11547 		return (rc);
11548 
11549 	if (hw_off_limits(sc)) {
11550 		rc = ENXIO;
11551 		goto done;
11552 	}
11553 
11554 	/*
11555 	 * The firmware, with the sole exception of the memory parity error
11556 	 * handler, runs from memory and not flash.  It is almost always safe to
11557 	 * install a new firmware on a running system.  Just set bit 1 in
11558 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11559 	 */
11560 	if (sc->flags & FULL_INIT_DONE &&
11561 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11562 		rc = EBUSY;
11563 		goto done;
11564 	}
11565 
11566 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11567 
11568 	rc = copyin(fw->data, fw_data, fw->len);
11569 	if (rc == 0)
11570 		rc = -t4_load_fw(sc, fw_data, fw->len);
11571 
11572 	free(fw_data, M_CXGBE);
11573 done:
11574 	end_synchronized_op(sc, 0);
11575 	return (rc);
11576 }
11577 
11578 static int
11579 load_cfg(struct adapter *sc, struct t4_data *cfg)
11580 {
11581 	int rc;
11582 	uint8_t *cfg_data = NULL;
11583 
11584 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11585 	if (rc)
11586 		return (rc);
11587 
11588 	if (hw_off_limits(sc)) {
11589 		rc = ENXIO;
11590 		goto done;
11591 	}
11592 
11593 	if (cfg->len == 0) {
11594 		/* clear */
11595 		rc = -t4_load_cfg(sc, NULL, 0);
11596 		goto done;
11597 	}
11598 
11599 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11600 
11601 	rc = copyin(cfg->data, cfg_data, cfg->len);
11602 	if (rc == 0)
11603 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11604 
11605 	free(cfg_data, M_CXGBE);
11606 done:
11607 	end_synchronized_op(sc, 0);
11608 	return (rc);
11609 }
11610 
11611 static int
11612 load_boot(struct adapter *sc, struct t4_bootrom *br)
11613 {
11614 	int rc;
11615 	uint8_t *br_data = NULL;
11616 	u_int offset;
11617 
11618 	if (br->len > 1024 * 1024)
11619 		return (EFBIG);
11620 
11621 	if (br->pf_offset == 0) {
11622 		/* pfidx */
11623 		if (br->pfidx_addr > 7)
11624 			return (EINVAL);
11625 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11626 		    A_PCIE_PF_EXPROM_OFST)));
11627 	} else if (br->pf_offset == 1) {
11628 		/* offset */
11629 		offset = G_OFFSET(br->pfidx_addr);
11630 	} else {
11631 		return (EINVAL);
11632 	}
11633 
11634 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11635 	if (rc)
11636 		return (rc);
11637 
11638 	if (hw_off_limits(sc)) {
11639 		rc = ENXIO;
11640 		goto done;
11641 	}
11642 
11643 	if (br->len == 0) {
11644 		/* clear */
11645 		rc = -t4_load_boot(sc, NULL, offset, 0);
11646 		goto done;
11647 	}
11648 
11649 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11650 
11651 	rc = copyin(br->data, br_data, br->len);
11652 	if (rc == 0)
11653 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11654 
11655 	free(br_data, M_CXGBE);
11656 done:
11657 	end_synchronized_op(sc, 0);
11658 	return (rc);
11659 }
11660 
11661 static int
11662 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11663 {
11664 	int rc;
11665 	uint8_t *bc_data = NULL;
11666 
11667 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11668 	if (rc)
11669 		return (rc);
11670 
11671 	if (hw_off_limits(sc)) {
11672 		rc = ENXIO;
11673 		goto done;
11674 	}
11675 
11676 	if (bc->len == 0) {
11677 		/* clear */
11678 		rc = -t4_load_bootcfg(sc, NULL, 0);
11679 		goto done;
11680 	}
11681 
11682 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11683 
11684 	rc = copyin(bc->data, bc_data, bc->len);
11685 	if (rc == 0)
11686 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11687 
11688 	free(bc_data, M_CXGBE);
11689 done:
11690 	end_synchronized_op(sc, 0);
11691 	return (rc);
11692 }
11693 
11694 static int
11695 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11696 {
11697 	int rc;
11698 	struct cudbg_init *cudbg;
11699 	void *handle, *buf;
11700 
11701 	/* buf is large, don't block if no memory is available */
11702 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11703 	if (buf == NULL)
11704 		return (ENOMEM);
11705 
11706 	handle = cudbg_alloc_handle();
11707 	if (handle == NULL) {
11708 		rc = ENOMEM;
11709 		goto done;
11710 	}
11711 
11712 	cudbg = cudbg_get_init(handle);
11713 	cudbg->adap = sc;
11714 	cudbg->print = (cudbg_print_cb)printf;
11715 
11716 #ifndef notyet
11717 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11718 	    __func__, dump->wr_flash, dump->len, dump->data);
11719 #endif
11720 
11721 	if (dump->wr_flash)
11722 		cudbg->use_flash = 1;
11723 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11724 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11725 
11726 	rc = cudbg_collect(handle, buf, &dump->len);
11727 	if (rc != 0)
11728 		goto done;
11729 
11730 	rc = copyout(buf, dump->data, dump->len);
11731 done:
11732 	cudbg_free_handle(handle);
11733 	free(buf, M_CXGBE);
11734 	return (rc);
11735 }
11736 
11737 static void
11738 free_offload_policy(struct t4_offload_policy *op)
11739 {
11740 	struct offload_rule *r;
11741 	int i;
11742 
11743 	if (op == NULL)
11744 		return;
11745 
11746 	r = &op->rule[0];
11747 	for (i = 0; i < op->nrules; i++, r++) {
11748 		free(r->bpf_prog.bf_insns, M_CXGBE);
11749 	}
11750 	free(op->rule, M_CXGBE);
11751 	free(op, M_CXGBE);
11752 }
11753 
11754 static int
11755 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11756 {
11757 	int i, rc, len;
11758 	struct t4_offload_policy *op, *old;
11759 	struct bpf_program *bf;
11760 	const struct offload_settings *s;
11761 	struct offload_rule *r;
11762 	void *u;
11763 
11764 	if (!is_offload(sc))
11765 		return (ENODEV);
11766 
11767 	if (uop->nrules == 0) {
11768 		/* Delete installed policies. */
11769 		op = NULL;
11770 		goto set_policy;
11771 	} else if (uop->nrules > 256) { /* arbitrary */
11772 		return (E2BIG);
11773 	}
11774 
11775 	/* Copy userspace offload policy to kernel */
11776 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11777 	op->nrules = uop->nrules;
11778 	len = op->nrules * sizeof(struct offload_rule);
11779 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11780 	rc = copyin(uop->rule, op->rule, len);
11781 	if (rc) {
11782 		free(op->rule, M_CXGBE);
11783 		free(op, M_CXGBE);
11784 		return (rc);
11785 	}
11786 
11787 	r = &op->rule[0];
11788 	for (i = 0; i < op->nrules; i++, r++) {
11789 
11790 		/* Validate open_type */
11791 		if (r->open_type != OPEN_TYPE_LISTEN &&
11792 		    r->open_type != OPEN_TYPE_ACTIVE &&
11793 		    r->open_type != OPEN_TYPE_PASSIVE &&
11794 		    r->open_type != OPEN_TYPE_DONTCARE) {
11795 error:
11796 			/*
11797 			 * Rules 0 to i have malloc'd filters that need to be
11798 			 * freed.  Rules i+1 to nrules have userspace pointers
11799 			 * and should be left alone.
11800 			 */
11801 			op->nrules = i;
11802 			free_offload_policy(op);
11803 			return (rc);
11804 		}
11805 
11806 		/* Validate settings */
11807 		s = &r->settings;
11808 		if ((s->offload != 0 && s->offload != 1) ||
11809 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11810 		    s->sched_class < -1 ||
11811 		    s->sched_class >= sc->params.nsched_cls) {
11812 			rc = EINVAL;
11813 			goto error;
11814 		}
11815 
11816 		bf = &r->bpf_prog;
11817 		u = bf->bf_insns;	/* userspace ptr */
11818 		bf->bf_insns = NULL;
11819 		if (bf->bf_len == 0) {
11820 			/* legal, matches everything */
11821 			continue;
11822 		}
11823 		len = bf->bf_len * sizeof(*bf->bf_insns);
11824 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11825 		rc = copyin(u, bf->bf_insns, len);
11826 		if (rc != 0)
11827 			goto error;
11828 
11829 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11830 			rc = EINVAL;
11831 			goto error;
11832 		}
11833 	}
11834 set_policy:
11835 	rw_wlock(&sc->policy_lock);
11836 	old = sc->policy;
11837 	sc->policy = op;
11838 	rw_wunlock(&sc->policy_lock);
11839 	free_offload_policy(old);
11840 
11841 	return (0);
11842 }
11843 
11844 #define MAX_READ_BUF_SIZE (128 * 1024)
11845 static int
11846 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11847 {
11848 	uint32_t addr, remaining, n;
11849 	uint32_t *buf;
11850 	int rc;
11851 	uint8_t *dst;
11852 
11853 	mtx_lock(&sc->reg_lock);
11854 	if (hw_off_limits(sc))
11855 		rc = ENXIO;
11856 	else
11857 		rc = validate_mem_range(sc, mr->addr, mr->len);
11858 	mtx_unlock(&sc->reg_lock);
11859 	if (rc != 0)
11860 		return (rc);
11861 
11862 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11863 	addr = mr->addr;
11864 	remaining = mr->len;
11865 	dst = (void *)mr->data;
11866 
11867 	while (remaining) {
11868 		n = min(remaining, MAX_READ_BUF_SIZE);
11869 		mtx_lock(&sc->reg_lock);
11870 		if (hw_off_limits(sc))
11871 			rc = ENXIO;
11872 		else
11873 			read_via_memwin(sc, 2, addr, buf, n);
11874 		mtx_unlock(&sc->reg_lock);
11875 		if (rc != 0)
11876 			break;
11877 
11878 		rc = copyout(buf, dst, n);
11879 		if (rc != 0)
11880 			break;
11881 
11882 		dst += n;
11883 		remaining -= n;
11884 		addr += n;
11885 	}
11886 
11887 	free(buf, M_CXGBE);
11888 	return (rc);
11889 }
11890 #undef MAX_READ_BUF_SIZE
11891 
11892 static int
11893 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11894 {
11895 	int rc;
11896 
11897 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11898 		return (EINVAL);
11899 
11900 	if (i2cd->len > sizeof(i2cd->data))
11901 		return (EFBIG);
11902 
11903 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11904 	if (rc)
11905 		return (rc);
11906 	if (hw_off_limits(sc))
11907 		rc = ENXIO;
11908 	else
11909 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11910 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11911 	end_synchronized_op(sc, 0);
11912 
11913 	return (rc);
11914 }
11915 
11916 static int
11917 clear_stats(struct adapter *sc, u_int port_id)
11918 {
11919 	int i, v, chan_map;
11920 	struct port_info *pi;
11921 	struct vi_info *vi;
11922 	struct sge_rxq *rxq;
11923 	struct sge_txq *txq;
11924 	struct sge_wrq *wrq;
11925 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11926 	struct sge_ofld_txq *ofld_txq;
11927 #endif
11928 #ifdef TCP_OFFLOAD
11929 	struct sge_ofld_rxq *ofld_rxq;
11930 #endif
11931 
11932 	if (port_id >= sc->params.nports)
11933 		return (EINVAL);
11934 	pi = sc->port[port_id];
11935 	if (pi == NULL)
11936 		return (EIO);
11937 
11938 	mtx_lock(&sc->reg_lock);
11939 	if (!hw_off_limits(sc)) {
11940 		/* MAC stats */
11941 		t4_clr_port_stats(sc, pi->tx_chan);
11942 		if (is_t6(sc)) {
11943 			if (pi->fcs_reg != -1)
11944 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11945 			else
11946 				pi->stats.rx_fcs_err = 0;
11947 		}
11948 		for_each_vi(pi, v, vi) {
11949 			if (vi->flags & VI_INIT_DONE)
11950 				t4_clr_vi_stats(sc, vi->vin);
11951 		}
11952 		chan_map = pi->rx_e_chan_map;
11953 		v = 0;	/* reuse */
11954 		while (chan_map) {
11955 			i = ffs(chan_map) - 1;
11956 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11957 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11958 			chan_map &= ~(1 << i);
11959 		}
11960 	}
11961 	mtx_unlock(&sc->reg_lock);
11962 	pi->tx_parse_error = 0;
11963 	pi->tnl_cong_drops = 0;
11964 
11965 	/*
11966 	 * Since this command accepts a port, clear stats for
11967 	 * all VIs on this port.
11968 	 */
11969 	for_each_vi(pi, v, vi) {
11970 		if (vi->flags & VI_INIT_DONE) {
11971 
11972 			for_each_rxq(vi, i, rxq) {
11973 #if defined(INET) || defined(INET6)
11974 				rxq->lro.lro_queued = 0;
11975 				rxq->lro.lro_flushed = 0;
11976 #endif
11977 				rxq->rxcsum = 0;
11978 				rxq->vlan_extraction = 0;
11979 				rxq->vxlan_rxcsum = 0;
11980 
11981 				rxq->fl.cl_allocated = 0;
11982 				rxq->fl.cl_recycled = 0;
11983 				rxq->fl.cl_fast_recycled = 0;
11984 			}
11985 
11986 			for_each_txq(vi, i, txq) {
11987 				txq->txcsum = 0;
11988 				txq->tso_wrs = 0;
11989 				txq->vlan_insertion = 0;
11990 				txq->imm_wrs = 0;
11991 				txq->sgl_wrs = 0;
11992 				txq->txpkt_wrs = 0;
11993 				txq->txpkts0_wrs = 0;
11994 				txq->txpkts1_wrs = 0;
11995 				txq->txpkts0_pkts = 0;
11996 				txq->txpkts1_pkts = 0;
11997 				txq->txpkts_flush = 0;
11998 				txq->raw_wrs = 0;
11999 				txq->vxlan_tso_wrs = 0;
12000 				txq->vxlan_txcsum = 0;
12001 				txq->kern_tls_records = 0;
12002 				txq->kern_tls_short = 0;
12003 				txq->kern_tls_partial = 0;
12004 				txq->kern_tls_full = 0;
12005 				txq->kern_tls_octets = 0;
12006 				txq->kern_tls_waste = 0;
12007 				txq->kern_tls_options = 0;
12008 				txq->kern_tls_header = 0;
12009 				txq->kern_tls_fin = 0;
12010 				txq->kern_tls_fin_short = 0;
12011 				txq->kern_tls_cbc = 0;
12012 				txq->kern_tls_gcm = 0;
12013 				mp_ring_reset_stats(txq->r);
12014 			}
12015 
12016 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12017 			for_each_ofld_txq(vi, i, ofld_txq) {
12018 				ofld_txq->wrq.tx_wrs_direct = 0;
12019 				ofld_txq->wrq.tx_wrs_copied = 0;
12020 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12021 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12022 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12023 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12024 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12025 			}
12026 #endif
12027 #ifdef TCP_OFFLOAD
12028 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12029 				ofld_rxq->fl.cl_allocated = 0;
12030 				ofld_rxq->fl.cl_recycled = 0;
12031 				ofld_rxq->fl.cl_fast_recycled = 0;
12032 				counter_u64_zero(
12033 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12034 				counter_u64_zero(
12035 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12036 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12037 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12038 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12039 				ofld_rxq->rx_iscsi_fl_octets = 0;
12040 				ofld_rxq->rx_toe_tls_records = 0;
12041 				ofld_rxq->rx_toe_tls_octets = 0;
12042 			}
12043 #endif
12044 
12045 			if (IS_MAIN_VI(vi)) {
12046 				wrq = &sc->sge.ctrlq[pi->port_id];
12047 				wrq->tx_wrs_direct = 0;
12048 				wrq->tx_wrs_copied = 0;
12049 			}
12050 		}
12051 	}
12052 
12053 	return (0);
12054 }
12055 
12056 static int
12057 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12058 {
12059 #ifdef INET6
12060 	struct in6_addr in6;
12061 
12062 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12063 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12064 		return (0);
12065 	else
12066 		return (EIO);
12067 #else
12068 	return (ENOTSUP);
12069 #endif
12070 }
12071 
12072 static int
12073 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12074 {
12075 #ifdef INET6
12076 	struct in6_addr in6;
12077 
12078 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12079 	return (t4_release_clip_addr(sc, &in6));
12080 #else
12081 	return (ENOTSUP);
12082 #endif
12083 }
12084 
12085 int
12086 t4_os_find_pci_capability(struct adapter *sc, int cap)
12087 {
12088 	int i;
12089 
12090 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12091 }
12092 
12093 int
12094 t4_os_pci_save_state(struct adapter *sc)
12095 {
12096 	device_t dev;
12097 	struct pci_devinfo *dinfo;
12098 
12099 	dev = sc->dev;
12100 	dinfo = device_get_ivars(dev);
12101 
12102 	pci_cfg_save(dev, dinfo, 0);
12103 	return (0);
12104 }
12105 
12106 int
12107 t4_os_pci_restore_state(struct adapter *sc)
12108 {
12109 	device_t dev;
12110 	struct pci_devinfo *dinfo;
12111 
12112 	dev = sc->dev;
12113 	dinfo = device_get_ivars(dev);
12114 
12115 	pci_cfg_restore(dev, dinfo);
12116 	return (0);
12117 }
12118 
12119 void
12120 t4_os_portmod_changed(struct port_info *pi)
12121 {
12122 	struct adapter *sc = pi->adapter;
12123 	struct vi_info *vi;
12124 	if_t ifp;
12125 	static const char *mod_str[] = {
12126 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12127 	};
12128 
12129 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12130 	    ("%s: port_type %u", __func__, pi->port_type));
12131 
12132 	vi = &pi->vi[0];
12133 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12134 		PORT_LOCK(pi);
12135 		build_medialist(pi);
12136 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12137 			fixup_link_config(pi);
12138 			apply_link_config(pi);
12139 		}
12140 		PORT_UNLOCK(pi);
12141 		end_synchronized_op(sc, LOCK_HELD);
12142 	}
12143 
12144 	ifp = vi->ifp;
12145 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12146 		if_printf(ifp, "transceiver unplugged.\n");
12147 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12148 		if_printf(ifp, "unknown transceiver inserted.\n");
12149 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12150 		if_printf(ifp, "unsupported transceiver inserted.\n");
12151 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12152 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12153 		    port_top_speed(pi), mod_str[pi->mod_type]);
12154 	} else {
12155 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12156 		    pi->mod_type);
12157 	}
12158 }
12159 
12160 void
12161 t4_os_link_changed(struct port_info *pi)
12162 {
12163 	struct vi_info *vi;
12164 	if_t ifp;
12165 	struct link_config *lc = &pi->link_cfg;
12166 	struct adapter *sc = pi->adapter;
12167 	int v;
12168 
12169 	PORT_LOCK_ASSERT_OWNED(pi);
12170 
12171 	if (is_t6(sc)) {
12172 		if (lc->link_ok) {
12173 			if (lc->speed > 25000 ||
12174 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12175 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12176 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12177 			} else {
12178 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12179 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12180 			}
12181 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12182 			pi->stats.rx_fcs_err = 0;
12183 		} else {
12184 			pi->fcs_reg = -1;
12185 		}
12186 	} else {
12187 		MPASS(pi->fcs_reg != -1);
12188 		MPASS(pi->fcs_base == 0);
12189 	}
12190 
12191 	for_each_vi(pi, v, vi) {
12192 		ifp = vi->ifp;
12193 		if (ifp == NULL)
12194 			continue;
12195 
12196 		if (lc->link_ok) {
12197 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12198 			if_link_state_change(ifp, LINK_STATE_UP);
12199 		} else {
12200 			if_link_state_change(ifp, LINK_STATE_DOWN);
12201 		}
12202 	}
12203 }
12204 
12205 void
12206 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12207 {
12208 	struct adapter *sc;
12209 
12210 	sx_slock(&t4_list_lock);
12211 	SLIST_FOREACH(sc, &t4_list, link) {
12212 		/*
12213 		 * func should not make any assumptions about what state sc is
12214 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12215 		 */
12216 		func(sc, arg);
12217 	}
12218 	sx_sunlock(&t4_list_lock);
12219 }
12220 
12221 static int
12222 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12223     struct thread *td)
12224 {
12225 	int rc;
12226 	struct adapter *sc = dev->si_drv1;
12227 
12228 	rc = priv_check(td, PRIV_DRIVER);
12229 	if (rc != 0)
12230 		return (rc);
12231 
12232 	switch (cmd) {
12233 	case CHELSIO_T4_GETREG: {
12234 		struct t4_reg *edata = (struct t4_reg *)data;
12235 
12236 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12237 			return (EFAULT);
12238 
12239 		mtx_lock(&sc->reg_lock);
12240 		if (hw_off_limits(sc))
12241 			rc = ENXIO;
12242 		else if (edata->size == 4)
12243 			edata->val = t4_read_reg(sc, edata->addr);
12244 		else if (edata->size == 8)
12245 			edata->val = t4_read_reg64(sc, edata->addr);
12246 		else
12247 			rc = EINVAL;
12248 		mtx_unlock(&sc->reg_lock);
12249 
12250 		break;
12251 	}
12252 	case CHELSIO_T4_SETREG: {
12253 		struct t4_reg *edata = (struct t4_reg *)data;
12254 
12255 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12256 			return (EFAULT);
12257 
12258 		mtx_lock(&sc->reg_lock);
12259 		if (hw_off_limits(sc))
12260 			rc = ENXIO;
12261 		else if (edata->size == 4) {
12262 			if (edata->val & 0xffffffff00000000)
12263 				rc = EINVAL;
12264 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12265 		} else if (edata->size == 8)
12266 			t4_write_reg64(sc, edata->addr, edata->val);
12267 		else
12268 			rc = EINVAL;
12269 		mtx_unlock(&sc->reg_lock);
12270 
12271 		break;
12272 	}
12273 	case CHELSIO_T4_REGDUMP: {
12274 		struct t4_regdump *regs = (struct t4_regdump *)data;
12275 		int reglen = t4_get_regs_len(sc);
12276 		uint8_t *buf;
12277 
12278 		if (regs->len < reglen) {
12279 			regs->len = reglen; /* hint to the caller */
12280 			return (ENOBUFS);
12281 		}
12282 
12283 		regs->len = reglen;
12284 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12285 		mtx_lock(&sc->reg_lock);
12286 		if (hw_off_limits(sc))
12287 			rc = ENXIO;
12288 		else
12289 			get_regs(sc, regs, buf);
12290 		mtx_unlock(&sc->reg_lock);
12291 		if (rc == 0)
12292 			rc = copyout(buf, regs->data, reglen);
12293 		free(buf, M_CXGBE);
12294 		break;
12295 	}
12296 	case CHELSIO_T4_GET_FILTER_MODE:
12297 		rc = get_filter_mode(sc, (uint32_t *)data);
12298 		break;
12299 	case CHELSIO_T4_SET_FILTER_MODE:
12300 		rc = set_filter_mode(sc, *(uint32_t *)data);
12301 		break;
12302 	case CHELSIO_T4_SET_FILTER_MASK:
12303 		rc = set_filter_mask(sc, *(uint32_t *)data);
12304 		break;
12305 	case CHELSIO_T4_GET_FILTER:
12306 		rc = get_filter(sc, (struct t4_filter *)data);
12307 		break;
12308 	case CHELSIO_T4_SET_FILTER:
12309 		rc = set_filter(sc, (struct t4_filter *)data);
12310 		break;
12311 	case CHELSIO_T4_DEL_FILTER:
12312 		rc = del_filter(sc, (struct t4_filter *)data);
12313 		break;
12314 	case CHELSIO_T4_GET_SGE_CONTEXT:
12315 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12316 		break;
12317 	case CHELSIO_T4_LOAD_FW:
12318 		rc = load_fw(sc, (struct t4_data *)data);
12319 		break;
12320 	case CHELSIO_T4_GET_MEM:
12321 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12322 		break;
12323 	case CHELSIO_T4_GET_I2C:
12324 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12325 		break;
12326 	case CHELSIO_T4_CLEAR_STATS:
12327 		rc = clear_stats(sc, *(uint32_t *)data);
12328 		break;
12329 	case CHELSIO_T4_SCHED_CLASS:
12330 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12331 		break;
12332 	case CHELSIO_T4_SCHED_QUEUE:
12333 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12334 		break;
12335 	case CHELSIO_T4_GET_TRACER:
12336 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12337 		break;
12338 	case CHELSIO_T4_SET_TRACER:
12339 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12340 		break;
12341 	case CHELSIO_T4_LOAD_CFG:
12342 		rc = load_cfg(sc, (struct t4_data *)data);
12343 		break;
12344 	case CHELSIO_T4_LOAD_BOOT:
12345 		rc = load_boot(sc, (struct t4_bootrom *)data);
12346 		break;
12347 	case CHELSIO_T4_LOAD_BOOTCFG:
12348 		rc = load_bootcfg(sc, (struct t4_data *)data);
12349 		break;
12350 	case CHELSIO_T4_CUDBG_DUMP:
12351 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12352 		break;
12353 	case CHELSIO_T4_SET_OFLD_POLICY:
12354 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12355 		break;
12356 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12357 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12358 		break;
12359 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12360 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12361 		break;
12362 	default:
12363 		rc = ENOTTY;
12364 	}
12365 
12366 	return (rc);
12367 }
12368 
12369 #ifdef TCP_OFFLOAD
12370 static int
12371 toe_capability(struct vi_info *vi, bool enable)
12372 {
12373 	int rc;
12374 	struct port_info *pi = vi->pi;
12375 	struct adapter *sc = pi->adapter;
12376 
12377 	ASSERT_SYNCHRONIZED_OP(sc);
12378 
12379 	if (!is_offload(sc))
12380 		return (ENODEV);
12381 	if (hw_off_limits(sc))
12382 		return (ENXIO);
12383 
12384 	if (enable) {
12385 #ifdef KERN_TLS
12386 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12387 			int i, j, n;
12388 			struct port_info *p;
12389 			struct vi_info *v;
12390 
12391 			/*
12392 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12393 			 * on any ifnet.
12394 			 */
12395 			n = 0;
12396 			for_each_port(sc, i) {
12397 				p = sc->port[i];
12398 				for_each_vi(p, j, v) {
12399 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12400 						CH_WARN(sc,
12401 						    "%s has NIC TLS enabled.\n",
12402 						    device_get_nameunit(v->dev));
12403 						n++;
12404 					}
12405 				}
12406 			}
12407 			if (n > 0) {
12408 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12409 				    "associated with this adapter before "
12410 				    "trying to enable TOE.\n");
12411 				return (EAGAIN);
12412 			}
12413 			rc = t6_config_kern_tls(sc, false);
12414 			if (rc)
12415 				return (rc);
12416 		}
12417 #endif
12418 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12419 			/* TOE is already enabled. */
12420 			return (0);
12421 		}
12422 
12423 		/*
12424 		 * We need the port's queues around so that we're able to send
12425 		 * and receive CPLs to/from the TOE even if the ifnet for this
12426 		 * port has never been UP'd administratively.
12427 		 */
12428 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12429 			return (rc);
12430 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12431 		    ((rc = vi_init(&pi->vi[0])) != 0))
12432 			return (rc);
12433 
12434 		if (isset(&sc->offload_map, pi->port_id)) {
12435 			/* TOE is enabled on another VI of this port. */
12436 			pi->uld_vis++;
12437 			return (0);
12438 		}
12439 
12440 		if (!uld_active(sc, ULD_TOM)) {
12441 			rc = t4_activate_uld(sc, ULD_TOM);
12442 			if (rc == EAGAIN) {
12443 				log(LOG_WARNING,
12444 				    "You must kldload t4_tom.ko before trying "
12445 				    "to enable TOE on a cxgbe interface.\n");
12446 			}
12447 			if (rc != 0)
12448 				return (rc);
12449 			KASSERT(sc->tom_softc != NULL,
12450 			    ("%s: TOM activated but softc NULL", __func__));
12451 			KASSERT(uld_active(sc, ULD_TOM),
12452 			    ("%s: TOM activated but flag not set", __func__));
12453 		}
12454 
12455 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12456 		if (!uld_active(sc, ULD_IWARP))
12457 			(void) t4_activate_uld(sc, ULD_IWARP);
12458 		if (!uld_active(sc, ULD_ISCSI))
12459 			(void) t4_activate_uld(sc, ULD_ISCSI);
12460 
12461 		pi->uld_vis++;
12462 		setbit(&sc->offload_map, pi->port_id);
12463 	} else {
12464 		pi->uld_vis--;
12465 
12466 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12467 			return (0);
12468 
12469 		KASSERT(uld_active(sc, ULD_TOM),
12470 		    ("%s: TOM never initialized?", __func__));
12471 		clrbit(&sc->offload_map, pi->port_id);
12472 	}
12473 
12474 	return (0);
12475 }
12476 
12477 /*
12478  * Add an upper layer driver to the global list.
12479  */
12480 int
12481 t4_register_uld(struct uld_info *ui)
12482 {
12483 	int rc = 0;
12484 	struct uld_info *u;
12485 
12486 	sx_xlock(&t4_uld_list_lock);
12487 	SLIST_FOREACH(u, &t4_uld_list, link) {
12488 	    if (u->uld_id == ui->uld_id) {
12489 		    rc = EEXIST;
12490 		    goto done;
12491 	    }
12492 	}
12493 
12494 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12495 	ui->refcount = 0;
12496 done:
12497 	sx_xunlock(&t4_uld_list_lock);
12498 	return (rc);
12499 }
12500 
12501 int
12502 t4_unregister_uld(struct uld_info *ui)
12503 {
12504 	int rc = EINVAL;
12505 	struct uld_info *u;
12506 
12507 	sx_xlock(&t4_uld_list_lock);
12508 
12509 	SLIST_FOREACH(u, &t4_uld_list, link) {
12510 	    if (u == ui) {
12511 		    if (ui->refcount > 0) {
12512 			    rc = EBUSY;
12513 			    goto done;
12514 		    }
12515 
12516 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12517 		    rc = 0;
12518 		    goto done;
12519 	    }
12520 	}
12521 done:
12522 	sx_xunlock(&t4_uld_list_lock);
12523 	return (rc);
12524 }
12525 
12526 int
12527 t4_activate_uld(struct adapter *sc, int id)
12528 {
12529 	int rc;
12530 	struct uld_info *ui;
12531 
12532 	ASSERT_SYNCHRONIZED_OP(sc);
12533 
12534 	if (id < 0 || id > ULD_MAX)
12535 		return (EINVAL);
12536 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12537 
12538 	sx_slock(&t4_uld_list_lock);
12539 
12540 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12541 		if (ui->uld_id == id) {
12542 			if (!(sc->flags & FULL_INIT_DONE)) {
12543 				rc = adapter_init(sc);
12544 				if (rc != 0)
12545 					break;
12546 			}
12547 
12548 			rc = ui->activate(sc);
12549 			if (rc == 0) {
12550 				setbit(&sc->active_ulds, id);
12551 				ui->refcount++;
12552 			}
12553 			break;
12554 		}
12555 	}
12556 
12557 	sx_sunlock(&t4_uld_list_lock);
12558 
12559 	return (rc);
12560 }
12561 
12562 int
12563 t4_deactivate_uld(struct adapter *sc, int id)
12564 {
12565 	int rc;
12566 	struct uld_info *ui;
12567 
12568 	ASSERT_SYNCHRONIZED_OP(sc);
12569 
12570 	if (id < 0 || id > ULD_MAX)
12571 		return (EINVAL);
12572 	rc = ENXIO;
12573 
12574 	sx_slock(&t4_uld_list_lock);
12575 
12576 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12577 		if (ui->uld_id == id) {
12578 			rc = ui->deactivate(sc);
12579 			if (rc == 0) {
12580 				clrbit(&sc->active_ulds, id);
12581 				ui->refcount--;
12582 			}
12583 			break;
12584 		}
12585 	}
12586 
12587 	sx_sunlock(&t4_uld_list_lock);
12588 
12589 	return (rc);
12590 }
12591 
12592 static int
12593 t4_deactivate_all_uld(struct adapter *sc)
12594 {
12595 	int rc;
12596 	struct uld_info *ui;
12597 
12598 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12599 	if (rc != 0)
12600 		return (ENXIO);
12601 
12602 	sx_slock(&t4_uld_list_lock);
12603 
12604 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12605 		if (isset(&sc->active_ulds, ui->uld_id)) {
12606 			rc = ui->deactivate(sc);
12607 			if (rc != 0)
12608 				break;
12609 			clrbit(&sc->active_ulds, ui->uld_id);
12610 			ui->refcount--;
12611 		}
12612 	}
12613 
12614 	sx_sunlock(&t4_uld_list_lock);
12615 	end_synchronized_op(sc, 0);
12616 
12617 	return (rc);
12618 }
12619 
12620 static void
12621 t4_async_event(struct adapter *sc)
12622 {
12623 	struct uld_info *ui;
12624 
12625 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12626 		return;
12627 	sx_slock(&t4_uld_list_lock);
12628 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12629 		if (ui->uld_id == ULD_IWARP) {
12630 			ui->async_event(sc);
12631 			break;
12632 		}
12633 	}
12634 	sx_sunlock(&t4_uld_list_lock);
12635 	end_synchronized_op(sc, 0);
12636 }
12637 
12638 int
12639 uld_active(struct adapter *sc, int uld_id)
12640 {
12641 
12642 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12643 
12644 	return (isset(&sc->active_ulds, uld_id));
12645 }
12646 #endif
12647 
12648 #ifdef KERN_TLS
12649 static int
12650 ktls_capability(struct adapter *sc, bool enable)
12651 {
12652 	ASSERT_SYNCHRONIZED_OP(sc);
12653 
12654 	if (!is_ktls(sc))
12655 		return (ENODEV);
12656 	if (!is_t6(sc))
12657 		return (0);
12658 	if (hw_off_limits(sc))
12659 		return (ENXIO);
12660 
12661 	if (enable) {
12662 		if (sc->flags & KERN_TLS_ON)
12663 			return (0);	/* already on */
12664 		if (sc->offload_map != 0) {
12665 			CH_WARN(sc,
12666 			    "Disable TOE on all interfaces associated with "
12667 			    "this adapter before trying to enable NIC TLS.\n");
12668 			return (EAGAIN);
12669 		}
12670 		return (t6_config_kern_tls(sc, true));
12671 	} else {
12672 		/*
12673 		 * Nothing to do for disable.  If TOE is enabled sometime later
12674 		 * then toe_capability will reconfigure the hardware.
12675 		 */
12676 		return (0);
12677 	}
12678 }
12679 #endif
12680 
12681 /*
12682  * t  = ptr to tunable.
12683  * nc = number of CPUs.
12684  * c  = compiled in default for that tunable.
12685  */
12686 static void
12687 calculate_nqueues(int *t, int nc, const int c)
12688 {
12689 	int nq;
12690 
12691 	if (*t > 0)
12692 		return;
12693 	nq = *t < 0 ? -*t : c;
12694 	*t = min(nc, nq);
12695 }
12696 
12697 /*
12698  * Come up with reasonable defaults for some of the tunables, provided they're
12699  * not set by the user (in which case we'll use the values as is).
12700  */
12701 static void
12702 tweak_tunables(void)
12703 {
12704 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12705 
12706 	if (t4_ntxq < 1) {
12707 #ifdef RSS
12708 		t4_ntxq = rss_getnumbuckets();
12709 #else
12710 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12711 #endif
12712 	}
12713 
12714 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12715 
12716 	if (t4_nrxq < 1) {
12717 #ifdef RSS
12718 		t4_nrxq = rss_getnumbuckets();
12719 #else
12720 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12721 #endif
12722 	}
12723 
12724 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12725 
12726 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12727 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12728 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12729 #endif
12730 #ifdef TCP_OFFLOAD
12731 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12732 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12733 #endif
12734 
12735 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12736 	if (t4_toecaps_allowed == -1)
12737 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12738 #else
12739 	if (t4_toecaps_allowed == -1)
12740 		t4_toecaps_allowed = 0;
12741 #endif
12742 
12743 #ifdef TCP_OFFLOAD
12744 	if (t4_rdmacaps_allowed == -1) {
12745 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12746 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12747 	}
12748 
12749 	if (t4_iscsicaps_allowed == -1) {
12750 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12751 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12752 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12753 	}
12754 
12755 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12756 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12757 
12758 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12759 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12760 #else
12761 	if (t4_rdmacaps_allowed == -1)
12762 		t4_rdmacaps_allowed = 0;
12763 
12764 	if (t4_iscsicaps_allowed == -1)
12765 		t4_iscsicaps_allowed = 0;
12766 #endif
12767 
12768 #ifdef DEV_NETMAP
12769 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12770 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12771 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12772 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12773 #endif
12774 
12775 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12776 		t4_tmr_idx = TMR_IDX;
12777 
12778 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12779 		t4_pktc_idx = PKTC_IDX;
12780 
12781 	if (t4_qsize_txq < 128)
12782 		t4_qsize_txq = 128;
12783 
12784 	if (t4_qsize_rxq < 128)
12785 		t4_qsize_rxq = 128;
12786 	while (t4_qsize_rxq & 7)
12787 		t4_qsize_rxq++;
12788 
12789 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12790 
12791 	/*
12792 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12793 	 * VI for the port.  The rest are additional virtual interfaces on the
12794 	 * same physical port.  Note that the main VI does not have native
12795 	 * netmap support but the extra VIs do.
12796 	 *
12797 	 * Limit the number of VIs per port to the number of available
12798 	 * MAC addresses per port.
12799 	 */
12800 	if (t4_num_vis < 1)
12801 		t4_num_vis = 1;
12802 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12803 		t4_num_vis = nitems(vi_mac_funcs);
12804 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12805 	}
12806 
12807 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12808 		pcie_relaxed_ordering = 1;
12809 #if defined(__i386__) || defined(__amd64__)
12810 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12811 			pcie_relaxed_ordering = 0;
12812 #endif
12813 	}
12814 }
12815 
12816 #ifdef DDB
12817 static void
12818 t4_dump_tcb(struct adapter *sc, int tid)
12819 {
12820 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12821 
12822 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12823 	save = t4_read_reg(sc, reg);
12824 	base = sc->memwin[2].mw_base;
12825 
12826 	/* Dump TCB for the tid */
12827 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12828 	tcb_addr += tid * TCB_SIZE;
12829 
12830 	if (is_t4(sc)) {
12831 		pf = 0;
12832 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12833 	} else {
12834 		pf = V_PFNUM(sc->pf);
12835 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12836 	}
12837 	t4_write_reg(sc, reg, win_pos | pf);
12838 	t4_read_reg(sc, reg);
12839 
12840 	off = tcb_addr - win_pos;
12841 	for (i = 0; i < 4; i++) {
12842 		uint32_t buf[8];
12843 		for (j = 0; j < 8; j++, off += 4)
12844 			buf[j] = htonl(t4_read_reg(sc, base + off));
12845 
12846 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12847 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12848 		    buf[7]);
12849 	}
12850 
12851 	t4_write_reg(sc, reg, save);
12852 	t4_read_reg(sc, reg);
12853 }
12854 
12855 static void
12856 t4_dump_devlog(struct adapter *sc)
12857 {
12858 	struct devlog_params *dparams = &sc->params.devlog;
12859 	struct fw_devlog_e e;
12860 	int i, first, j, m, nentries, rc;
12861 	uint64_t ftstamp = UINT64_MAX;
12862 
12863 	if (dparams->start == 0) {
12864 		db_printf("devlog params not valid\n");
12865 		return;
12866 	}
12867 
12868 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12869 	m = fwmtype_to_hwmtype(dparams->memtype);
12870 
12871 	/* Find the first entry. */
12872 	first = -1;
12873 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12874 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12875 		    sizeof(e), (void *)&e);
12876 		if (rc != 0)
12877 			break;
12878 
12879 		if (e.timestamp == 0)
12880 			break;
12881 
12882 		e.timestamp = be64toh(e.timestamp);
12883 		if (e.timestamp < ftstamp) {
12884 			ftstamp = e.timestamp;
12885 			first = i;
12886 		}
12887 	}
12888 
12889 	if (first == -1)
12890 		return;
12891 
12892 	i = first;
12893 	do {
12894 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12895 		    sizeof(e), (void *)&e);
12896 		if (rc != 0)
12897 			return;
12898 
12899 		if (e.timestamp == 0)
12900 			return;
12901 
12902 		e.timestamp = be64toh(e.timestamp);
12903 		e.seqno = be32toh(e.seqno);
12904 		for (j = 0; j < 8; j++)
12905 			e.params[j] = be32toh(e.params[j]);
12906 
12907 		db_printf("%10d  %15ju  %8s  %8s  ",
12908 		    e.seqno, e.timestamp,
12909 		    (e.level < nitems(devlog_level_strings) ?
12910 			devlog_level_strings[e.level] : "UNKNOWN"),
12911 		    (e.facility < nitems(devlog_facility_strings) ?
12912 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12913 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12914 		    e.params[3], e.params[4], e.params[5], e.params[6],
12915 		    e.params[7]);
12916 
12917 		if (++i == nentries)
12918 			i = 0;
12919 	} while (i != first && !db_pager_quit);
12920 }
12921 
12922 static DB_DEFINE_TABLE(show, t4, show_t4);
12923 
12924 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12925 {
12926 	device_t dev;
12927 	int t;
12928 	bool valid;
12929 
12930 	valid = false;
12931 	t = db_read_token();
12932 	if (t == tIDENT) {
12933 		dev = device_lookup_by_name(db_tok_string);
12934 		valid = true;
12935 	}
12936 	db_skip_to_eol();
12937 	if (!valid) {
12938 		db_printf("usage: show t4 devlog <nexus>\n");
12939 		return;
12940 	}
12941 
12942 	if (dev == NULL) {
12943 		db_printf("device not found\n");
12944 		return;
12945 	}
12946 
12947 	t4_dump_devlog(device_get_softc(dev));
12948 }
12949 
12950 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12951 {
12952 	device_t dev;
12953 	int radix, tid, t;
12954 	bool valid;
12955 
12956 	valid = false;
12957 	radix = db_radix;
12958 	db_radix = 10;
12959 	t = db_read_token();
12960 	if (t == tIDENT) {
12961 		dev = device_lookup_by_name(db_tok_string);
12962 		t = db_read_token();
12963 		if (t == tNUMBER) {
12964 			tid = db_tok_number;
12965 			valid = true;
12966 		}
12967 	}
12968 	db_radix = radix;
12969 	db_skip_to_eol();
12970 	if (!valid) {
12971 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12972 		return;
12973 	}
12974 
12975 	if (dev == NULL) {
12976 		db_printf("device not found\n");
12977 		return;
12978 	}
12979 	if (tid < 0) {
12980 		db_printf("invalid tid\n");
12981 		return;
12982 	}
12983 
12984 	t4_dump_tcb(device_get_softc(dev), tid);
12985 }
12986 #endif
12987 
12988 static eventhandler_tag vxlan_start_evtag;
12989 static eventhandler_tag vxlan_stop_evtag;
12990 
12991 struct vxlan_evargs {
12992 	if_t ifp;
12993 	uint16_t port;
12994 };
12995 
12996 static void
12997 enable_vxlan_rx(struct adapter *sc)
12998 {
12999 	int i, rc;
13000 	struct port_info *pi;
13001 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13002 
13003 	ASSERT_SYNCHRONIZED_OP(sc);
13004 
13005 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13006 	    F_VXLAN_EN);
13007 	for_each_port(sc, i) {
13008 		pi = sc->port[i];
13009 		if (pi->vxlan_tcam_entry == true)
13010 			continue;
13011 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13012 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13013 		    true);
13014 		if (rc < 0) {
13015 			rc = -rc;
13016 			CH_ERR(&pi->vi[0],
13017 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13018 		} else {
13019 			MPASS(rc == sc->rawf_base + pi->port_id);
13020 			pi->vxlan_tcam_entry = true;
13021 		}
13022 	}
13023 }
13024 
13025 static void
13026 t4_vxlan_start(struct adapter *sc, void *arg)
13027 {
13028 	struct vxlan_evargs *v = arg;
13029 
13030 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13031 		return;
13032 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13033 		return;
13034 
13035 	if (sc->vxlan_refcount == 0) {
13036 		sc->vxlan_port = v->port;
13037 		sc->vxlan_refcount = 1;
13038 		if (!hw_off_limits(sc))
13039 			enable_vxlan_rx(sc);
13040 	} else if (sc->vxlan_port == v->port) {
13041 		sc->vxlan_refcount++;
13042 	} else {
13043 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13044 		    "ignoring attempt to configure it on port %d\n",
13045 		    sc->vxlan_port, v->port);
13046 	}
13047 	end_synchronized_op(sc, 0);
13048 }
13049 
13050 static void
13051 t4_vxlan_stop(struct adapter *sc, void *arg)
13052 {
13053 	struct vxlan_evargs *v = arg;
13054 
13055 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13056 		return;
13057 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13058 		return;
13059 
13060 	/*
13061 	 * VXLANs may have been configured before the driver was loaded so we
13062 	 * may see more stops than starts.  This is not handled cleanly but at
13063 	 * least we keep the refcount sane.
13064 	 */
13065 	if (sc->vxlan_port != v->port)
13066 		goto done;
13067 	if (sc->vxlan_refcount == 0) {
13068 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13069 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13070 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13071 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13072 done:
13073 	end_synchronized_op(sc, 0);
13074 }
13075 
13076 static void
13077 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13078     sa_family_t family, u_int port)
13079 {
13080 	struct vxlan_evargs v;
13081 
13082 	MPASS(family == AF_INET || family == AF_INET6);
13083 	v.ifp = ifp;
13084 	v.port = port;
13085 
13086 	t4_iterate(t4_vxlan_start, &v);
13087 }
13088 
13089 static void
13090 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13091     u_int port)
13092 {
13093 	struct vxlan_evargs v;
13094 
13095 	MPASS(family == AF_INET || family == AF_INET6);
13096 	v.ifp = ifp;
13097 	v.port = port;
13098 
13099 	t4_iterate(t4_vxlan_stop, &v);
13100 }
13101 
13102 
13103 static struct sx mlu;	/* mod load unload */
13104 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13105 
13106 static int
13107 mod_event(module_t mod, int cmd, void *arg)
13108 {
13109 	int rc = 0;
13110 	static int loaded = 0;
13111 
13112 	switch (cmd) {
13113 	case MOD_LOAD:
13114 		sx_xlock(&mlu);
13115 		if (loaded++ == 0) {
13116 			t4_sge_modload();
13117 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13118 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13119 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13120 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13121 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13122 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13123 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13124 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13125 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13126 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13127 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13128 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13129 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13130 			    do_smt_write_rpl);
13131 			sx_init(&t4_list_lock, "T4/T5 adapters");
13132 			SLIST_INIT(&t4_list);
13133 			callout_init(&fatal_callout, 1);
13134 #ifdef TCP_OFFLOAD
13135 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13136 			SLIST_INIT(&t4_uld_list);
13137 #endif
13138 #ifdef INET6
13139 			t4_clip_modload();
13140 #endif
13141 #ifdef KERN_TLS
13142 			t6_ktls_modload();
13143 #endif
13144 			t4_tracer_modload();
13145 			tweak_tunables();
13146 			vxlan_start_evtag =
13147 			    EVENTHANDLER_REGISTER(vxlan_start,
13148 				t4_vxlan_start_handler, NULL,
13149 				EVENTHANDLER_PRI_ANY);
13150 			vxlan_stop_evtag =
13151 			    EVENTHANDLER_REGISTER(vxlan_stop,
13152 				t4_vxlan_stop_handler, NULL,
13153 				EVENTHANDLER_PRI_ANY);
13154 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13155 			    taskqueue_thread_enqueue, &reset_tq);
13156 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13157 			    "t4_rst_thr");
13158 		}
13159 		sx_xunlock(&mlu);
13160 		break;
13161 
13162 	case MOD_UNLOAD:
13163 		sx_xlock(&mlu);
13164 		if (--loaded == 0) {
13165 			int tries;
13166 
13167 			taskqueue_free(reset_tq);
13168 			sx_slock(&t4_list_lock);
13169 			if (!SLIST_EMPTY(&t4_list)) {
13170 				rc = EBUSY;
13171 				sx_sunlock(&t4_list_lock);
13172 				goto done_unload;
13173 			}
13174 #ifdef TCP_OFFLOAD
13175 			sx_slock(&t4_uld_list_lock);
13176 			if (!SLIST_EMPTY(&t4_uld_list)) {
13177 				rc = EBUSY;
13178 				sx_sunlock(&t4_uld_list_lock);
13179 				sx_sunlock(&t4_list_lock);
13180 				goto done_unload;
13181 			}
13182 #endif
13183 			tries = 0;
13184 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13185 				uprintf("%ju clusters with custom free routine "
13186 				    "still is use.\n", t4_sge_extfree_refs());
13187 				pause("t4unload", 2 * hz);
13188 			}
13189 #ifdef TCP_OFFLOAD
13190 			sx_sunlock(&t4_uld_list_lock);
13191 #endif
13192 			sx_sunlock(&t4_list_lock);
13193 
13194 			if (t4_sge_extfree_refs() == 0) {
13195 				EVENTHANDLER_DEREGISTER(vxlan_start,
13196 				    vxlan_start_evtag);
13197 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13198 				    vxlan_stop_evtag);
13199 				t4_tracer_modunload();
13200 #ifdef KERN_TLS
13201 				t6_ktls_modunload();
13202 #endif
13203 #ifdef INET6
13204 				t4_clip_modunload();
13205 #endif
13206 #ifdef TCP_OFFLOAD
13207 				sx_destroy(&t4_uld_list_lock);
13208 #endif
13209 				sx_destroy(&t4_list_lock);
13210 				t4_sge_modunload();
13211 				loaded = 0;
13212 			} else {
13213 				rc = EBUSY;
13214 				loaded++;	/* undo earlier decrement */
13215 			}
13216 		}
13217 done_unload:
13218 		sx_xunlock(&mlu);
13219 		break;
13220 	}
13221 
13222 	return (rc);
13223 }
13224 
13225 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13226 MODULE_VERSION(t4nex, 1);
13227 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13228 #ifdef DEV_NETMAP
13229 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13230 #endif /* DEV_NETMAP */
13231 
13232 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13233 MODULE_VERSION(t5nex, 1);
13234 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13235 #ifdef DEV_NETMAP
13236 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13237 #endif /* DEV_NETMAP */
13238 
13239 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13240 MODULE_VERSION(t6nex, 1);
13241 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13242 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13243 #ifdef DEV_NETMAP
13244 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13245 #endif /* DEV_NETMAP */
13246 
13247 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13248 MODULE_VERSION(cxgbe, 1);
13249 
13250 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13251 MODULE_VERSION(cxl, 1);
13252 
13253 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13254 MODULE_VERSION(cc, 1);
13255 
13256 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13257 MODULE_VERSION(vcxgbe, 1);
13258 
13259 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13260 MODULE_VERSION(vcxl, 1);
13261 
13262 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13263 MODULE_VERSION(vcc, 1);
13264