xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 024248c933c5741a21c17eda63092f330dd98337)
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 struct uld_info *t4_uld_list[ULD_MAX + 1];
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 
416 int t4_ddp_rcvbuf_len = 256 * 1024;
417 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_len, CTLFLAG_RWTUN,
418     &t4_ddp_rcvbuf_len, 0, "length of each DDP RX buffer");
419 
420 unsigned int t4_ddp_rcvbuf_cache = 4;
421 SYSCTL_UINT(_hw_cxgbe_toe, OID_AUTO, ddp_rcvbuf_cache, CTLFLAG_RWTUN,
422     &t4_ddp_rcvbuf_cache, 0,
423     "maximum number of free DDP RX buffers to cache per connection");
424 #endif
425 
426 #ifdef DEV_NETMAP
427 #define NN_MAIN_VI	(1 << 0)	/* Native netmap on the main VI */
428 #define NN_EXTRA_VI	(1 << 1)	/* Native netmap on the extra VI(s) */
429 static int t4_native_netmap = NN_EXTRA_VI;
430 SYSCTL_INT(_hw_cxgbe, OID_AUTO, native_netmap, CTLFLAG_RDTUN, &t4_native_netmap,
431     0, "Native netmap support.  bit 0 = main VI, bit 1 = extra VIs");
432 
433 #define NNMTXQ 8
434 static int t4_nnmtxq = -NNMTXQ;
435 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq, CTLFLAG_RDTUN, &t4_nnmtxq, 0,
436     "Number of netmap TX queues");
437 
438 #define NNMRXQ 8
439 static int t4_nnmrxq = -NNMRXQ;
440 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq, CTLFLAG_RDTUN, &t4_nnmrxq, 0,
441     "Number of netmap RX queues");
442 
443 #define NNMTXQ_VI 2
444 static int t4_nnmtxq_vi = -NNMTXQ_VI;
445 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmtxq_vi, CTLFLAG_RDTUN, &t4_nnmtxq_vi, 0,
446     "Number of netmap TX queues per VI");
447 
448 #define NNMRXQ_VI 2
449 static int t4_nnmrxq_vi = -NNMRXQ_VI;
450 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nnmrxq_vi, CTLFLAG_RDTUN, &t4_nnmrxq_vi, 0,
451     "Number of netmap RX queues per VI");
452 #endif
453 
454 /*
455  * Holdoff parameters for ports.
456  */
457 #define TMR_IDX 1
458 int t4_tmr_idx = TMR_IDX;
459 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx, CTLFLAG_RDTUN, &t4_tmr_idx,
460     0, "Holdoff timer index");
461 TUNABLE_INT("hw.cxgbe.holdoff_timer_idx_10G", &t4_tmr_idx);	/* Old name */
462 
463 #define PKTC_IDX (-1)
464 int t4_pktc_idx = PKTC_IDX;
465 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx, CTLFLAG_RDTUN, &t4_pktc_idx,
466     0, "Holdoff packet counter index");
467 TUNABLE_INT("hw.cxgbe.holdoff_pktc_idx_10G", &t4_pktc_idx);	/* Old name */
468 
469 /*
470  * Size (# of entries) of each tx and rx queue.
471  */
472 unsigned int t4_qsize_txq = TX_EQ_QSIZE;
473 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_txq, CTLFLAG_RDTUN, &t4_qsize_txq, 0,
474     "Number of descriptors in each TX queue");
475 
476 unsigned int t4_qsize_rxq = RX_IQ_QSIZE;
477 SYSCTL_INT(_hw_cxgbe, OID_AUTO, qsize_rxq, CTLFLAG_RDTUN, &t4_qsize_rxq, 0,
478     "Number of descriptors in each RX queue");
479 
480 /*
481  * Interrupt types allowed (bits 0, 1, 2 = INTx, MSI, MSI-X respectively).
482  */
483 int t4_intr_types = INTR_MSIX | INTR_MSI | INTR_INTX;
484 SYSCTL_INT(_hw_cxgbe, OID_AUTO, interrupt_types, CTLFLAG_RDTUN, &t4_intr_types,
485     0, "Interrupt types allowed (bit 0 = INTx, 1 = MSI, 2 = MSI-X)");
486 
487 /*
488  * Configuration file.  All the _CF names here are special.
489  */
490 #define DEFAULT_CF	"default"
491 #define BUILTIN_CF	"built-in"
492 #define FLASH_CF	"flash"
493 #define UWIRE_CF	"uwire"
494 #define FPGA_CF		"fpga"
495 static char t4_cfg_file[32] = DEFAULT_CF;
496 SYSCTL_STRING(_hw_cxgbe, OID_AUTO, config_file, CTLFLAG_RDTUN, t4_cfg_file,
497     sizeof(t4_cfg_file), "Firmware configuration file");
498 
499 /*
500  * PAUSE settings (bit 0, 1, 2 = rx_pause, tx_pause, pause_autoneg respectively).
501  * rx_pause = 1 to heed incoming PAUSE frames, 0 to ignore them.
502  * tx_pause = 1 to emit PAUSE frames when the rx FIFO reaches its high water
503  *            mark or when signalled to do so, 0 to never emit PAUSE.
504  * pause_autoneg = 1 means PAUSE will be negotiated if possible and the
505  *                 negotiated settings will override rx_pause/tx_pause.
506  *                 Otherwise rx_pause/tx_pause are applied forcibly.
507  */
508 static int t4_pause_settings = PAUSE_RX | PAUSE_TX | PAUSE_AUTONEG;
509 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pause_settings, CTLFLAG_RDTUN,
510     &t4_pause_settings, 0,
511     "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
512 
513 /*
514  * Forward Error Correction settings (bit 0, 1 = RS, BASER respectively).
515  * -1 to run with the firmware default.  Same as FEC_AUTO (bit 5)
516  *  0 to disable FEC.
517  */
518 static int t4_fec = -1;
519 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fec, CTLFLAG_RDTUN, &t4_fec, 0,
520     "Forward Error Correction (bit 0 = RS, bit 1 = BASER_RS)");
521 
522 /*
523  * Controls when the driver sets the FORCE_FEC bit in the L1_CFG32 that it
524  * issues to the firmware.  If the firmware doesn't support FORCE_FEC then the
525  * driver runs as if this is set to 0.
526  * -1 to set FORCE_FEC iff requested_fec != AUTO. Multiple FEC bits are okay.
527  *  0 to never set FORCE_FEC. requested_fec = AUTO means use the hint from the
528  *    transceiver. Multiple FEC bits may not be okay but will be passed on to
529  *    the firmware anyway (may result in l1cfg errors with old firmwares).
530  *  1 to always set FORCE_FEC. Multiple FEC bits are okay. requested_fec = AUTO
531  *    means set all FEC bits that are valid for the speed.
532  */
533 static int t4_force_fec = -1;
534 SYSCTL_INT(_hw_cxgbe, OID_AUTO, force_fec, CTLFLAG_RDTUN, &t4_force_fec, 0,
535     "Controls the use of FORCE_FEC bit in L1 configuration.");
536 
537 /*
538  * Link autonegotiation.
539  * -1 to run with the firmware default.
540  *  0 to disable.
541  *  1 to enable.
542  */
543 static int t4_autoneg = -1;
544 SYSCTL_INT(_hw_cxgbe, OID_AUTO, autoneg, CTLFLAG_RDTUN, &t4_autoneg, 0,
545     "Link autonegotiation");
546 
547 /*
548  * Firmware auto-install by driver during attach (0, 1, 2 = prohibited, allowed,
549  * encouraged respectively).  '-n' is the same as 'n' except the firmware
550  * version used in the checks is read from the firmware bundled with the driver.
551  */
552 static int t4_fw_install = 1;
553 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fw_install, CTLFLAG_RDTUN, &t4_fw_install, 0,
554     "Firmware auto-install (0 = prohibited, 1 = allowed, 2 = encouraged)");
555 
556 /*
557  * ASIC features that will be used.  Disable the ones you don't want so that the
558  * chip resources aren't wasted on features that will not be used.
559  */
560 static int t4_nbmcaps_allowed = 0;
561 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nbmcaps_allowed, CTLFLAG_RDTUN,
562     &t4_nbmcaps_allowed, 0, "Default NBM capabilities");
563 
564 static int t4_linkcaps_allowed = 0;	/* No DCBX, PPP, etc. by default */
565 SYSCTL_INT(_hw_cxgbe, OID_AUTO, linkcaps_allowed, CTLFLAG_RDTUN,
566     &t4_linkcaps_allowed, 0, "Default link capabilities");
567 
568 static int t4_switchcaps_allowed = FW_CAPS_CONFIG_SWITCH_INGRESS |
569     FW_CAPS_CONFIG_SWITCH_EGRESS;
570 SYSCTL_INT(_hw_cxgbe, OID_AUTO, switchcaps_allowed, CTLFLAG_RDTUN,
571     &t4_switchcaps_allowed, 0, "Default switch capabilities");
572 
573 #ifdef RATELIMIT
574 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
575 	FW_CAPS_CONFIG_NIC_HASHFILTER | FW_CAPS_CONFIG_NIC_ETHOFLD;
576 #else
577 static int t4_niccaps_allowed = FW_CAPS_CONFIG_NIC |
578 	FW_CAPS_CONFIG_NIC_HASHFILTER;
579 #endif
580 SYSCTL_INT(_hw_cxgbe, OID_AUTO, niccaps_allowed, CTLFLAG_RDTUN,
581     &t4_niccaps_allowed, 0, "Default NIC capabilities");
582 
583 static int t4_toecaps_allowed = -1;
584 SYSCTL_INT(_hw_cxgbe, OID_AUTO, toecaps_allowed, CTLFLAG_RDTUN,
585     &t4_toecaps_allowed, 0, "Default TCP offload capabilities");
586 
587 static int t4_rdmacaps_allowed = -1;
588 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rdmacaps_allowed, CTLFLAG_RDTUN,
589     &t4_rdmacaps_allowed, 0, "Default RDMA capabilities");
590 
591 static int t4_cryptocaps_allowed = -1;
592 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cryptocaps_allowed, CTLFLAG_RDTUN,
593     &t4_cryptocaps_allowed, 0, "Default crypto capabilities");
594 
595 static int t4_iscsicaps_allowed = -1;
596 SYSCTL_INT(_hw_cxgbe, OID_AUTO, iscsicaps_allowed, CTLFLAG_RDTUN,
597     &t4_iscsicaps_allowed, 0, "Default iSCSI capabilities");
598 
599 static int t4_fcoecaps_allowed = 0;
600 SYSCTL_INT(_hw_cxgbe, OID_AUTO, fcoecaps_allowed, CTLFLAG_RDTUN,
601     &t4_fcoecaps_allowed, 0, "Default FCoE capabilities");
602 
603 static int t5_write_combine = 0;
604 SYSCTL_INT(_hw_cxl, OID_AUTO, write_combine, CTLFLAG_RDTUN, &t5_write_combine,
605     0, "Use WC instead of UC for BAR2");
606 
607 /* From t4_sysctls: doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"} */
608 static int t4_doorbells_allowed = 0xf;
609 SYSCTL_INT(_hw_cxgbe, OID_AUTO, doorbells_allowed, CTLFLAG_RDTUN,
610 	   &t4_doorbells_allowed, 0, "Limit tx queues to these doorbells");
611 
612 static int t4_num_vis = 1;
613 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
614     "Number of VIs per port");
615 
616 /*
617  * PCIe Relaxed Ordering.
618  * -1: driver should figure out a good value.
619  * 0: disable RO.
620  * 1: enable RO.
621  * 2: leave RO alone.
622  */
623 static int pcie_relaxed_ordering = -1;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
625     &pcie_relaxed_ordering, 0,
626     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
627 
628 static int t4_panic_on_fatal_err = 0;
629 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
630     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
631 
632 static int t4_reset_on_fatal_err = 0;
633 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
634     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
635 
636 static int t4_clock_gate_on_suspend = 0;
637 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
638     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
639 
640 static int t4_tx_vm_wr = 0;
641 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
642     "Use VM work requests to transmit packets.");
643 
644 /*
645  * Set to non-zero to enable the attack filter.  A packet that matches any of
646  * these conditions will get dropped on ingress:
647  * 1) IP && source address == destination address.
648  * 2) TCP/IP && source address is not a unicast address.
649  * 3) TCP/IP && destination address is not a unicast address.
650  * 4) IP && source address is loopback (127.x.y.z).
651  * 5) IP && destination address is loopback (127.x.y.z).
652  * 6) IPv6 && source address == destination address.
653  * 7) IPv6 && source address is not a unicast address.
654  * 8) IPv6 && source address is loopback (::1/128).
655  * 9) IPv6 && destination address is loopback (::1/128).
656  * 10) IPv6 && source address is unspecified (::/128).
657  * 11) IPv6 && destination address is unspecified (::/128).
658  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
659  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
660  */
661 static int t4_attack_filter = 0;
662 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
663     &t4_attack_filter, 0, "Drop suspicious traffic");
664 
665 static int t4_drop_ip_fragments = 0;
666 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
667     &t4_drop_ip_fragments, 0, "Drop IP fragments");
668 
669 static int t4_drop_pkts_with_l2_errors = 1;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
671     &t4_drop_pkts_with_l2_errors, 0,
672     "Drop all frames with Layer 2 length or checksum errors");
673 
674 static int t4_drop_pkts_with_l3_errors = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l3_errors, 0,
677     "Drop all frames with IP version, length, or checksum errors");
678 
679 static int t4_drop_pkts_with_l4_errors = 0;
680 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
681     &t4_drop_pkts_with_l4_errors, 0,
682     "Drop all frames with Layer 4 length, checksum, or other errors");
683 
684 #ifdef TCP_OFFLOAD
685 /*
686  * TOE tunables.
687  */
688 static int t4_cop_managed_offloading = 0;
689 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
690     &t4_cop_managed_offloading, 0,
691     "COP (Connection Offload Policy) controls all TOE offload");
692 #endif
693 
694 #ifdef KERN_TLS
695 /*
696  * This enables KERN_TLS for all adapters if set.
697  */
698 static int t4_kern_tls = 0;
699 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
700     "Enable KERN_TLS mode for T6 adapters");
701 
702 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
703     "cxgbe(4) KERN_TLS parameters");
704 
705 static int t4_tls_inline_keys = 0;
706 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
707     &t4_tls_inline_keys, 0,
708     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
709     "in card memory.");
710 
711 static int t4_tls_combo_wrs = 0;
712 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
713     0, "Attempt to combine TCB field updates with TLS record work requests.");
714 #endif
715 
716 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
717 static int vi_mac_funcs[] = {
718 	FW_VI_FUNC_ETH,
719 	FW_VI_FUNC_OFLD,
720 	FW_VI_FUNC_IWARP,
721 	FW_VI_FUNC_OPENISCSI,
722 	FW_VI_FUNC_OPENFCOE,
723 	FW_VI_FUNC_FOISCSI,
724 	FW_VI_FUNC_FOFCOE,
725 };
726 
727 struct intrs_and_queues {
728 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
729 	uint16_t num_vis;	/* number of VIs for each port */
730 	uint16_t nirq;		/* Total # of vectors */
731 	uint16_t ntxq;		/* # of NIC txq's for each port */
732 	uint16_t nrxq;		/* # of NIC rxq's for each port */
733 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
734 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
735 	uint16_t nnmtxq;	/* # of netmap txq's */
736 	uint16_t nnmrxq;	/* # of netmap rxq's */
737 
738 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
739 	uint16_t ntxq_vi;	/* # of NIC txq's */
740 	uint16_t nrxq_vi;	/* # of NIC rxq's */
741 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
742 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
743 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
744 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
745 };
746 
747 static void setup_memwin(struct adapter *);
748 static void position_memwin(struct adapter *, int, uint32_t);
749 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
750 static int fwmtype_to_hwmtype(int);
751 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
752     uint32_t *);
753 static int fixup_devlog_params(struct adapter *);
754 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
755 static int contact_firmware(struct adapter *);
756 static int partition_resources(struct adapter *);
757 static int get_params__pre_init(struct adapter *);
758 static int set_params__pre_init(struct adapter *);
759 static int get_params__post_init(struct adapter *);
760 static int set_params__post_init(struct adapter *);
761 static void t4_set_desc(struct adapter *);
762 static bool fixed_ifmedia(struct port_info *);
763 static void build_medialist(struct port_info *);
764 static void init_link_config(struct port_info *);
765 static int fixup_link_config(struct port_info *);
766 static int apply_link_config(struct port_info *);
767 static int cxgbe_init_synchronized(struct vi_info *);
768 static int cxgbe_uninit_synchronized(struct vi_info *);
769 static int adapter_full_init(struct adapter *);
770 static void adapter_full_uninit(struct adapter *);
771 static int vi_full_init(struct vi_info *);
772 static void vi_full_uninit(struct vi_info *);
773 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
774 static void quiesce_txq(struct sge_txq *);
775 static void quiesce_wrq(struct sge_wrq *);
776 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
777 static void quiesce_vi(struct vi_info *);
778 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
779     driver_intr_t *, void *, char *);
780 static int t4_free_irq(struct adapter *, struct irq *);
781 static void t4_init_atid_table(struct adapter *);
782 static void t4_free_atid_table(struct adapter *);
783 static void stop_atid_allocator(struct adapter *);
784 static void restart_atid_allocator(struct adapter *);
785 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
786 static void vi_refresh_stats(struct vi_info *);
787 static void cxgbe_refresh_stats(struct vi_info *);
788 static void cxgbe_tick(void *);
789 static void vi_tick(void *);
790 static void cxgbe_sysctls(struct port_info *);
791 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
792 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
793 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
794 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
795 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
796 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
797 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
798 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
799 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
800 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
801 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
802 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
803 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
804 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
805 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
806 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
807 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
808 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
809 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
810 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
811 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
812 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
813 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
814 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
815 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
816 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
817 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
818 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
819 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
820 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
821 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
822 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
823 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
824 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
825 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
826 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
827 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
828 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
829 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
830 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
831 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
832 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
833 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
834 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
835 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
836 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
837 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
839 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
840 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
841 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
842 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
843 #ifdef TCP_OFFLOAD
844 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
845 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
846 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
847 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
848 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
849 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
850 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
851 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
852 #endif
853 static int get_sge_context(struct adapter *, struct t4_sge_context *);
854 static int load_fw(struct adapter *, struct t4_data *);
855 static int load_cfg(struct adapter *, struct t4_data *);
856 static int load_boot(struct adapter *, struct t4_bootrom *);
857 static int load_bootcfg(struct adapter *, struct t4_data *);
858 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
859 static void free_offload_policy(struct t4_offload_policy *);
860 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
861 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
862 static int read_i2c(struct adapter *, struct t4_i2c_data *);
863 static int clear_stats(struct adapter *, u_int);
864 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
865 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
866 static inline int stop_adapter(struct adapter *);
867 static inline void set_adapter_hwstatus(struct adapter *, const bool);
868 static int stop_lld(struct adapter *);
869 static inline int restart_adapter(struct adapter *);
870 static int restart_lld(struct adapter *);
871 #ifdef TCP_OFFLOAD
872 static int toe_capability(struct vi_info *, bool);
873 static int deactivate_all_uld(struct adapter *);
874 static void stop_all_uld(struct adapter *);
875 static void restart_all_uld(struct adapter *);
876 #endif
877 #ifdef KERN_TLS
878 static int ktls_capability(struct adapter *, bool);
879 #endif
880 static int mod_event(module_t, int, void *);
881 static int notify_siblings(device_t, int);
882 static uint64_t vi_get_counter(if_t, ift_counter);
883 static uint64_t cxgbe_get_counter(if_t, ift_counter);
884 static void enable_vxlan_rx(struct adapter *);
885 static void reset_adapter_task(void *, int);
886 static void fatal_error_task(void *, int);
887 static void dump_devlog(struct adapter *);
888 static void dump_cim_regs(struct adapter *);
889 static void dump_cimla(struct adapter *);
890 
891 struct {
892 	uint16_t device;
893 	char *desc;
894 } t4_pciids[] = {
895 	{0xa000, "Chelsio Terminator 4 FPGA"},
896 	{0x4400, "Chelsio T440-dbg"},
897 	{0x4401, "Chelsio T420-CR"},
898 	{0x4402, "Chelsio T422-CR"},
899 	{0x4403, "Chelsio T440-CR"},
900 	{0x4404, "Chelsio T420-BCH"},
901 	{0x4405, "Chelsio T440-BCH"},
902 	{0x4406, "Chelsio T440-CH"},
903 	{0x4407, "Chelsio T420-SO"},
904 	{0x4408, "Chelsio T420-CX"},
905 	{0x4409, "Chelsio T420-BT"},
906 	{0x440a, "Chelsio T404-BT"},
907 	{0x440e, "Chelsio T440-LP-CR"},
908 }, t5_pciids[] = {
909 	{0xb000, "Chelsio Terminator 5 FPGA"},
910 	{0x5400, "Chelsio T580-dbg"},
911 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
912 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
913 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
914 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
915 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
916 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
917 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
918 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
919 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
920 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
921 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
922 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
923 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
924 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
925 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
926 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
927 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
928 
929 	/* Custom */
930 	{0x5483, "Custom T540-CR"},
931 	{0x5484, "Custom T540-BT"},
932 }, t6_pciids[] = {
933 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
934 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
935 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
936 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
937 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
938 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
939 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
940 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
941 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
942 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
943 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
944 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
945 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
946 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
947 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
948 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
949 
950 	/* Custom */
951 	{0x6480, "Custom T6225-CR"},
952 	{0x6481, "Custom T62100-CR"},
953 	{0x6482, "Custom T6225-CR"},
954 	{0x6483, "Custom T62100-CR"},
955 	{0x6484, "Custom T64100-CR"},
956 	{0x6485, "Custom T6240-SO"},
957 	{0x6486, "Custom T6225-SO-CR"},
958 	{0x6487, "Custom T6225-CR"},
959 };
960 
961 #ifdef TCP_OFFLOAD
962 /*
963  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
964  * be exactly the same for both rxq and ofld_rxq.
965  */
966 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
967 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
968 #endif
969 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
970 
971 static int
972 t4_probe(device_t dev)
973 {
974 	int i;
975 	uint16_t v = pci_get_vendor(dev);
976 	uint16_t d = pci_get_device(dev);
977 	uint8_t f = pci_get_function(dev);
978 
979 	if (v != PCI_VENDOR_ID_CHELSIO)
980 		return (ENXIO);
981 
982 	/* Attach only to PF0 of the FPGA */
983 	if (d == 0xa000 && f != 0)
984 		return (ENXIO);
985 
986 	for (i = 0; i < nitems(t4_pciids); i++) {
987 		if (d == t4_pciids[i].device) {
988 			device_set_desc(dev, t4_pciids[i].desc);
989 			return (BUS_PROBE_DEFAULT);
990 		}
991 	}
992 
993 	return (ENXIO);
994 }
995 
996 static int
997 t5_probe(device_t dev)
998 {
999 	int i;
1000 	uint16_t v = pci_get_vendor(dev);
1001 	uint16_t d = pci_get_device(dev);
1002 	uint8_t f = pci_get_function(dev);
1003 
1004 	if (v != PCI_VENDOR_ID_CHELSIO)
1005 		return (ENXIO);
1006 
1007 	/* Attach only to PF0 of the FPGA */
1008 	if (d == 0xb000 && f != 0)
1009 		return (ENXIO);
1010 
1011 	for (i = 0; i < nitems(t5_pciids); i++) {
1012 		if (d == t5_pciids[i].device) {
1013 			device_set_desc(dev, t5_pciids[i].desc);
1014 			return (BUS_PROBE_DEFAULT);
1015 		}
1016 	}
1017 
1018 	return (ENXIO);
1019 }
1020 
1021 static int
1022 t6_probe(device_t dev)
1023 {
1024 	int i;
1025 	uint16_t v = pci_get_vendor(dev);
1026 	uint16_t d = pci_get_device(dev);
1027 
1028 	if (v != PCI_VENDOR_ID_CHELSIO)
1029 		return (ENXIO);
1030 
1031 	for (i = 0; i < nitems(t6_pciids); i++) {
1032 		if (d == t6_pciids[i].device) {
1033 			device_set_desc(dev, t6_pciids[i].desc);
1034 			return (BUS_PROBE_DEFAULT);
1035 		}
1036 	}
1037 
1038 	return (ENXIO);
1039 }
1040 
1041 static void
1042 t5_attribute_workaround(device_t dev)
1043 {
1044 	device_t root_port;
1045 	uint32_t v;
1046 
1047 	/*
1048 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1049 	 * Ordering attributes when replying to a TLP from a Root
1050 	 * Port.  As a workaround, find the parent Root Port and
1051 	 * disable No Snoop and Relaxed Ordering.  Note that this
1052 	 * affects all devices under this root port.
1053 	 */
1054 	root_port = pci_find_pcie_root_port(dev);
1055 	if (root_port == NULL) {
1056 		device_printf(dev, "Unable to find parent root port\n");
1057 		return;
1058 	}
1059 
1060 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1061 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1062 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1063 	    0)
1064 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1065 		    device_get_nameunit(root_port));
1066 }
1067 
1068 static const struct devnames devnames[] = {
1069 	{
1070 		.nexus_name = "t4nex",
1071 		.ifnet_name = "cxgbe",
1072 		.vi_ifnet_name = "vcxgbe",
1073 		.pf03_drv_name = "t4iov",
1074 		.vf_nexus_name = "t4vf",
1075 		.vf_ifnet_name = "cxgbev"
1076 	}, {
1077 		.nexus_name = "t5nex",
1078 		.ifnet_name = "cxl",
1079 		.vi_ifnet_name = "vcxl",
1080 		.pf03_drv_name = "t5iov",
1081 		.vf_nexus_name = "t5vf",
1082 		.vf_ifnet_name = "cxlv"
1083 	}, {
1084 		.nexus_name = "t6nex",
1085 		.ifnet_name = "cc",
1086 		.vi_ifnet_name = "vcc",
1087 		.pf03_drv_name = "t6iov",
1088 		.vf_nexus_name = "t6vf",
1089 		.vf_ifnet_name = "ccv"
1090 	}
1091 };
1092 
1093 void
1094 t4_init_devnames(struct adapter *sc)
1095 {
1096 	int id;
1097 
1098 	id = chip_id(sc);
1099 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1100 		sc->names = &devnames[id - CHELSIO_T4];
1101 	else {
1102 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1103 		sc->names = NULL;
1104 	}
1105 }
1106 
1107 static int
1108 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1109 {
1110 	const char *parent, *name;
1111 	long value;
1112 	int line, unit;
1113 
1114 	line = 0;
1115 	parent = device_get_nameunit(sc->dev);
1116 	name = sc->names->ifnet_name;
1117 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1118 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1119 		    value == pi->port_id)
1120 			return (unit);
1121 	}
1122 	return (-1);
1123 }
1124 
1125 static void
1126 t4_calibration(void *arg)
1127 {
1128 	struct adapter *sc;
1129 	struct clock_sync *cur, *nex;
1130 	uint64_t hw;
1131 	sbintime_t sbt;
1132 	int next_up;
1133 
1134 	sc = (struct adapter *)arg;
1135 
1136 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1137 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1138 	sbt = sbinuptime();
1139 
1140 	cur = &sc->cal_info[sc->cal_current];
1141 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1142 	nex = &sc->cal_info[next_up];
1143 	if (__predict_false(sc->cal_count == 0)) {
1144 		/* First time in, just get the values in */
1145 		cur->hw_cur = hw;
1146 		cur->sbt_cur = sbt;
1147 		sc->cal_count++;
1148 		goto done;
1149 	}
1150 
1151 	if (cur->hw_cur == hw) {
1152 		/* The clock is not advancing? */
1153 		sc->cal_count = 0;
1154 		atomic_store_rel_int(&cur->gen, 0);
1155 		goto done;
1156 	}
1157 
1158 	seqc_write_begin(&nex->gen);
1159 	nex->hw_prev = cur->hw_cur;
1160 	nex->sbt_prev = cur->sbt_cur;
1161 	nex->hw_cur = hw;
1162 	nex->sbt_cur = sbt;
1163 	seqc_write_end(&nex->gen);
1164 	sc->cal_current = next_up;
1165 done:
1166 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1167 	    sc, C_DIRECT_EXEC);
1168 }
1169 
1170 static void
1171 t4_calibration_start(struct adapter *sc)
1172 {
1173 	/*
1174 	 * Here if we have not done a calibration
1175 	 * then do so otherwise start the appropriate
1176 	 * timer.
1177 	 */
1178 	int i;
1179 
1180 	for (i = 0; i < CNT_CAL_INFO; i++) {
1181 		sc->cal_info[i].gen = 0;
1182 	}
1183 	sc->cal_current = 0;
1184 	sc->cal_count = 0;
1185 	sc->cal_gen = 0;
1186 	t4_calibration(sc);
1187 }
1188 
1189 static int
1190 t4_attach(device_t dev)
1191 {
1192 	struct adapter *sc;
1193 	int rc = 0, i, j, rqidx, tqidx, nports;
1194 	struct make_dev_args mda;
1195 	struct intrs_and_queues iaq;
1196 	struct sge *s;
1197 	uint32_t *buf;
1198 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1199 	int ofld_tqidx;
1200 #endif
1201 #ifdef TCP_OFFLOAD
1202 	int ofld_rqidx;
1203 #endif
1204 #ifdef DEV_NETMAP
1205 	int nm_rqidx, nm_tqidx;
1206 #endif
1207 	int num_vis;
1208 
1209 	sc = device_get_softc(dev);
1210 	sc->dev = dev;
1211 	sysctl_ctx_init(&sc->ctx);
1212 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1213 
1214 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1215 		t5_attribute_workaround(dev);
1216 	pci_enable_busmaster(dev);
1217 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1218 		uint32_t v;
1219 
1220 		pci_set_max_read_req(dev, 4096);
1221 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1222 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1223 		if (pcie_relaxed_ordering == 0 &&
1224 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1225 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1226 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1227 		} else if (pcie_relaxed_ordering == 1 &&
1228 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1229 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1230 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1231 		}
1232 	}
1233 
1234 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1235 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1236 	sc->traceq = -1;
1237 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1238 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1239 	    device_get_nameunit(dev));
1240 
1241 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1242 	    device_get_nameunit(dev));
1243 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1244 	t4_add_adapter(sc);
1245 
1246 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1247 	TAILQ_INIT(&sc->sfl);
1248 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1249 
1250 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1251 
1252 	sc->policy = NULL;
1253 	rw_init(&sc->policy_lock, "connection offload policy");
1254 
1255 	callout_init(&sc->ktls_tick, 1);
1256 
1257 	callout_init(&sc->cal_callout, 1);
1258 
1259 	refcount_init(&sc->vxlan_refcount, 0);
1260 
1261 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1262 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1263 
1264 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1265 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1266 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1267 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1268 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1269 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1270 
1271 	rc = t4_map_bars_0_and_4(sc);
1272 	if (rc != 0)
1273 		goto done; /* error message displayed already */
1274 
1275 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1276 
1277 	/* Prepare the adapter for operation. */
1278 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1279 	rc = -t4_prep_adapter(sc, buf);
1280 	free(buf, M_CXGBE);
1281 	if (rc != 0) {
1282 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1283 		goto done;
1284 	}
1285 
1286 	/*
1287 	 * This is the real PF# to which we're attaching.  Works from within PCI
1288 	 * passthrough environments too, where pci_get_function() could return a
1289 	 * different PF# depending on the passthrough configuration.  We need to
1290 	 * use the real PF# in all our communication with the firmware.
1291 	 */
1292 	j = t4_read_reg(sc, A_PL_WHOAMI);
1293 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1294 	sc->mbox = sc->pf;
1295 
1296 	t4_init_devnames(sc);
1297 	if (sc->names == NULL) {
1298 		rc = ENOTSUP;
1299 		goto done; /* error message displayed already */
1300 	}
1301 
1302 	/*
1303 	 * Do this really early, with the memory windows set up even before the
1304 	 * character device.  The userland tool's register i/o and mem read
1305 	 * will work even in "recovery mode".
1306 	 */
1307 	setup_memwin(sc);
1308 	if (t4_init_devlog_params(sc, 0) == 0)
1309 		fixup_devlog_params(sc);
1310 	make_dev_args_init(&mda);
1311 	mda.mda_devsw = &t4_cdevsw;
1312 	mda.mda_uid = UID_ROOT;
1313 	mda.mda_gid = GID_WHEEL;
1314 	mda.mda_mode = 0600;
1315 	mda.mda_si_drv1 = sc;
1316 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1317 	if (rc != 0)
1318 		device_printf(dev, "failed to create nexus char device: %d.\n",
1319 		    rc);
1320 
1321 	/* Go no further if recovery mode has been requested. */
1322 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1323 		device_printf(dev, "recovery mode.\n");
1324 		goto done;
1325 	}
1326 
1327 #if defined(__i386__)
1328 	if ((cpu_feature & CPUID_CX8) == 0) {
1329 		device_printf(dev, "64 bit atomics not available.\n");
1330 		rc = ENOTSUP;
1331 		goto done;
1332 	}
1333 #endif
1334 
1335 	/* Contact the firmware and try to become the master driver. */
1336 	rc = contact_firmware(sc);
1337 	if (rc != 0)
1338 		goto done; /* error message displayed already */
1339 	MPASS(sc->flags & FW_OK);
1340 
1341 	rc = get_params__pre_init(sc);
1342 	if (rc != 0)
1343 		goto done; /* error message displayed already */
1344 
1345 	if (sc->flags & MASTER_PF) {
1346 		rc = partition_resources(sc);
1347 		if (rc != 0)
1348 			goto done; /* error message displayed already */
1349 	}
1350 
1351 	rc = get_params__post_init(sc);
1352 	if (rc != 0)
1353 		goto done; /* error message displayed already */
1354 
1355 	rc = set_params__post_init(sc);
1356 	if (rc != 0)
1357 		goto done; /* error message displayed already */
1358 
1359 	rc = t4_map_bar_2(sc);
1360 	if (rc != 0)
1361 		goto done; /* error message displayed already */
1362 
1363 	rc = t4_adj_doorbells(sc);
1364 	if (rc != 0)
1365 		goto done; /* error message displayed already */
1366 
1367 	rc = t4_create_dma_tag(sc);
1368 	if (rc != 0)
1369 		goto done; /* error message displayed already */
1370 
1371 	/*
1372 	 * First pass over all the ports - allocate VIs and initialize some
1373 	 * basic parameters like mac address, port type, etc.
1374 	 */
1375 	for_each_port(sc, i) {
1376 		struct port_info *pi;
1377 
1378 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1379 		sc->port[i] = pi;
1380 
1381 		/* These must be set before t4_port_init */
1382 		pi->adapter = sc;
1383 		pi->port_id = i;
1384 		/*
1385 		 * XXX: vi[0] is special so we can't delay this allocation until
1386 		 * pi->nvi's final value is known.
1387 		 */
1388 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1389 		    M_ZERO | M_WAITOK);
1390 
1391 		/*
1392 		 * Allocate the "main" VI and initialize parameters
1393 		 * like mac addr.
1394 		 */
1395 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1396 		if (rc != 0) {
1397 			device_printf(dev, "unable to initialize port %d: %d\n",
1398 			    i, rc);
1399 			free(pi->vi, M_CXGBE);
1400 			free(pi, M_CXGBE);
1401 			sc->port[i] = NULL;
1402 			goto done;
1403 		}
1404 
1405 		if (is_bt(pi->port_type))
1406 			setbit(&sc->bt_map, pi->tx_chan);
1407 		else
1408 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1409 
1410 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1411 		    device_get_nameunit(dev), i);
1412 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1413 		sc->chan_map[pi->tx_chan] = i;
1414 
1415 		/*
1416 		 * The MPS counter for FCS errors doesn't work correctly on the
1417 		 * T6 so we use the MAC counter here.  Which MAC is in use
1418 		 * depends on the link settings which will be known when the
1419 		 * link comes up.
1420 		 */
1421 		if (is_t6(sc))
1422 			pi->fcs_reg = -1;
1423 		else {
1424 			pi->fcs_reg = t4_port_reg(sc, pi->tx_chan,
1425 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1426 		}
1427 		pi->fcs_base = 0;
1428 
1429 		/* All VIs on this port share this media. */
1430 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1431 		    cxgbe_media_status);
1432 
1433 		PORT_LOCK(pi);
1434 		init_link_config(pi);
1435 		fixup_link_config(pi);
1436 		build_medialist(pi);
1437 		if (fixed_ifmedia(pi))
1438 			pi->flags |= FIXED_IFMEDIA;
1439 		PORT_UNLOCK(pi);
1440 
1441 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1442 		    t4_ifnet_unit(sc, pi));
1443 		if (pi->dev == NULL) {
1444 			device_printf(dev,
1445 			    "failed to add device for port %d.\n", i);
1446 			rc = ENXIO;
1447 			goto done;
1448 		}
1449 		pi->vi[0].dev = pi->dev;
1450 		device_set_softc(pi->dev, pi);
1451 	}
1452 
1453 	/*
1454 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1455 	 */
1456 	nports = sc->params.nports;
1457 	rc = cfg_itype_and_nqueues(sc, &iaq);
1458 	if (rc != 0)
1459 		goto done; /* error message displayed already */
1460 
1461 	num_vis = iaq.num_vis;
1462 	sc->intr_type = iaq.intr_type;
1463 	sc->intr_count = iaq.nirq;
1464 
1465 	s = &sc->sge;
1466 	s->nrxq = nports * iaq.nrxq;
1467 	s->ntxq = nports * iaq.ntxq;
1468 	if (num_vis > 1) {
1469 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1470 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1471 	}
1472 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1473 	s->neq += nports;		/* ctrl queues: 1 per port */
1474 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1475 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1476 	if (is_offload(sc) || is_ethoffload(sc)) {
1477 		s->nofldtxq = nports * iaq.nofldtxq;
1478 		if (num_vis > 1)
1479 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1480 		s->neq += s->nofldtxq;
1481 
1482 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1483 		    M_CXGBE, M_ZERO | M_WAITOK);
1484 	}
1485 #endif
1486 #ifdef TCP_OFFLOAD
1487 	if (is_offload(sc)) {
1488 		s->nofldrxq = nports * iaq.nofldrxq;
1489 		if (num_vis > 1)
1490 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1491 		s->neq += s->nofldrxq;	/* free list */
1492 		s->niq += s->nofldrxq;
1493 
1494 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1495 		    M_CXGBE, M_ZERO | M_WAITOK);
1496 	}
1497 #endif
1498 #ifdef DEV_NETMAP
1499 	s->nnmrxq = 0;
1500 	s->nnmtxq = 0;
1501 	if (t4_native_netmap & NN_MAIN_VI) {
1502 		s->nnmrxq += nports * iaq.nnmrxq;
1503 		s->nnmtxq += nports * iaq.nnmtxq;
1504 	}
1505 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1506 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1507 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1508 	}
1509 	s->neq += s->nnmtxq + s->nnmrxq;
1510 	s->niq += s->nnmrxq;
1511 
1512 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1513 	    M_CXGBE, M_ZERO | M_WAITOK);
1514 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1515 	    M_CXGBE, M_ZERO | M_WAITOK);
1516 #endif
1517 	MPASS(s->niq <= s->iqmap_sz);
1518 	MPASS(s->neq <= s->eqmap_sz);
1519 
1520 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1521 	    M_ZERO | M_WAITOK);
1522 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1523 	    M_ZERO | M_WAITOK);
1524 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1525 	    M_ZERO | M_WAITOK);
1526 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1527 	    M_ZERO | M_WAITOK);
1528 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1529 	    M_ZERO | M_WAITOK);
1530 
1531 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1532 	    M_ZERO | M_WAITOK);
1533 
1534 	t4_init_l2t(sc, M_WAITOK);
1535 	t4_init_smt(sc, M_WAITOK);
1536 	t4_init_tx_sched(sc);
1537 	t4_init_atid_table(sc);
1538 #ifdef RATELIMIT
1539 	t4_init_etid_table(sc);
1540 #endif
1541 #ifdef INET6
1542 	t4_init_clip_table(sc);
1543 #endif
1544 	if (sc->vres.key.size != 0)
1545 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1546 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1547 
1548 	/*
1549 	 * Second pass over the ports.  This time we know the number of rx and
1550 	 * tx queues that each port should get.
1551 	 */
1552 	rqidx = tqidx = 0;
1553 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1554 	ofld_tqidx = 0;
1555 #endif
1556 #ifdef TCP_OFFLOAD
1557 	ofld_rqidx = 0;
1558 #endif
1559 #ifdef DEV_NETMAP
1560 	nm_rqidx = nm_tqidx = 0;
1561 #endif
1562 	for_each_port(sc, i) {
1563 		struct port_info *pi = sc->port[i];
1564 		struct vi_info *vi;
1565 
1566 		if (pi == NULL)
1567 			continue;
1568 
1569 		pi->nvi = num_vis;
1570 		for_each_vi(pi, j, vi) {
1571 			vi->pi = pi;
1572 			vi->adapter = sc;
1573 			vi->first_intr = -1;
1574 			vi->qsize_rxq = t4_qsize_rxq;
1575 			vi->qsize_txq = t4_qsize_txq;
1576 
1577 			vi->first_rxq = rqidx;
1578 			vi->first_txq = tqidx;
1579 			vi->tmr_idx = t4_tmr_idx;
1580 			vi->pktc_idx = t4_pktc_idx;
1581 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1582 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1583 
1584 			rqidx += vi->nrxq;
1585 			tqidx += vi->ntxq;
1586 
1587 			if (j == 0 && vi->ntxq > 1)
1588 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1589 			else
1590 				vi->rsrv_noflowq = 0;
1591 
1592 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1593 			vi->first_ofld_txq = ofld_tqidx;
1594 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1595 			ofld_tqidx += vi->nofldtxq;
1596 #endif
1597 #ifdef TCP_OFFLOAD
1598 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1599 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1600 			vi->first_ofld_rxq = ofld_rqidx;
1601 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1602 
1603 			ofld_rqidx += vi->nofldrxq;
1604 #endif
1605 #ifdef DEV_NETMAP
1606 			vi->first_nm_rxq = nm_rqidx;
1607 			vi->first_nm_txq = nm_tqidx;
1608 			if (j == 0) {
1609 				vi->nnmrxq = iaq.nnmrxq;
1610 				vi->nnmtxq = iaq.nnmtxq;
1611 			} else {
1612 				vi->nnmrxq = iaq.nnmrxq_vi;
1613 				vi->nnmtxq = iaq.nnmtxq_vi;
1614 			}
1615 			nm_rqidx += vi->nnmrxq;
1616 			nm_tqidx += vi->nnmtxq;
1617 #endif
1618 		}
1619 	}
1620 
1621 	rc = t4_setup_intr_handlers(sc);
1622 	if (rc != 0) {
1623 		device_printf(dev,
1624 		    "failed to setup interrupt handlers: %d\n", rc);
1625 		goto done;
1626 	}
1627 
1628 	rc = bus_generic_probe(dev);
1629 	if (rc != 0) {
1630 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1631 		goto done;
1632 	}
1633 
1634 	/*
1635 	 * Ensure thread-safe mailbox access (in debug builds).
1636 	 *
1637 	 * So far this was the only thread accessing the mailbox but various
1638 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1639 	 * will access the mailbox from different threads.
1640 	 */
1641 	sc->flags |= CHK_MBOX_ACCESS;
1642 
1643 	rc = bus_generic_attach(dev);
1644 	if (rc != 0) {
1645 		device_printf(dev,
1646 		    "failed to attach all child ports: %d\n", rc);
1647 		goto done;
1648 	}
1649 	t4_calibration_start(sc);
1650 
1651 	device_printf(dev,
1652 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1653 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1654 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1655 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1656 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1657 
1658 	t4_set_desc(sc);
1659 
1660 	notify_siblings(dev, 0);
1661 
1662 done:
1663 	if (rc != 0 && sc->cdev) {
1664 		/* cdev was created and so cxgbetool works; recover that way. */
1665 		device_printf(dev,
1666 		    "error during attach, adapter is now in recovery mode.\n");
1667 		rc = 0;
1668 	}
1669 
1670 	if (rc != 0)
1671 		t4_detach_common(dev);
1672 	else
1673 		t4_sysctls(sc);
1674 
1675 	return (rc);
1676 }
1677 
1678 static int
1679 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1680 {
1681 	struct adapter *sc;
1682 	struct port_info *pi;
1683 	int i;
1684 
1685 	sc = device_get_softc(bus);
1686 	for_each_port(sc, i) {
1687 		pi = sc->port[i];
1688 		if (pi != NULL && pi->dev == dev) {
1689 			sbuf_printf(sb, "port=%d", pi->port_id);
1690 			break;
1691 		}
1692 	}
1693 	return (0);
1694 }
1695 
1696 static int
1697 t4_ready(device_t dev)
1698 {
1699 	struct adapter *sc;
1700 
1701 	sc = device_get_softc(dev);
1702 	if (sc->flags & FW_OK)
1703 		return (0);
1704 	return (ENXIO);
1705 }
1706 
1707 static int
1708 t4_read_port_device(device_t dev, int port, device_t *child)
1709 {
1710 	struct adapter *sc;
1711 	struct port_info *pi;
1712 
1713 	sc = device_get_softc(dev);
1714 	if (port < 0 || port >= MAX_NPORTS)
1715 		return (EINVAL);
1716 	pi = sc->port[port];
1717 	if (pi == NULL || pi->dev == NULL)
1718 		return (ENXIO);
1719 	*child = pi->dev;
1720 	return (0);
1721 }
1722 
1723 static int
1724 notify_siblings(device_t dev, int detaching)
1725 {
1726 	device_t sibling;
1727 	int error, i;
1728 
1729 	error = 0;
1730 	for (i = 0; i < PCI_FUNCMAX; i++) {
1731 		if (i == pci_get_function(dev))
1732 			continue;
1733 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1734 		    pci_get_slot(dev), i);
1735 		if (sibling == NULL || !device_is_attached(sibling))
1736 			continue;
1737 		if (detaching)
1738 			error = T4_DETACH_CHILD(sibling);
1739 		else
1740 			(void)T4_ATTACH_CHILD(sibling);
1741 		if (error)
1742 			break;
1743 	}
1744 	return (error);
1745 }
1746 
1747 /*
1748  * Idempotent
1749  */
1750 static int
1751 t4_detach(device_t dev)
1752 {
1753 	int rc;
1754 
1755 	rc = notify_siblings(dev, 1);
1756 	if (rc) {
1757 		device_printf(dev,
1758 		    "failed to detach sibling devices: %d\n", rc);
1759 		return (rc);
1760 	}
1761 
1762 	return (t4_detach_common(dev));
1763 }
1764 
1765 int
1766 t4_detach_common(device_t dev)
1767 {
1768 	struct adapter *sc;
1769 	struct port_info *pi;
1770 	int i, rc;
1771 
1772 	sc = device_get_softc(dev);
1773 
1774 #ifdef TCP_OFFLOAD
1775 	rc = deactivate_all_uld(sc);
1776 	if (rc) {
1777 		device_printf(dev,
1778 		    "failed to detach upper layer drivers: %d\n", rc);
1779 		return (rc);
1780 	}
1781 #endif
1782 
1783 	if (sc->cdev) {
1784 		destroy_dev(sc->cdev);
1785 		sc->cdev = NULL;
1786 	}
1787 
1788 	sx_xlock(&t4_list_lock);
1789 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1790 	sx_xunlock(&t4_list_lock);
1791 
1792 	sc->flags &= ~CHK_MBOX_ACCESS;
1793 	if (sc->flags & FULL_INIT_DONE) {
1794 		if (!(sc->flags & IS_VF))
1795 			t4_intr_disable(sc);
1796 	}
1797 
1798 	if (device_is_attached(dev)) {
1799 		rc = bus_generic_detach(dev);
1800 		if (rc) {
1801 			device_printf(dev,
1802 			    "failed to detach child devices: %d\n", rc);
1803 			return (rc);
1804 		}
1805 	}
1806 
1807 	for (i = 0; i < sc->intr_count; i++)
1808 		t4_free_irq(sc, &sc->irq[i]);
1809 
1810 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1811 		t4_free_tx_sched(sc);
1812 
1813 	for (i = 0; i < MAX_NPORTS; i++) {
1814 		pi = sc->port[i];
1815 		if (pi) {
1816 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1817 			if (pi->dev)
1818 				device_delete_child(dev, pi->dev);
1819 
1820 			mtx_destroy(&pi->pi_lock);
1821 			free(pi->vi, M_CXGBE);
1822 			free(pi, M_CXGBE);
1823 		}
1824 	}
1825 	callout_stop(&sc->cal_callout);
1826 	callout_drain(&sc->cal_callout);
1827 	device_delete_children(dev);
1828 	sysctl_ctx_free(&sc->ctx);
1829 	adapter_full_uninit(sc);
1830 
1831 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1832 		t4_fw_bye(sc, sc->mbox);
1833 
1834 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1835 		pci_release_msi(dev);
1836 
1837 	if (sc->regs_res)
1838 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1839 		    sc->regs_res);
1840 
1841 	if (sc->udbs_res)
1842 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1843 		    sc->udbs_res);
1844 
1845 	if (sc->msix_res)
1846 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1847 		    sc->msix_res);
1848 
1849 	if (sc->l2t)
1850 		t4_free_l2t(sc);
1851 	if (sc->smt)
1852 		t4_free_smt(sc->smt);
1853 	t4_free_atid_table(sc);
1854 #ifdef RATELIMIT
1855 	t4_free_etid_table(sc);
1856 #endif
1857 	if (sc->key_map)
1858 		vmem_destroy(sc->key_map);
1859 #ifdef INET6
1860 	t4_destroy_clip_table(sc);
1861 #endif
1862 
1863 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1864 	free(sc->sge.ofld_txq, M_CXGBE);
1865 #endif
1866 #ifdef TCP_OFFLOAD
1867 	free(sc->sge.ofld_rxq, M_CXGBE);
1868 #endif
1869 #ifdef DEV_NETMAP
1870 	free(sc->sge.nm_rxq, M_CXGBE);
1871 	free(sc->sge.nm_txq, M_CXGBE);
1872 #endif
1873 	free(sc->irq, M_CXGBE);
1874 	free(sc->sge.rxq, M_CXGBE);
1875 	free(sc->sge.txq, M_CXGBE);
1876 	free(sc->sge.ctrlq, M_CXGBE);
1877 	free(sc->sge.iqmap, M_CXGBE);
1878 	free(sc->sge.eqmap, M_CXGBE);
1879 	free(sc->tids.ftid_tab, M_CXGBE);
1880 	free(sc->tids.hpftid_tab, M_CXGBE);
1881 	free_hftid_hash(&sc->tids);
1882 	free(sc->tids.tid_tab, M_CXGBE);
1883 	t4_destroy_dma_tag(sc);
1884 
1885 	callout_drain(&sc->ktls_tick);
1886 	callout_drain(&sc->sfl_callout);
1887 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1888 		mtx_destroy(&sc->tids.ftid_lock);
1889 		cv_destroy(&sc->tids.ftid_cv);
1890 	}
1891 	if (mtx_initialized(&sc->tids.atid_lock))
1892 		mtx_destroy(&sc->tids.atid_lock);
1893 	if (mtx_initialized(&sc->ifp_lock))
1894 		mtx_destroy(&sc->ifp_lock);
1895 
1896 	if (rw_initialized(&sc->policy_lock)) {
1897 		rw_destroy(&sc->policy_lock);
1898 #ifdef TCP_OFFLOAD
1899 		if (sc->policy != NULL)
1900 			free_offload_policy(sc->policy);
1901 #endif
1902 	}
1903 
1904 	for (i = 0; i < NUM_MEMWIN; i++) {
1905 		struct memwin *mw = &sc->memwin[i];
1906 
1907 		if (rw_initialized(&mw->mw_lock))
1908 			rw_destroy(&mw->mw_lock);
1909 	}
1910 
1911 	mtx_destroy(&sc->sfl_lock);
1912 	mtx_destroy(&sc->reg_lock);
1913 	mtx_destroy(&sc->sc_lock);
1914 
1915 	bzero(sc, sizeof(*sc));
1916 
1917 	return (0);
1918 }
1919 
1920 static inline int
1921 stop_adapter(struct adapter *sc)
1922 {
1923 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1924 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1925 			 __func__, curthread, sc->flags, sc->error_flags);
1926 		return (EALREADY);
1927 	}
1928 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1929 		 sc->flags, sc->error_flags);
1930 	return (t4_shutdown_adapter(sc));
1931 }
1932 
1933 static inline int
1934 restart_adapter(struct adapter *sc)
1935 {
1936 	uint32_t val;
1937 
1938 	if (!atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_STOPPED))) {
1939 		CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x, EALREADY\n",
1940 			 __func__, curthread, sc->flags, sc->error_flags);
1941 		return (EALREADY);
1942 	}
1943 	CH_ALERT(sc, "%s from %p, flags 0x%08x,0x%08x\n", __func__, curthread,
1944 		 sc->flags, sc->error_flags);
1945 
1946 	MPASS(hw_off_limits(sc));
1947 	MPASS((sc->flags & FW_OK) == 0);
1948 	MPASS((sc->flags & MASTER_PF) == 0);
1949 	MPASS(sc->reset_thread == NULL);
1950 
1951 	/*
1952 	 * The adapter is supposed to be back on PCIE with its config space and
1953 	 * BARs restored to their state before reset.  Register access via
1954 	 * t4_read_reg BAR0 should just work.
1955 	 */
1956 	sc->reset_thread = curthread;
1957 	val = t4_read_reg(sc, A_PL_WHOAMI);
1958 	if (val == 0xffffffff || val == 0xeeeeeeee) {
1959 		CH_ERR(sc, "%s: device registers not readable.\n", __func__);
1960 		sc->reset_thread = NULL;
1961 		atomic_set_int(&sc->error_flags, ADAP_STOPPED);
1962 		return (ENXIO);
1963 	}
1964 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR);
1965 	atomic_add_int(&sc->incarnation, 1);
1966 	atomic_add_int(&sc->num_resets, 1);
1967 
1968 	return (0);
1969 }
1970 
1971 static inline void
1972 set_adapter_hwstatus(struct adapter *sc, const bool usable)
1973 {
1974 	mtx_lock(&sc->reg_lock);
1975 	if (usable) {
1976 		/* Must be marked reusable by the designated thread. */
1977 		MPASS(sc->reset_thread == curthread);
1978 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
1979 	} else {
1980 		/* Mark the adapter totally off limits. */
1981 		atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
1982 		sc->flags &= ~(FW_OK | MASTER_PF);
1983 		sc->reset_thread = NULL;
1984 	}
1985 	mtx_unlock(&sc->reg_lock);
1986 }
1987 
1988 static int
1989 stop_lld(struct adapter *sc)
1990 {
1991 	struct port_info *pi;
1992 	struct vi_info *vi;
1993 	if_t ifp;
1994 	struct sge_rxq *rxq;
1995 	struct sge_txq *txq;
1996 	struct sge_wrq *wrq;
1997 #ifdef TCP_OFFLOAD
1998 	struct sge_ofld_rxq *ofld_rxq;
1999 #endif
2000 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2001 	struct sge_ofld_txq *ofld_txq;
2002 #endif
2003 	int rc, i, j, k;
2004 
2005 	/*
2006 	 * XXX: Can there be a synch_op in progress that will hang because
2007 	 * hardware has been stopped?  We'll hang too and the solution will be
2008 	 * to use a version of begin_synch_op that wakes up existing synch_op
2009 	 * with errors.  Maybe stop_adapter should do this wakeup?
2010 	 *
2011 	 * I don't think any synch_op could get stranded waiting for DMA or
2012 	 * interrupt so I think we're okay here.  Remove this comment block
2013 	 * after testing.
2014 	 */
2015 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4slld");
2016 	if (rc != 0)
2017 		return (ENXIO);
2018 
2019 	/* Quiesce all activity. */
2020 	for_each_port(sc, i) {
2021 		pi = sc->port[i];
2022 		pi->vxlan_tcam_entry = false;
2023 
2024 		PORT_LOCK(pi);
2025 		if (pi->up_vis > 0) {
2026 			/*
2027 			 * t4_shutdown_adapter has already shut down all the
2028 			 * PHYs but it also disables interrupts and DMA so there
2029 			 * won't be a link interrupt.  So we update the state
2030 			 * manually and inform the kernel.
2031 			 */
2032 			pi->link_cfg.link_ok = false;
2033 			t4_os_link_changed(pi);
2034 		}
2035 		PORT_UNLOCK(pi);
2036 
2037 		for_each_vi(pi, j, vi) {
2038 			vi->xact_addr_filt = -1;
2039 			mtx_lock(&vi->tick_mtx);
2040 			vi->flags |= VI_SKIP_STATS;
2041 			mtx_unlock(&vi->tick_mtx);
2042 			if (!(vi->flags & VI_INIT_DONE))
2043 				continue;
2044 
2045 			ifp = vi->ifp;
2046 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2047 				mtx_lock(&vi->tick_mtx);
2048 				callout_stop(&vi->tick);
2049 				mtx_unlock(&vi->tick_mtx);
2050 				callout_drain(&vi->tick);
2051 			}
2052 
2053 			/*
2054 			 * Note that the HW is not available.
2055 			 */
2056 			for_each_txq(vi, k, txq) {
2057 				TXQ_LOCK(txq);
2058 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2059 				TXQ_UNLOCK(txq);
2060 			}
2061 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2062 			for_each_ofld_txq(vi, k, ofld_txq) {
2063 				TXQ_LOCK(&ofld_txq->wrq);
2064 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2065 				TXQ_UNLOCK(&ofld_txq->wrq);
2066 			}
2067 #endif
2068 			for_each_rxq(vi, k, rxq) {
2069 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2070 			}
2071 #if defined(TCP_OFFLOAD)
2072 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2073 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2074 			}
2075 #endif
2076 
2077 			quiesce_vi(vi);
2078 		}
2079 
2080 		if (sc->flags & FULL_INIT_DONE) {
2081 			/* Control queue */
2082 			wrq = &sc->sge.ctrlq[i];
2083 			TXQ_LOCK(wrq);
2084 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2085 			TXQ_UNLOCK(wrq);
2086 			quiesce_wrq(wrq);
2087 		}
2088 	}
2089 	if (sc->flags & FULL_INIT_DONE) {
2090 		/* Firmware event queue */
2091 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2092 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2093 	}
2094 
2095 	/* Stop calibration */
2096 	callout_stop(&sc->cal_callout);
2097 	callout_drain(&sc->cal_callout);
2098 
2099 	if (t4_clock_gate_on_suspend) {
2100 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2101 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2102 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2103 	}
2104 
2105 	end_synchronized_op(sc, 0);
2106 
2107 	stop_atid_allocator(sc);
2108 	t4_stop_l2t(sc);
2109 
2110 	return (rc);
2111 }
2112 
2113 static int
2114 t4_suspend(device_t dev)
2115 {
2116 	struct adapter *sc = device_get_softc(dev);
2117 
2118 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2119 	stop_adapter(sc);
2120 	stop_lld(sc);
2121 #ifdef TCP_OFFLOAD
2122 	stop_all_uld(sc);
2123 #endif
2124 	set_adapter_hwstatus(sc, false);
2125 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2126 
2127 	return (0);
2128 }
2129 
2130 struct adapter_pre_reset_state {
2131 	u_int flags;
2132 	uint16_t nbmcaps;
2133 	uint16_t linkcaps;
2134 	uint16_t switchcaps;
2135 	uint16_t niccaps;
2136 	uint16_t toecaps;
2137 	uint16_t rdmacaps;
2138 	uint16_t cryptocaps;
2139 	uint16_t iscsicaps;
2140 	uint16_t fcoecaps;
2141 
2142 	u_int cfcsum;
2143 	char cfg_file[32];
2144 
2145 	struct adapter_params params;
2146 	struct t4_virt_res vres;
2147 	struct tid_info tids;
2148 	struct sge sge;
2149 
2150 	int rawf_base;
2151 	int nrawf;
2152 
2153 };
2154 
2155 static void
2156 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2157 {
2158 
2159 	ASSERT_SYNCHRONIZED_OP(sc);
2160 
2161 	o->flags = sc->flags;
2162 
2163 	o->nbmcaps =  sc->nbmcaps;
2164 	o->linkcaps = sc->linkcaps;
2165 	o->switchcaps = sc->switchcaps;
2166 	o->niccaps = sc->niccaps;
2167 	o->toecaps = sc->toecaps;
2168 	o->rdmacaps = sc->rdmacaps;
2169 	o->cryptocaps = sc->cryptocaps;
2170 	o->iscsicaps = sc->iscsicaps;
2171 	o->fcoecaps = sc->fcoecaps;
2172 
2173 	o->cfcsum = sc->cfcsum;
2174 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2175 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2176 
2177 	o->params = sc->params;
2178 	o->vres = sc->vres;
2179 	o->tids = sc->tids;
2180 	o->sge = sc->sge;
2181 
2182 	o->rawf_base = sc->rawf_base;
2183 	o->nrawf = sc->nrawf;
2184 }
2185 
2186 static int
2187 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2188 {
2189 	int rc = 0;
2190 
2191 	ASSERT_SYNCHRONIZED_OP(sc);
2192 
2193 	/* Capabilities */
2194 #define COMPARE_CAPS(c) do { \
2195 	if (o->c##caps != sc->c##caps) { \
2196 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2197 		    sc->c##caps); \
2198 		rc = EINVAL; \
2199 	} \
2200 } while (0)
2201 	COMPARE_CAPS(nbm);
2202 	COMPARE_CAPS(link);
2203 	COMPARE_CAPS(switch);
2204 	COMPARE_CAPS(nic);
2205 	COMPARE_CAPS(toe);
2206 	COMPARE_CAPS(rdma);
2207 	COMPARE_CAPS(crypto);
2208 	COMPARE_CAPS(iscsi);
2209 	COMPARE_CAPS(fcoe);
2210 #undef COMPARE_CAPS
2211 
2212 	/* Firmware config file */
2213 	if (o->cfcsum != sc->cfcsum) {
2214 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2215 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2216 		rc = EINVAL;
2217 	}
2218 
2219 #define COMPARE_PARAM(p, name) do { \
2220 	if (o->p != sc->p) { \
2221 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2222 		rc = EINVAL; \
2223 	} \
2224 } while (0)
2225 	COMPARE_PARAM(sge.iq_start, iq_start);
2226 	COMPARE_PARAM(sge.eq_start, eq_start);
2227 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2228 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2229 	COMPARE_PARAM(tids.nftids, nftids);
2230 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2231 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2232 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2233 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2234 	COMPARE_PARAM(tids.tid_base, tid_base);
2235 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2236 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2237 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2238 	COMPARE_PARAM(rawf_base, rawf_base);
2239 	COMPARE_PARAM(nrawf, nrawf);
2240 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2241 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2242 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2243 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2244 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2245 	COMPARE_PARAM(tids.ntids, ntids);
2246 	COMPARE_PARAM(tids.etid_base, etid_base);
2247 	COMPARE_PARAM(tids.etid_end, etid_end);
2248 	COMPARE_PARAM(tids.netids, netids);
2249 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2250 	COMPARE_PARAM(params.ethoffload, ethoffload);
2251 	COMPARE_PARAM(tids.natids, natids);
2252 	COMPARE_PARAM(tids.stid_base, stid_base);
2253 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2254 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2255 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2256 	COMPARE_PARAM(vres.stag.start, stag_start);
2257 	COMPARE_PARAM(vres.stag.size, stag_size);
2258 	COMPARE_PARAM(vres.rq.start, rq_start);
2259 	COMPARE_PARAM(vres.rq.size, rq_size);
2260 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2261 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2262 	COMPARE_PARAM(vres.qp.start, qp_start);
2263 	COMPARE_PARAM(vres.qp.size, qp_size);
2264 	COMPARE_PARAM(vres.cq.start, cq_start);
2265 	COMPARE_PARAM(vres.cq.size, cq_size);
2266 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2267 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2268 	COMPARE_PARAM(vres.srq.start, srq_start);
2269 	COMPARE_PARAM(vres.srq.size, srq_size);
2270 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2271 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2272 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2273 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2274 	COMPARE_PARAM(vres.key.start, key_start);
2275 	COMPARE_PARAM(vres.key.size, key_size);
2276 #undef COMPARE_PARAM
2277 
2278 	return (rc);
2279 }
2280 
2281 static int
2282 restart_lld(struct adapter *sc)
2283 {
2284 	struct adapter_pre_reset_state *old_state = NULL;
2285 	struct port_info *pi;
2286 	struct vi_info *vi;
2287 	if_t ifp;
2288 	struct sge_txq *txq;
2289 	int rc, i, j, k;
2290 
2291 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2292 	if (rc != 0)
2293 		return (ENXIO);
2294 
2295 	/* Restore memory window. */
2296 	setup_memwin(sc);
2297 
2298 	/* Go no further if recovery mode has been requested. */
2299 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2300 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2301 		rc = 0;
2302 		set_adapter_hwstatus(sc, true);
2303 		goto done;
2304 	}
2305 
2306 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2307 	save_caps_and_params(sc, old_state);
2308 
2309 	/* Reestablish contact with firmware and become the primary PF. */
2310 	rc = contact_firmware(sc);
2311 	if (rc != 0)
2312 		goto done; /* error message displayed already */
2313 	MPASS(sc->flags & FW_OK);
2314 
2315 	if (sc->flags & MASTER_PF) {
2316 		rc = partition_resources(sc);
2317 		if (rc != 0)
2318 			goto done; /* error message displayed already */
2319 	}
2320 
2321 	rc = get_params__post_init(sc);
2322 	if (rc != 0)
2323 		goto done; /* error message displayed already */
2324 
2325 	rc = set_params__post_init(sc);
2326 	if (rc != 0)
2327 		goto done; /* error message displayed already */
2328 
2329 	rc = compare_caps_and_params(sc, old_state);
2330 	if (rc != 0)
2331 		goto done; /* error message displayed already */
2332 
2333 	for_each_port(sc, i) {
2334 		pi = sc->port[i];
2335 		MPASS(pi != NULL);
2336 		MPASS(pi->vi != NULL);
2337 		MPASS(pi->vi[0].dev == pi->dev);
2338 
2339 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2340 		if (rc != 0) {
2341 			CH_ERR(sc,
2342 			    "failed to re-initialize port %d: %d\n", i, rc);
2343 			goto done;
2344 		}
2345 		MPASS(sc->chan_map[pi->tx_chan] == i);
2346 
2347 		PORT_LOCK(pi);
2348 		fixup_link_config(pi);
2349 		build_medialist(pi);
2350 		PORT_UNLOCK(pi);
2351 		for_each_vi(pi, j, vi) {
2352 			if (IS_MAIN_VI(vi))
2353 				continue;
2354 			rc = alloc_extra_vi(sc, pi, vi);
2355 			if (rc != 0) {
2356 				CH_ERR(vi,
2357 				    "failed to re-allocate extra VI: %d\n", rc);
2358 				goto done;
2359 			}
2360 		}
2361 	}
2362 
2363 	/*
2364 	 * Interrupts and queues are about to be enabled and other threads will
2365 	 * want to access the hardware too.  It is safe to do so.  Note that
2366 	 * this thread is still in the middle of a synchronized_op.
2367 	 */
2368 	set_adapter_hwstatus(sc, true);
2369 
2370 	if (sc->flags & FULL_INIT_DONE) {
2371 		rc = adapter_full_init(sc);
2372 		if (rc != 0) {
2373 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2374 			goto done;
2375 		}
2376 
2377 		if (sc->vxlan_refcount > 0)
2378 			enable_vxlan_rx(sc);
2379 
2380 		for_each_port(sc, i) {
2381 			pi = sc->port[i];
2382 			for_each_vi(pi, j, vi) {
2383 				mtx_lock(&vi->tick_mtx);
2384 				vi->flags &= ~VI_SKIP_STATS;
2385 				mtx_unlock(&vi->tick_mtx);
2386 				if (!(vi->flags & VI_INIT_DONE))
2387 					continue;
2388 				rc = vi_full_init(vi);
2389 				if (rc != 0) {
2390 					CH_ERR(vi, "failed to re-initialize "
2391 					    "interface: %d\n", rc);
2392 					goto done;
2393 				}
2394 
2395 				ifp = vi->ifp;
2396 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2397 					continue;
2398 				/*
2399 				 * Note that we do not setup multicast addresses
2400 				 * in the first pass.  This ensures that the
2401 				 * unicast DMACs for all VIs on all ports get an
2402 				 * MPS TCAM entry.
2403 				 */
2404 				rc = update_mac_settings(ifp, XGMAC_ALL &
2405 				    ~XGMAC_MCADDRS);
2406 				if (rc != 0) {
2407 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2408 					goto done;
2409 				}
2410 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2411 				    true);
2412 				if (rc != 0) {
2413 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2414 					goto done;
2415 				}
2416 				for_each_txq(vi, k, txq) {
2417 					TXQ_LOCK(txq);
2418 					txq->eq.flags |= EQ_ENABLED;
2419 					TXQ_UNLOCK(txq);
2420 				}
2421 				mtx_lock(&vi->tick_mtx);
2422 				callout_schedule(&vi->tick, hz);
2423 				mtx_unlock(&vi->tick_mtx);
2424 			}
2425 			PORT_LOCK(pi);
2426 			if (pi->up_vis > 0) {
2427 				t4_update_port_info(pi);
2428 				fixup_link_config(pi);
2429 				build_medialist(pi);
2430 				apply_link_config(pi);
2431 				if (pi->link_cfg.link_ok)
2432 					t4_os_link_changed(pi);
2433 			}
2434 			PORT_UNLOCK(pi);
2435 		}
2436 
2437 		/* Now reprogram the L2 multicast addresses. */
2438 		for_each_port(sc, i) {
2439 			pi = sc->port[i];
2440 			for_each_vi(pi, j, vi) {
2441 				if (!(vi->flags & VI_INIT_DONE))
2442 					continue;
2443 				ifp = vi->ifp;
2444 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2445 					continue;
2446 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2447 				if (rc != 0) {
2448 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2449 					rc = 0;	/* carry on */
2450 				}
2451 			}
2452 		}
2453 	}
2454 
2455 	/* Reset all calibration */
2456 	t4_calibration_start(sc);
2457 done:
2458 	end_synchronized_op(sc, 0);
2459 	free(old_state, M_CXGBE);
2460 
2461 	restart_atid_allocator(sc);
2462 	t4_restart_l2t(sc);
2463 
2464 	return (rc);
2465 }
2466 
2467 static int
2468 t4_resume(device_t dev)
2469 {
2470 	struct adapter *sc = device_get_softc(dev);
2471 
2472 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2473 	restart_adapter(sc);
2474 	restart_lld(sc);
2475 #ifdef TCP_OFFLOAD
2476 	restart_all_uld(sc);
2477 #endif
2478 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2479 
2480 	return (0);
2481 }
2482 
2483 static int
2484 t4_reset_prepare(device_t dev, device_t child)
2485 {
2486 	struct adapter *sc = device_get_softc(dev);
2487 
2488 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2489 	return (0);
2490 }
2491 
2492 static int
2493 t4_reset_post(device_t dev, device_t child)
2494 {
2495 	struct adapter *sc = device_get_softc(dev);
2496 
2497 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2498 	return (0);
2499 }
2500 
2501 static int
2502 reset_adapter_with_pci_bus_reset(struct adapter *sc)
2503 {
2504 	int rc;
2505 
2506 	mtx_lock(&Giant);
2507 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2508 	mtx_unlock(&Giant);
2509 	return (rc);
2510 }
2511 
2512 static int
2513 reset_adapter_with_pl_rst(struct adapter *sc)
2514 {
2515 	stop_adapter(sc);
2516 	stop_lld(sc);
2517 #ifdef TCP_OFFLOAD
2518 	stop_all_uld(sc);
2519 #endif
2520 	set_adapter_hwstatus(sc, false);
2521 
2522 	/* This is a t4_write_reg without the hw_off_limits check. */
2523 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2524 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2525 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2526 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2527 
2528 	restart_adapter(sc);
2529 	restart_lld(sc);
2530 #ifdef TCP_OFFLOAD
2531 	restart_all_uld(sc);
2532 #endif
2533 
2534 	return (0);
2535 }
2536 
2537 static void
2538 reset_adapter_task(void *arg, int pending)
2539 {
2540 	struct adapter *sc = arg;
2541 	const int flags = sc->flags;
2542 	const int eflags = sc->error_flags;
2543 	int rc;
2544 
2545 	if (pending > 1)
2546 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2547 	if (vm_guest == 0)
2548 		rc = reset_adapter_with_pci_bus_reset(sc);
2549 	else
2550 		rc = reset_adapter_with_pl_rst(sc);
2551 	if (rc != 0) {
2552 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2553 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2554 		       rc, flags, sc->flags, eflags, sc->error_flags);
2555 	}
2556 }
2557 
2558 static int
2559 cxgbe_probe(device_t dev)
2560 {
2561 	struct port_info *pi = device_get_softc(dev);
2562 
2563 	device_set_descf(dev, "port %d", pi->port_id);
2564 
2565 	return (BUS_PROBE_DEFAULT);
2566 }
2567 
2568 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2569     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2570     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2571     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2572 #define T4_CAP_ENABLE (T4_CAP)
2573 
2574 static void
2575 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2576 {
2577 	if_t ifp;
2578 	struct sbuf *sb;
2579 	struct sysctl_ctx_list *ctx = &vi->ctx;
2580 	struct sysctl_oid_list *children;
2581 	struct pfil_head_args pa;
2582 	struct adapter *sc = vi->adapter;
2583 
2584 	sysctl_ctx_init(ctx);
2585 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2586 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2587 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2588 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2589 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2590 #ifdef DEV_NETMAP
2591 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2592 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2593 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2594 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2595 #endif
2596 #ifdef TCP_OFFLOAD
2597 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2598 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2599 #endif
2600 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2601 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2602 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2603 #endif
2604 
2605 	vi->xact_addr_filt = -1;
2606 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2607 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2608 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2609 		vi->flags |= TX_USES_VM_WR;
2610 
2611 	/* Allocate an ifnet and set it up */
2612 	ifp = if_alloc_dev(IFT_ETHER, dev);
2613 	vi->ifp = ifp;
2614 	if_setsoftc(ifp, vi);
2615 
2616 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2617 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2618 
2619 	if_setinitfn(ifp, cxgbe_init);
2620 	if_setioctlfn(ifp, cxgbe_ioctl);
2621 	if_settransmitfn(ifp, cxgbe_transmit);
2622 	if_setqflushfn(ifp, cxgbe_qflush);
2623 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2624 		if_setgetcounterfn(ifp, vi_get_counter);
2625 	else
2626 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2627 #if defined(KERN_TLS) || defined(RATELIMIT)
2628 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2629 #endif
2630 #ifdef RATELIMIT
2631 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2632 #endif
2633 
2634 	if_setcapabilities(ifp, T4_CAP);
2635 	if_setcapenable(ifp, T4_CAP_ENABLE);
2636 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2637 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2638 	if (chip_id(sc) >= CHELSIO_T6) {
2639 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2640 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2641 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2642 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2643 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2644 	}
2645 
2646 #ifdef TCP_OFFLOAD
2647 	if (vi->nofldrxq != 0)
2648 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2649 #endif
2650 #ifdef RATELIMIT
2651 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2652 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2653 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2654 	}
2655 #endif
2656 
2657 	if_sethwtsomax(ifp, IP_MAXPACKET);
2658 	if (vi->flags & TX_USES_VM_WR)
2659 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2660 	else
2661 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2662 #ifdef RATELIMIT
2663 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2664 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2665 #endif
2666 	if_sethwtsomaxsegsize(ifp, 65536);
2667 #ifdef KERN_TLS
2668 	if (is_ktls(sc)) {
2669 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2670 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2671 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2672 	}
2673 #endif
2674 
2675 	ether_ifattach(ifp, vi->hw_addr);
2676 #ifdef DEV_NETMAP
2677 	if (vi->nnmrxq != 0)
2678 		cxgbe_nm_attach(vi);
2679 #endif
2680 	sb = sbuf_new_auto();
2681 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2682 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2683 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2684 	case IFCAP_TOE:
2685 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2686 		break;
2687 	case IFCAP_TOE | IFCAP_TXRTLMT:
2688 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2689 		break;
2690 	case IFCAP_TXRTLMT:
2691 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2692 		break;
2693 	}
2694 #endif
2695 #ifdef TCP_OFFLOAD
2696 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2697 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2698 #endif
2699 #ifdef DEV_NETMAP
2700 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2701 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2702 		    vi->nnmtxq, vi->nnmrxq);
2703 #endif
2704 	sbuf_finish(sb);
2705 	device_printf(dev, "%s\n", sbuf_data(sb));
2706 	sbuf_delete(sb);
2707 
2708 	vi_sysctls(vi);
2709 
2710 	pa.pa_version = PFIL_VERSION;
2711 	pa.pa_flags = PFIL_IN;
2712 	pa.pa_type = PFIL_TYPE_ETHERNET;
2713 	pa.pa_headname = if_name(ifp);
2714 	vi->pfil = pfil_head_register(&pa);
2715 }
2716 
2717 static int
2718 cxgbe_attach(device_t dev)
2719 {
2720 	struct port_info *pi = device_get_softc(dev);
2721 	struct adapter *sc = pi->adapter;
2722 	struct vi_info *vi;
2723 	int i;
2724 
2725 	sysctl_ctx_init(&pi->ctx);
2726 
2727 	cxgbe_vi_attach(dev, &pi->vi[0]);
2728 
2729 	for_each_vi(pi, i, vi) {
2730 		if (i == 0)
2731 			continue;
2732 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2733 		if (vi->dev == NULL) {
2734 			device_printf(dev, "failed to add VI %d\n", i);
2735 			continue;
2736 		}
2737 		device_set_softc(vi->dev, vi);
2738 	}
2739 
2740 	cxgbe_sysctls(pi);
2741 
2742 	bus_generic_attach(dev);
2743 
2744 	return (0);
2745 }
2746 
2747 static void
2748 cxgbe_vi_detach(struct vi_info *vi)
2749 {
2750 	if_t ifp = vi->ifp;
2751 
2752 	if (vi->pfil != NULL) {
2753 		pfil_head_unregister(vi->pfil);
2754 		vi->pfil = NULL;
2755 	}
2756 
2757 	ether_ifdetach(ifp);
2758 
2759 	/* Let detach proceed even if these fail. */
2760 #ifdef DEV_NETMAP
2761 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2762 		cxgbe_nm_detach(vi);
2763 #endif
2764 	cxgbe_uninit_synchronized(vi);
2765 	callout_drain(&vi->tick);
2766 	mtx_destroy(&vi->tick_mtx);
2767 	sysctl_ctx_free(&vi->ctx);
2768 	vi_full_uninit(vi);
2769 
2770 	if_free(vi->ifp);
2771 	vi->ifp = NULL;
2772 }
2773 
2774 static int
2775 cxgbe_detach(device_t dev)
2776 {
2777 	struct port_info *pi = device_get_softc(dev);
2778 	struct adapter *sc = pi->adapter;
2779 	int rc;
2780 
2781 	/* Detach the extra VIs first. */
2782 	rc = bus_generic_detach(dev);
2783 	if (rc)
2784 		return (rc);
2785 	device_delete_children(dev);
2786 
2787 	sysctl_ctx_free(&pi->ctx);
2788 	begin_vi_detach(sc, &pi->vi[0]);
2789 	if (pi->flags & HAS_TRACEQ) {
2790 		sc->traceq = -1;	/* cloner should not create ifnet */
2791 		t4_tracer_port_detach(sc);
2792 	}
2793 	cxgbe_vi_detach(&pi->vi[0]);
2794 	ifmedia_removeall(&pi->media);
2795 	end_vi_detach(sc, &pi->vi[0]);
2796 
2797 	return (0);
2798 }
2799 
2800 static void
2801 cxgbe_init(void *arg)
2802 {
2803 	struct vi_info *vi = arg;
2804 	struct adapter *sc = vi->adapter;
2805 
2806 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2807 		return;
2808 	cxgbe_init_synchronized(vi);
2809 	end_synchronized_op(sc, 0);
2810 }
2811 
2812 static int
2813 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2814 {
2815 	int rc = 0, mtu, flags;
2816 	struct vi_info *vi = if_getsoftc(ifp);
2817 	struct port_info *pi = vi->pi;
2818 	struct adapter *sc = pi->adapter;
2819 	struct ifreq *ifr = (struct ifreq *)data;
2820 	uint32_t mask;
2821 
2822 	switch (cmd) {
2823 	case SIOCSIFMTU:
2824 		mtu = ifr->ifr_mtu;
2825 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2826 			return (EINVAL);
2827 
2828 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2829 		if (rc)
2830 			return (rc);
2831 		if_setmtu(ifp, mtu);
2832 		if (vi->flags & VI_INIT_DONE) {
2833 			t4_update_fl_bufsize(ifp);
2834 			if (!hw_off_limits(sc) &&
2835 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2836 				rc = update_mac_settings(ifp, XGMAC_MTU);
2837 		}
2838 		end_synchronized_op(sc, 0);
2839 		break;
2840 
2841 	case SIOCSIFFLAGS:
2842 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2843 		if (rc)
2844 			return (rc);
2845 
2846 		if (hw_off_limits(sc)) {
2847 			rc = ENXIO;
2848 			goto fail;
2849 		}
2850 
2851 		if (if_getflags(ifp) & IFF_UP) {
2852 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2853 				flags = vi->if_flags;
2854 				if ((if_getflags(ifp) ^ flags) &
2855 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2856 					rc = update_mac_settings(ifp,
2857 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2858 				}
2859 			} else {
2860 				rc = cxgbe_init_synchronized(vi);
2861 			}
2862 			vi->if_flags = if_getflags(ifp);
2863 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2864 			rc = cxgbe_uninit_synchronized(vi);
2865 		}
2866 		end_synchronized_op(sc, 0);
2867 		break;
2868 
2869 	case SIOCADDMULTI:
2870 	case SIOCDELMULTI:
2871 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2872 		if (rc)
2873 			return (rc);
2874 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2875 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2876 		end_synchronized_op(sc, 0);
2877 		break;
2878 
2879 	case SIOCSIFCAP:
2880 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2881 		if (rc)
2882 			return (rc);
2883 
2884 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2885 		if (mask & IFCAP_TXCSUM) {
2886 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2887 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2888 
2889 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2890 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2891 				mask &= ~IFCAP_TSO4;
2892 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2893 				if_printf(ifp,
2894 				    "tso4 disabled due to -txcsum.\n");
2895 			}
2896 		}
2897 		if (mask & IFCAP_TXCSUM_IPV6) {
2898 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2899 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2900 
2901 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2902 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2903 				mask &= ~IFCAP_TSO6;
2904 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2905 				if_printf(ifp,
2906 				    "tso6 disabled due to -txcsum6.\n");
2907 			}
2908 		}
2909 		if (mask & IFCAP_RXCSUM)
2910 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2911 		if (mask & IFCAP_RXCSUM_IPV6)
2912 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2913 
2914 		/*
2915 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2916 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2917 		 * sending a TSO request our way, so it's sufficient to toggle
2918 		 * IFCAP_TSOx only.
2919 		 */
2920 		if (mask & IFCAP_TSO4) {
2921 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2922 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2923 				if_printf(ifp, "enable txcsum first.\n");
2924 				rc = EAGAIN;
2925 				goto fail;
2926 			}
2927 			if_togglecapenable(ifp, IFCAP_TSO4);
2928 		}
2929 		if (mask & IFCAP_TSO6) {
2930 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2931 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2932 				if_printf(ifp, "enable txcsum6 first.\n");
2933 				rc = EAGAIN;
2934 				goto fail;
2935 			}
2936 			if_togglecapenable(ifp, IFCAP_TSO6);
2937 		}
2938 		if (mask & IFCAP_LRO) {
2939 #if defined(INET) || defined(INET6)
2940 			int i;
2941 			struct sge_rxq *rxq;
2942 
2943 			if_togglecapenable(ifp, IFCAP_LRO);
2944 			for_each_rxq(vi, i, rxq) {
2945 				if (if_getcapenable(ifp) & IFCAP_LRO)
2946 					rxq->iq.flags |= IQ_LRO_ENABLED;
2947 				else
2948 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2949 			}
2950 #endif
2951 		}
2952 #ifdef TCP_OFFLOAD
2953 		if (mask & IFCAP_TOE) {
2954 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2955 
2956 			rc = toe_capability(vi, enable);
2957 			if (rc != 0)
2958 				goto fail;
2959 
2960 			if_togglecapenable(ifp, mask);
2961 		}
2962 #endif
2963 		if (mask & IFCAP_VLAN_HWTAGGING) {
2964 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2965 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2966 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2967 		}
2968 		if (mask & IFCAP_VLAN_MTU) {
2969 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2970 
2971 			/* Need to find out how to disable auto-mtu-inflation */
2972 		}
2973 		if (mask & IFCAP_VLAN_HWTSO)
2974 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2975 		if (mask & IFCAP_VLAN_HWCSUM)
2976 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2977 #ifdef RATELIMIT
2978 		if (mask & IFCAP_TXRTLMT)
2979 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2980 #endif
2981 		if (mask & IFCAP_HWRXTSTMP) {
2982 			int i;
2983 			struct sge_rxq *rxq;
2984 
2985 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2986 			for_each_rxq(vi, i, rxq) {
2987 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2988 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2989 				else
2990 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2991 			}
2992 		}
2993 		if (mask & IFCAP_MEXTPG)
2994 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2995 
2996 #ifdef KERN_TLS
2997 		if (mask & IFCAP_TXTLS) {
2998 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2999 
3000 			rc = ktls_capability(sc, enable);
3001 			if (rc != 0)
3002 				goto fail;
3003 
3004 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3005 		}
3006 #endif
3007 		if (mask & IFCAP_VXLAN_HWCSUM) {
3008 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3009 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3010 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3011 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3012 		}
3013 		if (mask & IFCAP_VXLAN_HWTSO) {
3014 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3015 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3016 			    CSUM_INNER_IP_TSO);
3017 		}
3018 
3019 #ifdef VLAN_CAPABILITIES
3020 		VLAN_CAPABILITIES(ifp);
3021 #endif
3022 fail:
3023 		end_synchronized_op(sc, 0);
3024 		break;
3025 
3026 	case SIOCSIFMEDIA:
3027 	case SIOCGIFMEDIA:
3028 	case SIOCGIFXMEDIA:
3029 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3030 		break;
3031 
3032 	case SIOCGI2C: {
3033 		struct ifi2creq i2c;
3034 
3035 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3036 		if (rc != 0)
3037 			break;
3038 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3039 			rc = EPERM;
3040 			break;
3041 		}
3042 		if (i2c.len > sizeof(i2c.data)) {
3043 			rc = EINVAL;
3044 			break;
3045 		}
3046 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3047 		if (rc)
3048 			return (rc);
3049 		if (hw_off_limits(sc))
3050 			rc = ENXIO;
3051 		else
3052 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3053 			    i2c.offset, i2c.len, &i2c.data[0]);
3054 		end_synchronized_op(sc, 0);
3055 		if (rc == 0)
3056 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3057 		break;
3058 	}
3059 
3060 	default:
3061 		rc = ether_ioctl(ifp, cmd, data);
3062 	}
3063 
3064 	return (rc);
3065 }
3066 
3067 static int
3068 cxgbe_transmit(if_t ifp, struct mbuf *m)
3069 {
3070 	struct vi_info *vi = if_getsoftc(ifp);
3071 	struct port_info *pi = vi->pi;
3072 	struct adapter *sc;
3073 	struct sge_txq *txq;
3074 	void *items[1];
3075 	int rc;
3076 
3077 	M_ASSERTPKTHDR(m);
3078 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3079 #if defined(KERN_TLS) || defined(RATELIMIT)
3080 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3081 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3082 #endif
3083 
3084 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3085 		m_freem(m);
3086 		return (ENETDOWN);
3087 	}
3088 
3089 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3090 	if (__predict_false(rc != 0)) {
3091 		if (__predict_true(rc == EINPROGRESS)) {
3092 			/* queued by parse_pkt */
3093 			MPASS(m != NULL);
3094 			return (0);
3095 		}
3096 
3097 		MPASS(m == NULL);			/* was freed already */
3098 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3099 		return (rc);
3100 	}
3101 
3102 	/* Select a txq. */
3103 	sc = vi->adapter;
3104 	txq = &sc->sge.txq[vi->first_txq];
3105 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3106 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3107 		    vi->rsrv_noflowq);
3108 
3109 	items[0] = m;
3110 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3111 	if (__predict_false(rc != 0))
3112 		m_freem(m);
3113 
3114 	return (rc);
3115 }
3116 
3117 static void
3118 cxgbe_qflush(if_t ifp)
3119 {
3120 	struct vi_info *vi = if_getsoftc(ifp);
3121 	struct sge_txq *txq;
3122 	int i;
3123 
3124 	/* queues do not exist if !VI_INIT_DONE. */
3125 	if (vi->flags & VI_INIT_DONE) {
3126 		for_each_txq(vi, i, txq) {
3127 			TXQ_LOCK(txq);
3128 			txq->eq.flags |= EQ_QFLUSH;
3129 			TXQ_UNLOCK(txq);
3130 			while (!mp_ring_is_idle(txq->r)) {
3131 				mp_ring_check_drainage(txq->r, 4096);
3132 				pause("qflush", 1);
3133 			}
3134 			TXQ_LOCK(txq);
3135 			txq->eq.flags &= ~EQ_QFLUSH;
3136 			TXQ_UNLOCK(txq);
3137 		}
3138 	}
3139 	if_qflush(ifp);
3140 }
3141 
3142 static uint64_t
3143 vi_get_counter(if_t ifp, ift_counter c)
3144 {
3145 	struct vi_info *vi = if_getsoftc(ifp);
3146 	struct fw_vi_stats_vf *s = &vi->stats;
3147 
3148 	mtx_lock(&vi->tick_mtx);
3149 	vi_refresh_stats(vi);
3150 	mtx_unlock(&vi->tick_mtx);
3151 
3152 	switch (c) {
3153 	case IFCOUNTER_IPACKETS:
3154 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3155 		    s->rx_ucast_frames);
3156 	case IFCOUNTER_IERRORS:
3157 		return (s->rx_err_frames);
3158 	case IFCOUNTER_OPACKETS:
3159 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3160 		    s->tx_ucast_frames + s->tx_offload_frames);
3161 	case IFCOUNTER_OERRORS:
3162 		return (s->tx_drop_frames);
3163 	case IFCOUNTER_IBYTES:
3164 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3165 		    s->rx_ucast_bytes);
3166 	case IFCOUNTER_OBYTES:
3167 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3168 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3169 	case IFCOUNTER_IMCASTS:
3170 		return (s->rx_mcast_frames);
3171 	case IFCOUNTER_OMCASTS:
3172 		return (s->tx_mcast_frames);
3173 	case IFCOUNTER_OQDROPS: {
3174 		uint64_t drops;
3175 
3176 		drops = 0;
3177 		if (vi->flags & VI_INIT_DONE) {
3178 			int i;
3179 			struct sge_txq *txq;
3180 
3181 			for_each_txq(vi, i, txq)
3182 				drops += counter_u64_fetch(txq->r->dropped);
3183 		}
3184 
3185 		return (drops);
3186 
3187 	}
3188 
3189 	default:
3190 		return (if_get_counter_default(ifp, c));
3191 	}
3192 }
3193 
3194 static uint64_t
3195 cxgbe_get_counter(if_t ifp, ift_counter c)
3196 {
3197 	struct vi_info *vi = if_getsoftc(ifp);
3198 	struct port_info *pi = vi->pi;
3199 	struct port_stats *s = &pi->stats;
3200 
3201 	mtx_lock(&vi->tick_mtx);
3202 	cxgbe_refresh_stats(vi);
3203 	mtx_unlock(&vi->tick_mtx);
3204 
3205 	switch (c) {
3206 	case IFCOUNTER_IPACKETS:
3207 		return (s->rx_frames);
3208 
3209 	case IFCOUNTER_IERRORS:
3210 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3211 		    s->rx_fcs_err + s->rx_len_err);
3212 
3213 	case IFCOUNTER_OPACKETS:
3214 		return (s->tx_frames);
3215 
3216 	case IFCOUNTER_OERRORS:
3217 		return (s->tx_error_frames);
3218 
3219 	case IFCOUNTER_IBYTES:
3220 		return (s->rx_octets);
3221 
3222 	case IFCOUNTER_OBYTES:
3223 		return (s->tx_octets);
3224 
3225 	case IFCOUNTER_IMCASTS:
3226 		return (s->rx_mcast_frames);
3227 
3228 	case IFCOUNTER_OMCASTS:
3229 		return (s->tx_mcast_frames);
3230 
3231 	case IFCOUNTER_IQDROPS:
3232 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3233 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3234 		    s->rx_trunc3 + pi->tnl_cong_drops);
3235 
3236 	case IFCOUNTER_OQDROPS: {
3237 		uint64_t drops;
3238 
3239 		drops = s->tx_drop;
3240 		if (vi->flags & VI_INIT_DONE) {
3241 			int i;
3242 			struct sge_txq *txq;
3243 
3244 			for_each_txq(vi, i, txq)
3245 				drops += counter_u64_fetch(txq->r->dropped);
3246 		}
3247 
3248 		return (drops);
3249 
3250 	}
3251 
3252 	default:
3253 		return (if_get_counter_default(ifp, c));
3254 	}
3255 }
3256 
3257 #if defined(KERN_TLS) || defined(RATELIMIT)
3258 static int
3259 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3260     struct m_snd_tag **pt)
3261 {
3262 	int error;
3263 
3264 	switch (params->hdr.type) {
3265 #ifdef RATELIMIT
3266 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3267 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3268 		break;
3269 #endif
3270 #ifdef KERN_TLS
3271 	case IF_SND_TAG_TYPE_TLS:
3272 	{
3273 		struct vi_info *vi = if_getsoftc(ifp);
3274 
3275 		if (is_t6(vi->pi->adapter))
3276 			error = t6_tls_tag_alloc(ifp, params, pt);
3277 		else
3278 			error = EOPNOTSUPP;
3279 		break;
3280 	}
3281 #endif
3282 	default:
3283 		error = EOPNOTSUPP;
3284 	}
3285 	return (error);
3286 }
3287 #endif
3288 
3289 /*
3290  * The kernel picks a media from the list we had provided but we still validate
3291  * the requeste.
3292  */
3293 int
3294 cxgbe_media_change(if_t ifp)
3295 {
3296 	struct vi_info *vi = if_getsoftc(ifp);
3297 	struct port_info *pi = vi->pi;
3298 	struct ifmedia *ifm = &pi->media;
3299 	struct link_config *lc = &pi->link_cfg;
3300 	struct adapter *sc = pi->adapter;
3301 	int rc;
3302 
3303 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3304 	if (rc != 0)
3305 		return (rc);
3306 	PORT_LOCK(pi);
3307 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3308 		/* ifconfig .. media autoselect */
3309 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3310 			rc = ENOTSUP; /* AN not supported by transceiver */
3311 			goto done;
3312 		}
3313 		lc->requested_aneg = AUTONEG_ENABLE;
3314 		lc->requested_speed = 0;
3315 		lc->requested_fc |= PAUSE_AUTONEG;
3316 	} else {
3317 		lc->requested_aneg = AUTONEG_DISABLE;
3318 		lc->requested_speed =
3319 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3320 		lc->requested_fc = 0;
3321 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3322 			lc->requested_fc |= PAUSE_RX;
3323 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3324 			lc->requested_fc |= PAUSE_TX;
3325 	}
3326 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3327 		fixup_link_config(pi);
3328 		rc = apply_link_config(pi);
3329 	}
3330 done:
3331 	PORT_UNLOCK(pi);
3332 	end_synchronized_op(sc, 0);
3333 	return (rc);
3334 }
3335 
3336 /*
3337  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3338  * given speed.
3339  */
3340 static int
3341 port_mword(struct port_info *pi, uint32_t speed)
3342 {
3343 
3344 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3345 	MPASS(powerof2(speed));
3346 
3347 	switch(pi->port_type) {
3348 	case FW_PORT_TYPE_BT_SGMII:
3349 	case FW_PORT_TYPE_BT_XFI:
3350 	case FW_PORT_TYPE_BT_XAUI:
3351 		/* BaseT */
3352 		switch (speed) {
3353 		case FW_PORT_CAP32_SPEED_100M:
3354 			return (IFM_100_T);
3355 		case FW_PORT_CAP32_SPEED_1G:
3356 			return (IFM_1000_T);
3357 		case FW_PORT_CAP32_SPEED_10G:
3358 			return (IFM_10G_T);
3359 		}
3360 		break;
3361 	case FW_PORT_TYPE_KX4:
3362 		if (speed == FW_PORT_CAP32_SPEED_10G)
3363 			return (IFM_10G_KX4);
3364 		break;
3365 	case FW_PORT_TYPE_CX4:
3366 		if (speed == FW_PORT_CAP32_SPEED_10G)
3367 			return (IFM_10G_CX4);
3368 		break;
3369 	case FW_PORT_TYPE_KX:
3370 		if (speed == FW_PORT_CAP32_SPEED_1G)
3371 			return (IFM_1000_KX);
3372 		break;
3373 	case FW_PORT_TYPE_KR:
3374 	case FW_PORT_TYPE_BP_AP:
3375 	case FW_PORT_TYPE_BP4_AP:
3376 	case FW_PORT_TYPE_BP40_BA:
3377 	case FW_PORT_TYPE_KR4_100G:
3378 	case FW_PORT_TYPE_KR_SFP28:
3379 	case FW_PORT_TYPE_KR_XLAUI:
3380 		switch (speed) {
3381 		case FW_PORT_CAP32_SPEED_1G:
3382 			return (IFM_1000_KX);
3383 		case FW_PORT_CAP32_SPEED_10G:
3384 			return (IFM_10G_KR);
3385 		case FW_PORT_CAP32_SPEED_25G:
3386 			return (IFM_25G_KR);
3387 		case FW_PORT_CAP32_SPEED_40G:
3388 			return (IFM_40G_KR4);
3389 		case FW_PORT_CAP32_SPEED_50G:
3390 			return (IFM_50G_KR2);
3391 		case FW_PORT_CAP32_SPEED_100G:
3392 			return (IFM_100G_KR4);
3393 		}
3394 		break;
3395 	case FW_PORT_TYPE_FIBER_XFI:
3396 	case FW_PORT_TYPE_FIBER_XAUI:
3397 	case FW_PORT_TYPE_SFP:
3398 	case FW_PORT_TYPE_QSFP_10G:
3399 	case FW_PORT_TYPE_QSA:
3400 	case FW_PORT_TYPE_QSFP:
3401 	case FW_PORT_TYPE_CR4_QSFP:
3402 	case FW_PORT_TYPE_CR_QSFP:
3403 	case FW_PORT_TYPE_CR2_QSFP:
3404 	case FW_PORT_TYPE_SFP28:
3405 		/* Pluggable transceiver */
3406 		switch (pi->mod_type) {
3407 		case FW_PORT_MOD_TYPE_LR:
3408 			switch (speed) {
3409 			case FW_PORT_CAP32_SPEED_1G:
3410 				return (IFM_1000_LX);
3411 			case FW_PORT_CAP32_SPEED_10G:
3412 				return (IFM_10G_LR);
3413 			case FW_PORT_CAP32_SPEED_25G:
3414 				return (IFM_25G_LR);
3415 			case FW_PORT_CAP32_SPEED_40G:
3416 				return (IFM_40G_LR4);
3417 			case FW_PORT_CAP32_SPEED_50G:
3418 				return (IFM_50G_LR2);
3419 			case FW_PORT_CAP32_SPEED_100G:
3420 				return (IFM_100G_LR4);
3421 			}
3422 			break;
3423 		case FW_PORT_MOD_TYPE_SR:
3424 			switch (speed) {
3425 			case FW_PORT_CAP32_SPEED_1G:
3426 				return (IFM_1000_SX);
3427 			case FW_PORT_CAP32_SPEED_10G:
3428 				return (IFM_10G_SR);
3429 			case FW_PORT_CAP32_SPEED_25G:
3430 				return (IFM_25G_SR);
3431 			case FW_PORT_CAP32_SPEED_40G:
3432 				return (IFM_40G_SR4);
3433 			case FW_PORT_CAP32_SPEED_50G:
3434 				return (IFM_50G_SR2);
3435 			case FW_PORT_CAP32_SPEED_100G:
3436 				return (IFM_100G_SR4);
3437 			}
3438 			break;
3439 		case FW_PORT_MOD_TYPE_ER:
3440 			if (speed == FW_PORT_CAP32_SPEED_10G)
3441 				return (IFM_10G_ER);
3442 			break;
3443 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3444 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3445 			switch (speed) {
3446 			case FW_PORT_CAP32_SPEED_1G:
3447 				return (IFM_1000_CX);
3448 			case FW_PORT_CAP32_SPEED_10G:
3449 				return (IFM_10G_TWINAX);
3450 			case FW_PORT_CAP32_SPEED_25G:
3451 				return (IFM_25G_CR);
3452 			case FW_PORT_CAP32_SPEED_40G:
3453 				return (IFM_40G_CR4);
3454 			case FW_PORT_CAP32_SPEED_50G:
3455 				return (IFM_50G_CR2);
3456 			case FW_PORT_CAP32_SPEED_100G:
3457 				return (IFM_100G_CR4);
3458 			}
3459 			break;
3460 		case FW_PORT_MOD_TYPE_LRM:
3461 			if (speed == FW_PORT_CAP32_SPEED_10G)
3462 				return (IFM_10G_LRM);
3463 			break;
3464 		case FW_PORT_MOD_TYPE_NA:
3465 			MPASS(0);	/* Not pluggable? */
3466 			/* fall throough */
3467 		case FW_PORT_MOD_TYPE_ERROR:
3468 		case FW_PORT_MOD_TYPE_UNKNOWN:
3469 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3470 			break;
3471 		case FW_PORT_MOD_TYPE_NONE:
3472 			return (IFM_NONE);
3473 		}
3474 		break;
3475 	case FW_PORT_TYPE_NONE:
3476 		return (IFM_NONE);
3477 	}
3478 
3479 	return (IFM_UNKNOWN);
3480 }
3481 
3482 void
3483 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3484 {
3485 	struct vi_info *vi = if_getsoftc(ifp);
3486 	struct port_info *pi = vi->pi;
3487 	struct adapter *sc = pi->adapter;
3488 	struct link_config *lc = &pi->link_cfg;
3489 
3490 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3491 		return;
3492 	PORT_LOCK(pi);
3493 
3494 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3495 		/*
3496 		 * If all the interfaces are administratively down the firmware
3497 		 * does not report transceiver changes.  Refresh port info here
3498 		 * so that ifconfig displays accurate ifmedia at all times.
3499 		 * This is the only reason we have a synchronized op in this
3500 		 * function.  Just PORT_LOCK would have been enough otherwise.
3501 		 */
3502 		t4_update_port_info(pi);
3503 		build_medialist(pi);
3504 	}
3505 
3506 	/* ifm_status */
3507 	ifmr->ifm_status = IFM_AVALID;
3508 	if (lc->link_ok == false)
3509 		goto done;
3510 	ifmr->ifm_status |= IFM_ACTIVE;
3511 
3512 	/* ifm_active */
3513 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3514 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3515 	if (lc->fc & PAUSE_RX)
3516 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3517 	if (lc->fc & PAUSE_TX)
3518 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3519 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3520 done:
3521 	PORT_UNLOCK(pi);
3522 	end_synchronized_op(sc, 0);
3523 }
3524 
3525 static int
3526 vcxgbe_probe(device_t dev)
3527 {
3528 	struct vi_info *vi = device_get_softc(dev);
3529 
3530 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3531 	    vi - vi->pi->vi);
3532 
3533 	return (BUS_PROBE_DEFAULT);
3534 }
3535 
3536 static int
3537 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3538 {
3539 	int func, index, rc;
3540 	uint32_t param, val;
3541 
3542 	ASSERT_SYNCHRONIZED_OP(sc);
3543 
3544 	index = vi - pi->vi;
3545 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3546 	KASSERT(index < nitems(vi_mac_funcs),
3547 	    ("%s: VI %s doesn't have a MAC func", __func__,
3548 	    device_get_nameunit(vi->dev)));
3549 	func = vi_mac_funcs[index];
3550 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3551 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3552 	if (rc < 0) {
3553 		CH_ERR(vi, "failed to allocate virtual interface %d"
3554 		    "for port %d: %d\n", index, pi->port_id, -rc);
3555 		return (-rc);
3556 	}
3557 	vi->viid = rc;
3558 
3559 	if (vi->rss_size == 1) {
3560 		/*
3561 		 * This VI didn't get a slice of the RSS table.  Reduce the
3562 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3563 		 * configuration file (nvi, rssnvi for this PF) if this is a
3564 		 * problem.
3565 		 */
3566 		device_printf(vi->dev, "RSS table not available.\n");
3567 		vi->rss_base = 0xffff;
3568 
3569 		return (0);
3570 	}
3571 
3572 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3573 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3574 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3575 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3576 	if (rc)
3577 		vi->rss_base = 0xffff;
3578 	else {
3579 		MPASS((val >> 16) == vi->rss_size);
3580 		vi->rss_base = val & 0xffff;
3581 	}
3582 
3583 	return (0);
3584 }
3585 
3586 static int
3587 vcxgbe_attach(device_t dev)
3588 {
3589 	struct vi_info *vi;
3590 	struct port_info *pi;
3591 	struct adapter *sc;
3592 	int rc;
3593 
3594 	vi = device_get_softc(dev);
3595 	pi = vi->pi;
3596 	sc = pi->adapter;
3597 
3598 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3599 	if (rc)
3600 		return (rc);
3601 	rc = alloc_extra_vi(sc, pi, vi);
3602 	end_synchronized_op(sc, 0);
3603 	if (rc)
3604 		return (rc);
3605 
3606 	cxgbe_vi_attach(dev, vi);
3607 
3608 	return (0);
3609 }
3610 
3611 static int
3612 vcxgbe_detach(device_t dev)
3613 {
3614 	struct vi_info *vi;
3615 	struct adapter *sc;
3616 
3617 	vi = device_get_softc(dev);
3618 	sc = vi->adapter;
3619 
3620 	begin_vi_detach(sc, vi);
3621 	cxgbe_vi_detach(vi);
3622 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3623 	end_vi_detach(sc, vi);
3624 
3625 	return (0);
3626 }
3627 
3628 static struct callout fatal_callout;
3629 static struct taskqueue *reset_tq;
3630 
3631 static void
3632 delayed_panic(void *arg)
3633 {
3634 	struct adapter *sc = arg;
3635 
3636 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3637 }
3638 
3639 static void
3640 fatal_error_task(void *arg, int pending)
3641 {
3642 	struct adapter *sc = arg;
3643 	int rc;
3644 
3645 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3646 		dump_cim_regs(sc);
3647 		dump_cimla(sc);
3648 		dump_devlog(sc);
3649 	}
3650 
3651 	if (t4_reset_on_fatal_err) {
3652 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3653 		rc = reset_adapter_with_pci_bus_reset(sc);
3654 		if (rc == 0 && t4_panic_on_fatal_err) {
3655 			CH_ALERT(sc, "reset was successful, "
3656 			    "system will NOT panic.\n");
3657 			return;
3658 		}
3659 	}
3660 
3661 	if (t4_panic_on_fatal_err) {
3662 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3663 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3664 	}
3665 }
3666 
3667 void
3668 t4_fatal_err(struct adapter *sc, bool fw_error)
3669 {
3670 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3671 
3672 	stop_adapter(sc);
3673 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3674 		return;
3675 	if (fw_error) {
3676 		/*
3677 		 * We are here because of a firmware error/timeout and not
3678 		 * because of a hardware interrupt.  It is possible (although
3679 		 * not very likely) that an error interrupt was also raised but
3680 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3681 		 * main INT_CAUSE registers here to make sure we haven't missed
3682 		 * anything interesting.
3683 		 */
3684 		t4_slow_intr_handler(sc, verbose);
3685 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3686 	}
3687 	t4_report_fw_error(sc);
3688 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3689 	    device_get_nameunit(sc->dev), fw_error);
3690 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3691 }
3692 
3693 void
3694 t4_add_adapter(struct adapter *sc)
3695 {
3696 	sx_xlock(&t4_list_lock);
3697 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3698 	sx_xunlock(&t4_list_lock);
3699 }
3700 
3701 int
3702 t4_map_bars_0_and_4(struct adapter *sc)
3703 {
3704 	sc->regs_rid = PCIR_BAR(0);
3705 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3706 	    &sc->regs_rid, RF_ACTIVE);
3707 	if (sc->regs_res == NULL) {
3708 		device_printf(sc->dev, "cannot map registers.\n");
3709 		return (ENXIO);
3710 	}
3711 	sc->bt = rman_get_bustag(sc->regs_res);
3712 	sc->bh = rman_get_bushandle(sc->regs_res);
3713 	sc->mmio_len = rman_get_size(sc->regs_res);
3714 	setbit(&sc->doorbells, DOORBELL_KDB);
3715 
3716 	sc->msix_rid = PCIR_BAR(4);
3717 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3718 	    &sc->msix_rid, RF_ACTIVE);
3719 	if (sc->msix_res == NULL) {
3720 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3721 		return (ENXIO);
3722 	}
3723 
3724 	return (0);
3725 }
3726 
3727 int
3728 t4_map_bar_2(struct adapter *sc)
3729 {
3730 
3731 	/*
3732 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3733 	 * to map it if RDMA is disabled.
3734 	 */
3735 	if (is_t4(sc) && sc->rdmacaps == 0)
3736 		return (0);
3737 
3738 	sc->udbs_rid = PCIR_BAR(2);
3739 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3740 	    &sc->udbs_rid, RF_ACTIVE);
3741 	if (sc->udbs_res == NULL) {
3742 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3743 		return (ENXIO);
3744 	}
3745 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3746 
3747 	if (chip_id(sc) >= CHELSIO_T5) {
3748 		setbit(&sc->doorbells, DOORBELL_UDB);
3749 #if defined(__i386__) || defined(__amd64__)
3750 		if (t5_write_combine) {
3751 			int rc, mode;
3752 
3753 			/*
3754 			 * Enable write combining on BAR2.  This is the
3755 			 * userspace doorbell BAR and is split into 128B
3756 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3757 			 * with an egress queue.  The first 64B has the doorbell
3758 			 * and the second 64B can be used to submit a tx work
3759 			 * request with an implicit doorbell.
3760 			 */
3761 
3762 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3763 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3764 			if (rc == 0) {
3765 				clrbit(&sc->doorbells, DOORBELL_UDB);
3766 				setbit(&sc->doorbells, DOORBELL_WCWR);
3767 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3768 			} else {
3769 				device_printf(sc->dev,
3770 				    "couldn't enable write combining: %d\n",
3771 				    rc);
3772 			}
3773 
3774 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3775 			t4_write_reg(sc, A_SGE_STAT_CFG,
3776 			    V_STATSOURCE_T5(7) | mode);
3777 		}
3778 #endif
3779 	}
3780 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3781 
3782 	return (0);
3783 }
3784 
3785 int
3786 t4_adj_doorbells(struct adapter *sc)
3787 {
3788 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3789 		sc->doorbells &= t4_doorbells_allowed;
3790 		return (0);
3791 	}
3792 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3793 	       sc->doorbells, t4_doorbells_allowed);
3794 	return (EINVAL);
3795 }
3796 
3797 struct memwin_init {
3798 	uint32_t base;
3799 	uint32_t aperture;
3800 };
3801 
3802 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3803 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3804 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3805 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3806 };
3807 
3808 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3809 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3810 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3811 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3812 };
3813 
3814 static void
3815 setup_memwin(struct adapter *sc)
3816 {
3817 	const struct memwin_init *mw_init;
3818 	struct memwin *mw;
3819 	int i;
3820 	uint32_t bar0;
3821 
3822 	if (is_t4(sc)) {
3823 		/*
3824 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3825 		 * mechanism.  Works from within PCI passthrough environments
3826 		 * too, where rman_get_start() can return a different value.  We
3827 		 * need to program the T4 memory window decoders with the actual
3828 		 * addresses that will be coming across the PCIe link.
3829 		 */
3830 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3831 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3832 
3833 		mw_init = &t4_memwin[0];
3834 	} else {
3835 		/* T5+ use the relative offset inside the PCIe BAR */
3836 		bar0 = 0;
3837 
3838 		mw_init = &t5_memwin[0];
3839 	}
3840 
3841 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3842 		if (!rw_initialized(&mw->mw_lock)) {
3843 			rw_init(&mw->mw_lock, "memory window access");
3844 			mw->mw_base = mw_init->base;
3845 			mw->mw_aperture = mw_init->aperture;
3846 			mw->mw_curpos = 0;
3847 		}
3848 		t4_write_reg(sc,
3849 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3850 		    (mw->mw_base + bar0) | V_BIR(0) |
3851 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3852 		rw_wlock(&mw->mw_lock);
3853 		position_memwin(sc, i, mw->mw_curpos);
3854 		rw_wunlock(&mw->mw_lock);
3855 	}
3856 
3857 	/* flush */
3858 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3859 }
3860 
3861 /*
3862  * Positions the memory window at the given address in the card's address space.
3863  * There are some alignment requirements and the actual position may be at an
3864  * address prior to the requested address.  mw->mw_curpos always has the actual
3865  * position of the window.
3866  */
3867 static void
3868 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3869 {
3870 	struct memwin *mw;
3871 	uint32_t pf;
3872 	uint32_t reg;
3873 
3874 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3875 	mw = &sc->memwin[idx];
3876 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3877 
3878 	if (is_t4(sc)) {
3879 		pf = 0;
3880 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3881 	} else {
3882 		pf = V_PFNUM(sc->pf);
3883 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3884 	}
3885 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3886 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3887 	t4_read_reg(sc, reg);	/* flush */
3888 }
3889 
3890 int
3891 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3892     int len, int rw)
3893 {
3894 	struct memwin *mw;
3895 	uint32_t mw_end, v;
3896 
3897 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3898 
3899 	/* Memory can only be accessed in naturally aligned 4 byte units */
3900 	if (addr & 3 || len & 3 || len <= 0)
3901 		return (EINVAL);
3902 
3903 	mw = &sc->memwin[idx];
3904 	while (len > 0) {
3905 		rw_rlock(&mw->mw_lock);
3906 		mw_end = mw->mw_curpos + mw->mw_aperture;
3907 		if (addr >= mw_end || addr < mw->mw_curpos) {
3908 			/* Will need to reposition the window */
3909 			if (!rw_try_upgrade(&mw->mw_lock)) {
3910 				rw_runlock(&mw->mw_lock);
3911 				rw_wlock(&mw->mw_lock);
3912 			}
3913 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3914 			position_memwin(sc, idx, addr);
3915 			rw_downgrade(&mw->mw_lock);
3916 			mw_end = mw->mw_curpos + mw->mw_aperture;
3917 		}
3918 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3919 		while (addr < mw_end && len > 0) {
3920 			if (rw == 0) {
3921 				v = t4_read_reg(sc, mw->mw_base + addr -
3922 				    mw->mw_curpos);
3923 				*val++ = le32toh(v);
3924 			} else {
3925 				v = *val++;
3926 				t4_write_reg(sc, mw->mw_base + addr -
3927 				    mw->mw_curpos, htole32(v));
3928 			}
3929 			addr += 4;
3930 			len -= 4;
3931 		}
3932 		rw_runlock(&mw->mw_lock);
3933 	}
3934 
3935 	return (0);
3936 }
3937 
3938 CTASSERT(M_TID_COOKIE == M_COOKIE);
3939 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3940 
3941 static void
3942 t4_init_atid_table(struct adapter *sc)
3943 {
3944 	struct tid_info *t;
3945 	int i;
3946 
3947 	t = &sc->tids;
3948 	if (t->natids == 0)
3949 		return;
3950 
3951 	MPASS(t->atid_tab == NULL);
3952 
3953 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3954 	    M_ZERO | M_WAITOK);
3955 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3956 	t->afree = t->atid_tab;
3957 	t->atids_in_use = 0;
3958 	t->atid_alloc_stopped = false;
3959 	for (i = 1; i < t->natids; i++)
3960 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3961 	t->atid_tab[t->natids - 1].next = NULL;
3962 }
3963 
3964 static void
3965 t4_free_atid_table(struct adapter *sc)
3966 {
3967 	struct tid_info *t;
3968 
3969 	t = &sc->tids;
3970 
3971 	KASSERT(t->atids_in_use == 0,
3972 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3973 
3974 	if (mtx_initialized(&t->atid_lock))
3975 		mtx_destroy(&t->atid_lock);
3976 	free(t->atid_tab, M_CXGBE);
3977 	t->atid_tab = NULL;
3978 }
3979 
3980 static void
3981 stop_atid_allocator(struct adapter *sc)
3982 {
3983 	struct tid_info *t = &sc->tids;
3984 
3985 	mtx_lock(&t->atid_lock);
3986 	t->atid_alloc_stopped = true;
3987 	mtx_unlock(&t->atid_lock);
3988 }
3989 
3990 static void
3991 restart_atid_allocator(struct adapter *sc)
3992 {
3993 	struct tid_info *t = &sc->tids;
3994 
3995 	mtx_lock(&t->atid_lock);
3996 	KASSERT(t->atids_in_use == 0,
3997 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3998 	t->atid_alloc_stopped = false;
3999 	mtx_unlock(&t->atid_lock);
4000 }
4001 
4002 int
4003 alloc_atid(struct adapter *sc, void *ctx)
4004 {
4005 	struct tid_info *t = &sc->tids;
4006 	int atid = -1;
4007 
4008 	mtx_lock(&t->atid_lock);
4009 	if (t->afree && !t->atid_alloc_stopped) {
4010 		union aopen_entry *p = t->afree;
4011 
4012 		atid = p - t->atid_tab;
4013 		MPASS(atid <= M_TID_TID);
4014 		t->afree = p->next;
4015 		p->data = ctx;
4016 		t->atids_in_use++;
4017 	}
4018 	mtx_unlock(&t->atid_lock);
4019 	return (atid);
4020 }
4021 
4022 void *
4023 lookup_atid(struct adapter *sc, int atid)
4024 {
4025 	struct tid_info *t = &sc->tids;
4026 
4027 	return (t->atid_tab[atid].data);
4028 }
4029 
4030 void
4031 free_atid(struct adapter *sc, int atid)
4032 {
4033 	struct tid_info *t = &sc->tids;
4034 	union aopen_entry *p = &t->atid_tab[atid];
4035 
4036 	mtx_lock(&t->atid_lock);
4037 	p->next = t->afree;
4038 	t->afree = p;
4039 	t->atids_in_use--;
4040 	mtx_unlock(&t->atid_lock);
4041 }
4042 
4043 static void
4044 queue_tid_release(struct adapter *sc, int tid)
4045 {
4046 
4047 	CXGBE_UNIMPLEMENTED("deferred tid release");
4048 }
4049 
4050 void
4051 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4052 {
4053 	struct wrqe *wr;
4054 	struct cpl_tid_release *req;
4055 
4056 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4057 	if (wr == NULL) {
4058 		queue_tid_release(sc, tid);	/* defer */
4059 		return;
4060 	}
4061 	req = wrtod(wr);
4062 
4063 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4064 
4065 	t4_wrq_tx(sc, wr);
4066 }
4067 
4068 static int
4069 t4_range_cmp(const void *a, const void *b)
4070 {
4071 	return ((const struct t4_range *)a)->start -
4072 	       ((const struct t4_range *)b)->start;
4073 }
4074 
4075 /*
4076  * Verify that the memory range specified by the addr/len pair is valid within
4077  * the card's address space.
4078  */
4079 static int
4080 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4081 {
4082 	struct t4_range mem_ranges[4], *r, *next;
4083 	uint32_t em, addr_len;
4084 	int i, n, remaining;
4085 
4086 	/* Memory can only be accessed in naturally aligned 4 byte units */
4087 	if (addr & 3 || len & 3 || len == 0)
4088 		return (EINVAL);
4089 
4090 	/* Enabled memories */
4091 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4092 
4093 	r = &mem_ranges[0];
4094 	n = 0;
4095 	bzero(r, sizeof(mem_ranges));
4096 	if (em & F_EDRAM0_ENABLE) {
4097 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4098 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4099 		if (r->size > 0) {
4100 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4101 			if (addr >= r->start &&
4102 			    addr + len <= r->start + r->size)
4103 				return (0);
4104 			r++;
4105 			n++;
4106 		}
4107 	}
4108 	if (em & F_EDRAM1_ENABLE) {
4109 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4110 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4111 		if (r->size > 0) {
4112 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4113 			if (addr >= r->start &&
4114 			    addr + len <= r->start + r->size)
4115 				return (0);
4116 			r++;
4117 			n++;
4118 		}
4119 	}
4120 	if (em & F_EXT_MEM_ENABLE) {
4121 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4122 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4123 		if (r->size > 0) {
4124 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4125 			if (addr >= r->start &&
4126 			    addr + len <= r->start + r->size)
4127 				return (0);
4128 			r++;
4129 			n++;
4130 		}
4131 	}
4132 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4133 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4134 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4135 		if (r->size > 0) {
4136 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4137 			if (addr >= r->start &&
4138 			    addr + len <= r->start + r->size)
4139 				return (0);
4140 			r++;
4141 			n++;
4142 		}
4143 	}
4144 	MPASS(n <= nitems(mem_ranges));
4145 
4146 	if (n > 1) {
4147 		/* Sort and merge the ranges. */
4148 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4149 
4150 		/* Start from index 0 and examine the next n - 1 entries. */
4151 		r = &mem_ranges[0];
4152 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4153 
4154 			MPASS(r->size > 0);	/* r is a valid entry. */
4155 			next = r + 1;
4156 			MPASS(next->size > 0);	/* and so is the next one. */
4157 
4158 			while (r->start + r->size >= next->start) {
4159 				/* Merge the next one into the current entry. */
4160 				r->size = max(r->start + r->size,
4161 				    next->start + next->size) - r->start;
4162 				n--;	/* One fewer entry in total. */
4163 				if (--remaining == 0)
4164 					goto done;	/* short circuit */
4165 				next++;
4166 			}
4167 			if (next != r + 1) {
4168 				/*
4169 				 * Some entries were merged into r and next
4170 				 * points to the first valid entry that couldn't
4171 				 * be merged.
4172 				 */
4173 				MPASS(next->size > 0);	/* must be valid */
4174 				memcpy(r + 1, next, remaining * sizeof(*r));
4175 #ifdef INVARIANTS
4176 				/*
4177 				 * This so that the foo->size assertion in the
4178 				 * next iteration of the loop do the right
4179 				 * thing for entries that were pulled up and are
4180 				 * no longer valid.
4181 				 */
4182 				MPASS(n < nitems(mem_ranges));
4183 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4184 				    sizeof(struct t4_range));
4185 #endif
4186 			}
4187 		}
4188 done:
4189 		/* Done merging the ranges. */
4190 		MPASS(n > 0);
4191 		r = &mem_ranges[0];
4192 		for (i = 0; i < n; i++, r++) {
4193 			if (addr >= r->start &&
4194 			    addr + len <= r->start + r->size)
4195 				return (0);
4196 		}
4197 	}
4198 
4199 	return (EFAULT);
4200 }
4201 
4202 static int
4203 fwmtype_to_hwmtype(int mtype)
4204 {
4205 
4206 	switch (mtype) {
4207 	case FW_MEMTYPE_EDC0:
4208 		return (MEM_EDC0);
4209 	case FW_MEMTYPE_EDC1:
4210 		return (MEM_EDC1);
4211 	case FW_MEMTYPE_EXTMEM:
4212 		return (MEM_MC0);
4213 	case FW_MEMTYPE_EXTMEM1:
4214 		return (MEM_MC1);
4215 	default:
4216 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4217 	}
4218 }
4219 
4220 /*
4221  * Verify that the memory range specified by the memtype/offset/len pair is
4222  * valid and lies entirely within the memtype specified.  The global address of
4223  * the start of the range is returned in addr.
4224  */
4225 static int
4226 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4227     uint32_t *addr)
4228 {
4229 	uint32_t em, addr_len, maddr;
4230 
4231 	/* Memory can only be accessed in naturally aligned 4 byte units */
4232 	if (off & 3 || len & 3 || len == 0)
4233 		return (EINVAL);
4234 
4235 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4236 	switch (fwmtype_to_hwmtype(mtype)) {
4237 	case MEM_EDC0:
4238 		if (!(em & F_EDRAM0_ENABLE))
4239 			return (EINVAL);
4240 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4241 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4242 		break;
4243 	case MEM_EDC1:
4244 		if (!(em & F_EDRAM1_ENABLE))
4245 			return (EINVAL);
4246 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4247 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4248 		break;
4249 	case MEM_MC:
4250 		if (!(em & F_EXT_MEM_ENABLE))
4251 			return (EINVAL);
4252 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4253 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4254 		break;
4255 	case MEM_MC1:
4256 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4257 			return (EINVAL);
4258 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4259 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4260 		break;
4261 	default:
4262 		return (EINVAL);
4263 	}
4264 
4265 	*addr = maddr + off;	/* global address */
4266 	return (validate_mem_range(sc, *addr, len));
4267 }
4268 
4269 static int
4270 fixup_devlog_params(struct adapter *sc)
4271 {
4272 	struct devlog_params *dparams = &sc->params.devlog;
4273 	int rc;
4274 
4275 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4276 	    dparams->size, &dparams->addr);
4277 
4278 	return (rc);
4279 }
4280 
4281 static void
4282 update_nirq(struct intrs_and_queues *iaq, int nports)
4283 {
4284 
4285 	iaq->nirq = T4_EXTRA_INTR;
4286 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4287 	iaq->nirq += nports * iaq->nofldrxq;
4288 	iaq->nirq += nports * (iaq->num_vis - 1) *
4289 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4290 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4291 }
4292 
4293 /*
4294  * Adjust requirements to fit the number of interrupts available.
4295  */
4296 static void
4297 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4298     int navail)
4299 {
4300 	int old_nirq;
4301 	const int nports = sc->params.nports;
4302 
4303 	MPASS(nports > 0);
4304 	MPASS(navail > 0);
4305 
4306 	bzero(iaq, sizeof(*iaq));
4307 	iaq->intr_type = itype;
4308 	iaq->num_vis = t4_num_vis;
4309 	iaq->ntxq = t4_ntxq;
4310 	iaq->ntxq_vi = t4_ntxq_vi;
4311 	iaq->nrxq = t4_nrxq;
4312 	iaq->nrxq_vi = t4_nrxq_vi;
4313 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4314 	if (is_offload(sc) || is_ethoffload(sc)) {
4315 		iaq->nofldtxq = t4_nofldtxq;
4316 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4317 	}
4318 #endif
4319 #ifdef TCP_OFFLOAD
4320 	if (is_offload(sc)) {
4321 		iaq->nofldrxq = t4_nofldrxq;
4322 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4323 	}
4324 #endif
4325 #ifdef DEV_NETMAP
4326 	if (t4_native_netmap & NN_MAIN_VI) {
4327 		iaq->nnmtxq = t4_nnmtxq;
4328 		iaq->nnmrxq = t4_nnmrxq;
4329 	}
4330 	if (t4_native_netmap & NN_EXTRA_VI) {
4331 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4332 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4333 	}
4334 #endif
4335 
4336 	update_nirq(iaq, nports);
4337 	if (iaq->nirq <= navail &&
4338 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4339 		/*
4340 		 * This is the normal case -- there are enough interrupts for
4341 		 * everything.
4342 		 */
4343 		goto done;
4344 	}
4345 
4346 	/*
4347 	 * If extra VIs have been configured try reducing their count and see if
4348 	 * that works.
4349 	 */
4350 	while (iaq->num_vis > 1) {
4351 		iaq->num_vis--;
4352 		update_nirq(iaq, nports);
4353 		if (iaq->nirq <= navail &&
4354 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4355 			device_printf(sc->dev, "virtual interfaces per port "
4356 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4357 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4358 			    "itype %d, navail %u, nirq %d.\n",
4359 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4360 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4361 			    itype, navail, iaq->nirq);
4362 			goto done;
4363 		}
4364 	}
4365 
4366 	/*
4367 	 * Extra VIs will not be created.  Log a message if they were requested.
4368 	 */
4369 	MPASS(iaq->num_vis == 1);
4370 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4371 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4372 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4373 	if (iaq->num_vis != t4_num_vis) {
4374 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4375 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4376 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4377 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4378 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4379 	}
4380 
4381 	/*
4382 	 * Keep reducing the number of NIC rx queues to the next lower power of
4383 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4384 	 * if that works.
4385 	 */
4386 	do {
4387 		if (iaq->nrxq > 1) {
4388 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4389 			if (iaq->nnmrxq > iaq->nrxq)
4390 				iaq->nnmrxq = iaq->nrxq;
4391 		}
4392 		if (iaq->nofldrxq > 1)
4393 			iaq->nofldrxq >>= 1;
4394 
4395 		old_nirq = iaq->nirq;
4396 		update_nirq(iaq, nports);
4397 		if (iaq->nirq <= navail &&
4398 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4399 			device_printf(sc->dev, "running with reduced number of "
4400 			    "rx queues because of shortage of interrupts.  "
4401 			    "nrxq=%u, nofldrxq=%u.  "
4402 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4403 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4404 			goto done;
4405 		}
4406 	} while (old_nirq != iaq->nirq);
4407 
4408 	/* One interrupt for everything.  Ugh. */
4409 	device_printf(sc->dev, "running with minimal number of queues.  "
4410 	    "itype %d, navail %u.\n", itype, navail);
4411 	iaq->nirq = 1;
4412 	iaq->nrxq = 1;
4413 	iaq->ntxq = 1;
4414 	if (iaq->nofldrxq > 0) {
4415 		iaq->nofldrxq = 1;
4416 		iaq->nofldtxq = 1;
4417 	}
4418 	iaq->nnmtxq = 0;
4419 	iaq->nnmrxq = 0;
4420 done:
4421 	MPASS(iaq->num_vis > 0);
4422 	if (iaq->num_vis > 1) {
4423 		MPASS(iaq->nrxq_vi > 0);
4424 		MPASS(iaq->ntxq_vi > 0);
4425 	}
4426 	MPASS(iaq->nirq > 0);
4427 	MPASS(iaq->nrxq > 0);
4428 	MPASS(iaq->ntxq > 0);
4429 	if (itype == INTR_MSI) {
4430 		MPASS(powerof2(iaq->nirq));
4431 	}
4432 }
4433 
4434 static int
4435 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4436 {
4437 	int rc, itype, navail, nalloc;
4438 
4439 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4440 
4441 		if ((itype & t4_intr_types) == 0)
4442 			continue;	/* not allowed */
4443 
4444 		if (itype == INTR_MSIX)
4445 			navail = pci_msix_count(sc->dev);
4446 		else if (itype == INTR_MSI)
4447 			navail = pci_msi_count(sc->dev);
4448 		else
4449 			navail = 1;
4450 restart:
4451 		if (navail == 0)
4452 			continue;
4453 
4454 		calculate_iaq(sc, iaq, itype, navail);
4455 		nalloc = iaq->nirq;
4456 		rc = 0;
4457 		if (itype == INTR_MSIX)
4458 			rc = pci_alloc_msix(sc->dev, &nalloc);
4459 		else if (itype == INTR_MSI)
4460 			rc = pci_alloc_msi(sc->dev, &nalloc);
4461 
4462 		if (rc == 0 && nalloc > 0) {
4463 			if (nalloc == iaq->nirq)
4464 				return (0);
4465 
4466 			/*
4467 			 * Didn't get the number requested.  Use whatever number
4468 			 * the kernel is willing to allocate.
4469 			 */
4470 			device_printf(sc->dev, "fewer vectors than requested, "
4471 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4472 			    itype, iaq->nirq, nalloc);
4473 			pci_release_msi(sc->dev);
4474 			navail = nalloc;
4475 			goto restart;
4476 		}
4477 
4478 		device_printf(sc->dev,
4479 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4480 		    itype, rc, iaq->nirq, nalloc);
4481 	}
4482 
4483 	device_printf(sc->dev,
4484 	    "failed to find a usable interrupt type.  "
4485 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4486 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4487 
4488 	return (ENXIO);
4489 }
4490 
4491 #define FW_VERSION(chip) ( \
4492     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4493     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4494     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4495     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4496 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4497 
4498 /* Just enough of fw_hdr to cover all version info. */
4499 struct fw_h {
4500 	__u8	ver;
4501 	__u8	chip;
4502 	__be16	len512;
4503 	__be32	fw_ver;
4504 	__be32	tp_microcode_ver;
4505 	__u8	intfver_nic;
4506 	__u8	intfver_vnic;
4507 	__u8	intfver_ofld;
4508 	__u8	intfver_ri;
4509 	__u8	intfver_iscsipdu;
4510 	__u8	intfver_iscsi;
4511 	__u8	intfver_fcoepdu;
4512 	__u8	intfver_fcoe;
4513 };
4514 /* Spot check a couple of fields. */
4515 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4516 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4517 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4518 
4519 struct fw_info {
4520 	uint8_t chip;
4521 	char *kld_name;
4522 	char *fw_mod_name;
4523 	struct fw_h fw_h;
4524 } fw_info[] = {
4525 	{
4526 		.chip = CHELSIO_T4,
4527 		.kld_name = "t4fw_cfg",
4528 		.fw_mod_name = "t4fw",
4529 		.fw_h = {
4530 			.chip = FW_HDR_CHIP_T4,
4531 			.fw_ver = htobe32(FW_VERSION(T4)),
4532 			.intfver_nic = FW_INTFVER(T4, NIC),
4533 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4534 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4535 			.intfver_ri = FW_INTFVER(T4, RI),
4536 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4537 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4538 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4539 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4540 		},
4541 	}, {
4542 		.chip = CHELSIO_T5,
4543 		.kld_name = "t5fw_cfg",
4544 		.fw_mod_name = "t5fw",
4545 		.fw_h = {
4546 			.chip = FW_HDR_CHIP_T5,
4547 			.fw_ver = htobe32(FW_VERSION(T5)),
4548 			.intfver_nic = FW_INTFVER(T5, NIC),
4549 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4550 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4551 			.intfver_ri = FW_INTFVER(T5, RI),
4552 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4553 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4554 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4555 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4556 		},
4557 	}, {
4558 		.chip = CHELSIO_T6,
4559 		.kld_name = "t6fw_cfg",
4560 		.fw_mod_name = "t6fw",
4561 		.fw_h = {
4562 			.chip = FW_HDR_CHIP_T6,
4563 			.fw_ver = htobe32(FW_VERSION(T6)),
4564 			.intfver_nic = FW_INTFVER(T6, NIC),
4565 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4566 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4567 			.intfver_ri = FW_INTFVER(T6, RI),
4568 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4569 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4570 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4571 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4572 		},
4573 	}
4574 };
4575 
4576 static struct fw_info *
4577 find_fw_info(int chip)
4578 {
4579 	int i;
4580 
4581 	for (i = 0; i < nitems(fw_info); i++) {
4582 		if (fw_info[i].chip == chip)
4583 			return (&fw_info[i]);
4584 	}
4585 	return (NULL);
4586 }
4587 
4588 /*
4589  * Is the given firmware API compatible with the one the driver was compiled
4590  * with?
4591  */
4592 static int
4593 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4594 {
4595 
4596 	/* short circuit if it's the exact same firmware version */
4597 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4598 		return (1);
4599 
4600 	/*
4601 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4602 	 * features that are supported in the driver.
4603 	 */
4604 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4605 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4606 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4607 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4608 		return (1);
4609 #undef SAME_INTF
4610 
4611 	return (0);
4612 }
4613 
4614 static int
4615 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4616     const struct firmware **fw)
4617 {
4618 	struct fw_info *fw_info;
4619 
4620 	*dcfg = NULL;
4621 	if (fw != NULL)
4622 		*fw = NULL;
4623 
4624 	fw_info = find_fw_info(chip_id(sc));
4625 	if (fw_info == NULL) {
4626 		device_printf(sc->dev,
4627 		    "unable to look up firmware information for chip %d.\n",
4628 		    chip_id(sc));
4629 		return (EINVAL);
4630 	}
4631 
4632 	*dcfg = firmware_get(fw_info->kld_name);
4633 	if (*dcfg != NULL) {
4634 		if (fw != NULL)
4635 			*fw = firmware_get(fw_info->fw_mod_name);
4636 		return (0);
4637 	}
4638 
4639 	return (ENOENT);
4640 }
4641 
4642 static void
4643 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4644     const struct firmware *fw)
4645 {
4646 
4647 	if (fw != NULL)
4648 		firmware_put(fw, FIRMWARE_UNLOAD);
4649 	if (dcfg != NULL)
4650 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4651 }
4652 
4653 /*
4654  * Return values:
4655  * 0 means no firmware install attempted.
4656  * ERESTART means a firmware install was attempted and was successful.
4657  * +ve errno means a firmware install was attempted but failed.
4658  */
4659 static int
4660 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4661     const struct fw_h *drv_fw, const char *reason, int *already)
4662 {
4663 	const struct firmware *cfg, *fw;
4664 	const uint32_t c = be32toh(card_fw->fw_ver);
4665 	uint32_t d, k;
4666 	int rc, fw_install;
4667 	struct fw_h bundled_fw;
4668 	bool load_attempted;
4669 
4670 	cfg = fw = NULL;
4671 	load_attempted = false;
4672 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4673 
4674 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4675 	if (t4_fw_install < 0) {
4676 		rc = load_fw_module(sc, &cfg, &fw);
4677 		if (rc != 0 || fw == NULL) {
4678 			device_printf(sc->dev,
4679 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4680 			    " will use compiled-in firmware version for"
4681 			    "hw.cxgbe.fw_install checks.\n",
4682 			    rc, cfg, fw);
4683 		} else {
4684 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4685 		}
4686 		load_attempted = true;
4687 	}
4688 	d = be32toh(bundled_fw.fw_ver);
4689 
4690 	if (reason != NULL)
4691 		goto install;
4692 
4693 	if ((sc->flags & FW_OK) == 0) {
4694 
4695 		if (c == 0xffffffff) {
4696 			reason = "missing";
4697 			goto install;
4698 		}
4699 
4700 		rc = 0;
4701 		goto done;
4702 	}
4703 
4704 	if (!fw_compatible(card_fw, &bundled_fw)) {
4705 		reason = "incompatible or unusable";
4706 		goto install;
4707 	}
4708 
4709 	if (d > c) {
4710 		reason = "older than the version bundled with this driver";
4711 		goto install;
4712 	}
4713 
4714 	if (fw_install == 2 && d != c) {
4715 		reason = "different than the version bundled with this driver";
4716 		goto install;
4717 	}
4718 
4719 	/* No reason to do anything to the firmware already on the card. */
4720 	rc = 0;
4721 	goto done;
4722 
4723 install:
4724 	rc = 0;
4725 	if ((*already)++)
4726 		goto done;
4727 
4728 	if (fw_install == 0) {
4729 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4730 		    "but the driver is prohibited from installing a firmware "
4731 		    "on the card.\n",
4732 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4733 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4734 
4735 		goto done;
4736 	}
4737 
4738 	/*
4739 	 * We'll attempt to install a firmware.  Load the module first (if it
4740 	 * hasn't been loaded already).
4741 	 */
4742 	if (!load_attempted) {
4743 		rc = load_fw_module(sc, &cfg, &fw);
4744 		if (rc != 0 || fw == NULL) {
4745 			device_printf(sc->dev,
4746 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4747 			    rc, cfg, fw);
4748 			/* carry on */
4749 		}
4750 	}
4751 	if (fw == NULL) {
4752 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4753 		    "but the driver cannot take corrective action because it "
4754 		    "is unable to load the firmware module.\n",
4755 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4756 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4757 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4758 		goto done;
4759 	}
4760 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4761 	if (k != d) {
4762 		MPASS(t4_fw_install > 0);
4763 		device_printf(sc->dev,
4764 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4765 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4766 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4767 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4768 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4769 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4770 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4771 		goto done;
4772 	}
4773 
4774 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4775 	    "installing firmware %u.%u.%u.%u on card.\n",
4776 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4777 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4778 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4779 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4780 
4781 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4782 	if (rc != 0) {
4783 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4784 	} else {
4785 		/* Installed successfully, update the cached header too. */
4786 		rc = ERESTART;
4787 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4788 	}
4789 done:
4790 	unload_fw_module(sc, cfg, fw);
4791 
4792 	return (rc);
4793 }
4794 
4795 /*
4796  * Establish contact with the firmware and attempt to become the master driver.
4797  *
4798  * A firmware will be installed to the card if needed (if the driver is allowed
4799  * to do so).
4800  */
4801 static int
4802 contact_firmware(struct adapter *sc)
4803 {
4804 	int rc, already = 0;
4805 	enum dev_state state;
4806 	struct fw_info *fw_info;
4807 	struct fw_hdr *card_fw;		/* fw on the card */
4808 	const struct fw_h *drv_fw;
4809 
4810 	fw_info = find_fw_info(chip_id(sc));
4811 	if (fw_info == NULL) {
4812 		device_printf(sc->dev,
4813 		    "unable to look up firmware information for chip %d.\n",
4814 		    chip_id(sc));
4815 		return (EINVAL);
4816 	}
4817 	drv_fw = &fw_info->fw_h;
4818 
4819 	/* Read the header of the firmware on the card */
4820 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4821 restart:
4822 	rc = -t4_get_fw_hdr(sc, card_fw);
4823 	if (rc != 0) {
4824 		device_printf(sc->dev,
4825 		    "unable to read firmware header from card's flash: %d\n",
4826 		    rc);
4827 		goto done;
4828 	}
4829 
4830 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4831 	    &already);
4832 	if (rc == ERESTART)
4833 		goto restart;
4834 	if (rc != 0)
4835 		goto done;
4836 
4837 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4838 	if (rc < 0 || state == DEV_STATE_ERR) {
4839 		rc = -rc;
4840 		device_printf(sc->dev,
4841 		    "failed to connect to the firmware: %d, %d.  "
4842 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4843 #if 0
4844 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4845 		    "not responding properly to HELLO", &already) == ERESTART)
4846 			goto restart;
4847 #endif
4848 		goto done;
4849 	}
4850 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4851 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4852 
4853 	if (rc == sc->pf) {
4854 		sc->flags |= MASTER_PF;
4855 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4856 		    NULL, &already);
4857 		if (rc == ERESTART)
4858 			rc = 0;
4859 		else if (rc != 0)
4860 			goto done;
4861 	} else if (state == DEV_STATE_UNINIT) {
4862 		/*
4863 		 * We didn't get to be the master so we definitely won't be
4864 		 * configuring the chip.  It's a bug if someone else hasn't
4865 		 * configured it already.
4866 		 */
4867 		device_printf(sc->dev, "couldn't be master(%d), "
4868 		    "device not already initialized either(%d).  "
4869 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4870 		rc = EPROTO;
4871 		goto done;
4872 	} else {
4873 		/*
4874 		 * Some other PF is the master and has configured the chip.
4875 		 * This is allowed but untested.
4876 		 */
4877 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4878 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4879 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4880 		sc->cfcsum = 0;
4881 		rc = 0;
4882 	}
4883 done:
4884 	if (rc != 0 && sc->flags & FW_OK) {
4885 		t4_fw_bye(sc, sc->mbox);
4886 		sc->flags &= ~FW_OK;
4887 	}
4888 	free(card_fw, M_CXGBE);
4889 	return (rc);
4890 }
4891 
4892 static int
4893 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4894     uint32_t mtype, uint32_t moff)
4895 {
4896 	struct fw_info *fw_info;
4897 	const struct firmware *dcfg, *rcfg = NULL;
4898 	const uint32_t *cfdata;
4899 	uint32_t cflen, addr;
4900 	int rc;
4901 
4902 	load_fw_module(sc, &dcfg, NULL);
4903 
4904 	/* Card specific interpretation of "default". */
4905 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4906 		if (pci_get_device(sc->dev) == 0x440a)
4907 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4908 		if (is_fpga(sc))
4909 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4910 	}
4911 
4912 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4913 		if (dcfg == NULL) {
4914 			device_printf(sc->dev,
4915 			    "KLD with default config is not available.\n");
4916 			rc = ENOENT;
4917 			goto done;
4918 		}
4919 		cfdata = dcfg->data;
4920 		cflen = dcfg->datasize & ~3;
4921 	} else {
4922 		char s[32];
4923 
4924 		fw_info = find_fw_info(chip_id(sc));
4925 		if (fw_info == NULL) {
4926 			device_printf(sc->dev,
4927 			    "unable to look up firmware information for chip %d.\n",
4928 			    chip_id(sc));
4929 			rc = EINVAL;
4930 			goto done;
4931 		}
4932 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4933 
4934 		rcfg = firmware_get(s);
4935 		if (rcfg == NULL) {
4936 			device_printf(sc->dev,
4937 			    "unable to load module \"%s\" for configuration "
4938 			    "profile \"%s\".\n", s, cfg_file);
4939 			rc = ENOENT;
4940 			goto done;
4941 		}
4942 		cfdata = rcfg->data;
4943 		cflen = rcfg->datasize & ~3;
4944 	}
4945 
4946 	if (cflen > FLASH_CFG_MAX_SIZE) {
4947 		device_printf(sc->dev,
4948 		    "config file too long (%d, max allowed is %d).\n",
4949 		    cflen, FLASH_CFG_MAX_SIZE);
4950 		rc = EINVAL;
4951 		goto done;
4952 	}
4953 
4954 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4955 	if (rc != 0) {
4956 		device_printf(sc->dev,
4957 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4958 		    __func__, mtype, moff, cflen, rc);
4959 		rc = EINVAL;
4960 		goto done;
4961 	}
4962 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4963 done:
4964 	if (rcfg != NULL)
4965 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4966 	unload_fw_module(sc, dcfg, NULL);
4967 	return (rc);
4968 }
4969 
4970 struct caps_allowed {
4971 	uint16_t nbmcaps;
4972 	uint16_t linkcaps;
4973 	uint16_t switchcaps;
4974 	uint16_t niccaps;
4975 	uint16_t toecaps;
4976 	uint16_t rdmacaps;
4977 	uint16_t cryptocaps;
4978 	uint16_t iscsicaps;
4979 	uint16_t fcoecaps;
4980 };
4981 
4982 #define FW_PARAM_DEV(param) \
4983 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4984 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4985 #define FW_PARAM_PFVF(param) \
4986 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4987 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4988 
4989 /*
4990  * Provide a configuration profile to the firmware and have it initialize the
4991  * chip accordingly.  This may involve uploading a configuration file to the
4992  * card.
4993  */
4994 static int
4995 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4996     const struct caps_allowed *caps_allowed)
4997 {
4998 	int rc;
4999 	struct fw_caps_config_cmd caps;
5000 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
5001 
5002 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
5003 	if (rc != 0) {
5004 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5005 		return (rc);
5006 	}
5007 
5008 	bzero(&caps, sizeof(caps));
5009 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5010 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5011 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5012 		mtype = 0;
5013 		moff = 0;
5014 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5015 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5016 		mtype = FW_MEMTYPE_FLASH;
5017 		moff = t4_flash_cfg_addr(sc);
5018 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5019 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5020 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5021 		    FW_LEN16(caps));
5022 	} else {
5023 		/*
5024 		 * Ask the firmware where it wants us to upload the config file.
5025 		 */
5026 		param = FW_PARAM_DEV(CF);
5027 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5028 		if (rc != 0) {
5029 			/* No support for config file?  Shouldn't happen. */
5030 			device_printf(sc->dev,
5031 			    "failed to query config file location: %d.\n", rc);
5032 			goto done;
5033 		}
5034 		mtype = G_FW_PARAMS_PARAM_Y(val);
5035 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5036 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5037 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5038 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5039 		    FW_LEN16(caps));
5040 
5041 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
5042 		if (rc != 0) {
5043 			device_printf(sc->dev,
5044 			    "failed to upload config file to card: %d.\n", rc);
5045 			goto done;
5046 		}
5047 	}
5048 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5049 	if (rc != 0) {
5050 		device_printf(sc->dev, "failed to pre-process config file: %d "
5051 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5052 		goto done;
5053 	}
5054 
5055 	finicsum = be32toh(caps.finicsum);
5056 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5057 	if (finicsum != cfcsum) {
5058 		device_printf(sc->dev,
5059 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5060 		    finicsum, cfcsum);
5061 	}
5062 	sc->cfcsum = cfcsum;
5063 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5064 
5065 	/*
5066 	 * Let the firmware know what features will (not) be used so it can tune
5067 	 * things accordingly.
5068 	 */
5069 #define LIMIT_CAPS(x) do { \
5070 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5071 } while (0)
5072 	LIMIT_CAPS(nbm);
5073 	LIMIT_CAPS(link);
5074 	LIMIT_CAPS(switch);
5075 	LIMIT_CAPS(nic);
5076 	LIMIT_CAPS(toe);
5077 	LIMIT_CAPS(rdma);
5078 	LIMIT_CAPS(crypto);
5079 	LIMIT_CAPS(iscsi);
5080 	LIMIT_CAPS(fcoe);
5081 #undef LIMIT_CAPS
5082 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5083 		/*
5084 		 * TOE and hashfilters are mutually exclusive.  It is a config
5085 		 * file or firmware bug if both are reported as available.  Try
5086 		 * to cope with the situation in non-debug builds by disabling
5087 		 * TOE.
5088 		 */
5089 		MPASS(caps.toecaps == 0);
5090 
5091 		caps.toecaps = 0;
5092 		caps.rdmacaps = 0;
5093 		caps.iscsicaps = 0;
5094 	}
5095 
5096 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5097 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5098 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5099 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5100 	if (rc != 0) {
5101 		device_printf(sc->dev,
5102 		    "failed to process config file: %d.\n", rc);
5103 		goto done;
5104 	}
5105 
5106 	t4_tweak_chip_settings(sc);
5107 	set_params__pre_init(sc);
5108 
5109 	/* get basic stuff going */
5110 	rc = -t4_fw_initialize(sc, sc->mbox);
5111 	if (rc != 0) {
5112 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5113 		goto done;
5114 	}
5115 done:
5116 	return (rc);
5117 }
5118 
5119 /*
5120  * Partition chip resources for use between various PFs, VFs, etc.
5121  */
5122 static int
5123 partition_resources(struct adapter *sc)
5124 {
5125 	char cfg_file[sizeof(t4_cfg_file)];
5126 	struct caps_allowed caps_allowed;
5127 	int rc;
5128 	bool fallback;
5129 
5130 	/* Only the master driver gets to configure the chip resources. */
5131 	MPASS(sc->flags & MASTER_PF);
5132 
5133 #define COPY_CAPS(x) do { \
5134 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5135 } while (0)
5136 	bzero(&caps_allowed, sizeof(caps_allowed));
5137 	COPY_CAPS(nbm);
5138 	COPY_CAPS(link);
5139 	COPY_CAPS(switch);
5140 	COPY_CAPS(nic);
5141 	COPY_CAPS(toe);
5142 	COPY_CAPS(rdma);
5143 	COPY_CAPS(crypto);
5144 	COPY_CAPS(iscsi);
5145 	COPY_CAPS(fcoe);
5146 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5147 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5148 retry:
5149 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5150 	if (rc != 0 && fallback) {
5151 		dump_devlog(sc);
5152 		device_printf(sc->dev,
5153 		    "failed (%d) to configure card with \"%s\" profile, "
5154 		    "will fall back to a basic configuration and retry.\n",
5155 		    rc, cfg_file);
5156 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5157 		bzero(&caps_allowed, sizeof(caps_allowed));
5158 		COPY_CAPS(switch);
5159 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5160 		fallback = false;
5161 		goto retry;
5162 	}
5163 #undef COPY_CAPS
5164 	return (rc);
5165 }
5166 
5167 /*
5168  * Retrieve parameters that are needed (or nice to have) very early.
5169  */
5170 static int
5171 get_params__pre_init(struct adapter *sc)
5172 {
5173 	int rc;
5174 	uint32_t param[2], val[2];
5175 
5176 	t4_get_version_info(sc);
5177 
5178 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5179 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5180 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5181 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5182 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5183 
5184 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5185 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5186 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5187 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5188 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5189 
5190 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5191 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5192 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5193 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5194 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5195 
5196 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5197 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5198 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5199 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5200 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5201 
5202 	param[0] = FW_PARAM_DEV(PORTVEC);
5203 	param[1] = FW_PARAM_DEV(CCLK);
5204 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5205 	if (rc != 0) {
5206 		device_printf(sc->dev,
5207 		    "failed to query parameters (pre_init): %d.\n", rc);
5208 		return (rc);
5209 	}
5210 
5211 	sc->params.portvec = val[0];
5212 	sc->params.nports = bitcount32(val[0]);
5213 	sc->params.vpd.cclk = val[1];
5214 
5215 	/* Read device log parameters. */
5216 	rc = -t4_init_devlog_params(sc, 1);
5217 	if (rc == 0)
5218 		fixup_devlog_params(sc);
5219 	else {
5220 		device_printf(sc->dev,
5221 		    "failed to get devlog parameters: %d.\n", rc);
5222 		rc = 0;	/* devlog isn't critical for device operation */
5223 	}
5224 
5225 	return (rc);
5226 }
5227 
5228 /*
5229  * Any params that need to be set before FW_INITIALIZE.
5230  */
5231 static int
5232 set_params__pre_init(struct adapter *sc)
5233 {
5234 	int rc = 0;
5235 	uint32_t param, val;
5236 
5237 	if (chip_id(sc) >= CHELSIO_T6) {
5238 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5239 		val = 1;
5240 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5241 		/* firmwares < 1.20.1.0 do not have this param. */
5242 		if (rc == FW_EINVAL &&
5243 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5244 			rc = 0;
5245 		}
5246 		if (rc != 0) {
5247 			device_printf(sc->dev,
5248 			    "failed to enable high priority filters :%d.\n",
5249 			    rc);
5250 		}
5251 
5252 		param = FW_PARAM_DEV(PPOD_EDRAM);
5253 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5254 		if (rc == 0 && val == 1) {
5255 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5256 			    &val);
5257 			if (rc != 0) {
5258 				device_printf(sc->dev,
5259 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5260 			}
5261 		}
5262 	}
5263 
5264 	/* Enable opaque VIIDs with firmwares that support it. */
5265 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5266 	val = 1;
5267 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5268 	if (rc == 0 && val == 1)
5269 		sc->params.viid_smt_extn_support = true;
5270 	else
5271 		sc->params.viid_smt_extn_support = false;
5272 
5273 	return (rc);
5274 }
5275 
5276 /*
5277  * Retrieve various parameters that are of interest to the driver.  The device
5278  * has been initialized by the firmware at this point.
5279  */
5280 static int
5281 get_params__post_init(struct adapter *sc)
5282 {
5283 	int rc;
5284 	uint32_t param[7], val[7];
5285 	struct fw_caps_config_cmd caps;
5286 
5287 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5288 	param[1] = FW_PARAM_PFVF(EQ_START);
5289 	param[2] = FW_PARAM_PFVF(FILTER_START);
5290 	param[3] = FW_PARAM_PFVF(FILTER_END);
5291 	param[4] = FW_PARAM_PFVF(L2T_START);
5292 	param[5] = FW_PARAM_PFVF(L2T_END);
5293 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5294 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5295 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5296 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5297 	if (rc != 0) {
5298 		device_printf(sc->dev,
5299 		    "failed to query parameters (post_init): %d.\n", rc);
5300 		return (rc);
5301 	}
5302 
5303 	sc->sge.iq_start = val[0];
5304 	sc->sge.eq_start = val[1];
5305 	if ((int)val[3] > (int)val[2]) {
5306 		sc->tids.ftid_base = val[2];
5307 		sc->tids.ftid_end = val[3];
5308 		sc->tids.nftids = val[3] - val[2] + 1;
5309 	}
5310 	sc->vres.l2t.start = val[4];
5311 	sc->vres.l2t.size = val[5] - val[4] + 1;
5312 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5313 	if (sc->vres.l2t.size > 0)
5314 		MPASS(fls(val[5]) <= S_SYNC_WR);
5315 	sc->params.core_vdd = val[6];
5316 
5317 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5318 	param[1] = FW_PARAM_PFVF(EQ_END);
5319 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5320 	if (rc != 0) {
5321 		device_printf(sc->dev,
5322 		    "failed to query parameters (post_init2): %d.\n", rc);
5323 		return (rc);
5324 	}
5325 	MPASS((int)val[0] >= sc->sge.iq_start);
5326 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5327 	MPASS((int)val[1] >= sc->sge.eq_start);
5328 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5329 
5330 	if (chip_id(sc) >= CHELSIO_T6) {
5331 
5332 		sc->tids.tid_base = t4_read_reg(sc,
5333 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5334 
5335 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5336 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5337 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5338 		if (rc != 0) {
5339 			device_printf(sc->dev,
5340 			   "failed to query hpfilter parameters: %d.\n", rc);
5341 			return (rc);
5342 		}
5343 		if ((int)val[1] > (int)val[0]) {
5344 			sc->tids.hpftid_base = val[0];
5345 			sc->tids.hpftid_end = val[1];
5346 			sc->tids.nhpftids = val[1] - val[0] + 1;
5347 
5348 			/*
5349 			 * These should go off if the layout changes and the
5350 			 * driver needs to catch up.
5351 			 */
5352 			MPASS(sc->tids.hpftid_base == 0);
5353 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5354 		}
5355 
5356 		param[0] = FW_PARAM_PFVF(RAWF_START);
5357 		param[1] = FW_PARAM_PFVF(RAWF_END);
5358 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5359 		if (rc != 0) {
5360 			device_printf(sc->dev,
5361 			   "failed to query rawf parameters: %d.\n", rc);
5362 			return (rc);
5363 		}
5364 		if ((int)val[1] > (int)val[0]) {
5365 			sc->rawf_base = val[0];
5366 			sc->nrawf = val[1] - val[0] + 1;
5367 		}
5368 	}
5369 
5370 	/*
5371 	 * The parameters that follow may not be available on all firmwares.  We
5372 	 * query them individually rather than in a compound query because old
5373 	 * firmwares fail the entire query if an unknown parameter is queried.
5374 	 */
5375 
5376 	/*
5377 	 * MPS buffer group configuration.
5378 	 */
5379 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5380 	val[0] = 0;
5381 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5382 	if (rc == 0)
5383 		sc->params.mps_bg_map = val[0];
5384 	else
5385 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5386 
5387 	param[0] = FW_PARAM_DEV(TPCHMAP);
5388 	val[0] = 0;
5389 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5390 	if (rc == 0)
5391 		sc->params.tp_ch_map = val[0];
5392 	else
5393 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5394 
5395 	/*
5396 	 * Determine whether the firmware supports the filter2 work request.
5397 	 */
5398 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5399 	val[0] = 0;
5400 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5401 	if (rc == 0)
5402 		sc->params.filter2_wr_support = val[0] != 0;
5403 	else
5404 		sc->params.filter2_wr_support = 0;
5405 
5406 	/*
5407 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5408 	 */
5409 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5410 	val[0] = 0;
5411 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5412 	if (rc == 0)
5413 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5414 	else
5415 		sc->params.ulptx_memwrite_dsgl = false;
5416 
5417 	/* FW_RI_FR_NSMR_TPTE_WR support */
5418 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5419 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5420 	if (rc == 0)
5421 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5422 	else
5423 		sc->params.fr_nsmr_tpte_wr_support = false;
5424 
5425 	/* Support for 512 SGL entries per FR MR. */
5426 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5427 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5428 	if (rc == 0)
5429 		sc->params.dev_512sgl_mr = val[0] != 0;
5430 	else
5431 		sc->params.dev_512sgl_mr = false;
5432 
5433 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5434 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5435 	if (rc == 0)
5436 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5437 	else
5438 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5439 
5440 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5441 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5442 	if (rc == 0) {
5443 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5444 		sc->params.nsched_cls = val[0];
5445 	} else
5446 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5447 
5448 	/* get capabilites */
5449 	bzero(&caps, sizeof(caps));
5450 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5451 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5452 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5453 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5454 	if (rc != 0) {
5455 		device_printf(sc->dev,
5456 		    "failed to get card capabilities: %d.\n", rc);
5457 		return (rc);
5458 	}
5459 
5460 #define READ_CAPS(x) do { \
5461 	sc->x = htobe16(caps.x); \
5462 } while (0)
5463 	READ_CAPS(nbmcaps);
5464 	READ_CAPS(linkcaps);
5465 	READ_CAPS(switchcaps);
5466 	READ_CAPS(niccaps);
5467 	READ_CAPS(toecaps);
5468 	READ_CAPS(rdmacaps);
5469 	READ_CAPS(cryptocaps);
5470 	READ_CAPS(iscsicaps);
5471 	READ_CAPS(fcoecaps);
5472 
5473 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5474 		MPASS(chip_id(sc) > CHELSIO_T4);
5475 		MPASS(sc->toecaps == 0);
5476 		sc->toecaps = 0;
5477 
5478 		param[0] = FW_PARAM_DEV(NTID);
5479 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5480 		if (rc != 0) {
5481 			device_printf(sc->dev,
5482 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5483 			return (rc);
5484 		}
5485 		sc->tids.ntids = val[0];
5486 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5487 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5488 			sc->tids.ntids -= sc->tids.nhpftids;
5489 		}
5490 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5491 		sc->params.hash_filter = 1;
5492 	}
5493 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5494 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5495 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5496 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5497 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5498 		if (rc != 0) {
5499 			device_printf(sc->dev,
5500 			    "failed to query NIC parameters: %d.\n", rc);
5501 			return (rc);
5502 		}
5503 		if ((int)val[1] > (int)val[0]) {
5504 			sc->tids.etid_base = val[0];
5505 			sc->tids.etid_end = val[1];
5506 			sc->tids.netids = val[1] - val[0] + 1;
5507 			sc->params.eo_wr_cred = val[2];
5508 			sc->params.ethoffload = 1;
5509 		}
5510 	}
5511 	if (sc->toecaps) {
5512 		/* query offload-related parameters */
5513 		param[0] = FW_PARAM_DEV(NTID);
5514 		param[1] = FW_PARAM_PFVF(SERVER_START);
5515 		param[2] = FW_PARAM_PFVF(SERVER_END);
5516 		param[3] = FW_PARAM_PFVF(TDDP_START);
5517 		param[4] = FW_PARAM_PFVF(TDDP_END);
5518 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5519 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5520 		if (rc != 0) {
5521 			device_printf(sc->dev,
5522 			    "failed to query TOE parameters: %d.\n", rc);
5523 			return (rc);
5524 		}
5525 		sc->tids.ntids = val[0];
5526 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5527 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5528 			sc->tids.ntids -= sc->tids.nhpftids;
5529 		}
5530 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5531 		if ((int)val[2] > (int)val[1]) {
5532 			sc->tids.stid_base = val[1];
5533 			sc->tids.nstids = val[2] - val[1] + 1;
5534 		}
5535 		sc->vres.ddp.start = val[3];
5536 		sc->vres.ddp.size = val[4] - val[3] + 1;
5537 		sc->params.ofldq_wr_cred = val[5];
5538 		sc->params.offload = 1;
5539 	} else {
5540 		/*
5541 		 * The firmware attempts memfree TOE configuration for -SO cards
5542 		 * and will report toecaps=0 if it runs out of resources (this
5543 		 * depends on the config file).  It may not report 0 for other
5544 		 * capabilities dependent on the TOE in this case.  Set them to
5545 		 * 0 here so that the driver doesn't bother tracking resources
5546 		 * that will never be used.
5547 		 */
5548 		sc->iscsicaps = 0;
5549 		sc->rdmacaps = 0;
5550 	}
5551 	if (sc->rdmacaps) {
5552 		param[0] = FW_PARAM_PFVF(STAG_START);
5553 		param[1] = FW_PARAM_PFVF(STAG_END);
5554 		param[2] = FW_PARAM_PFVF(RQ_START);
5555 		param[3] = FW_PARAM_PFVF(RQ_END);
5556 		param[4] = FW_PARAM_PFVF(PBL_START);
5557 		param[5] = FW_PARAM_PFVF(PBL_END);
5558 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5559 		if (rc != 0) {
5560 			device_printf(sc->dev,
5561 			    "failed to query RDMA parameters(1): %d.\n", rc);
5562 			return (rc);
5563 		}
5564 		sc->vres.stag.start = val[0];
5565 		sc->vres.stag.size = val[1] - val[0] + 1;
5566 		sc->vres.rq.start = val[2];
5567 		sc->vres.rq.size = val[3] - val[2] + 1;
5568 		sc->vres.pbl.start = val[4];
5569 		sc->vres.pbl.size = val[5] - val[4] + 1;
5570 
5571 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5572 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5573 		param[2] = FW_PARAM_PFVF(CQ_START);
5574 		param[3] = FW_PARAM_PFVF(CQ_END);
5575 		param[4] = FW_PARAM_PFVF(OCQ_START);
5576 		param[5] = FW_PARAM_PFVF(OCQ_END);
5577 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5578 		if (rc != 0) {
5579 			device_printf(sc->dev,
5580 			    "failed to query RDMA parameters(2): %d.\n", rc);
5581 			return (rc);
5582 		}
5583 		sc->vres.qp.start = val[0];
5584 		sc->vres.qp.size = val[1] - val[0] + 1;
5585 		sc->vres.cq.start = val[2];
5586 		sc->vres.cq.size = val[3] - val[2] + 1;
5587 		sc->vres.ocq.start = val[4];
5588 		sc->vres.ocq.size = val[5] - val[4] + 1;
5589 
5590 		param[0] = FW_PARAM_PFVF(SRQ_START);
5591 		param[1] = FW_PARAM_PFVF(SRQ_END);
5592 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5593 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5594 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5595 		if (rc != 0) {
5596 			device_printf(sc->dev,
5597 			    "failed to query RDMA parameters(3): %d.\n", rc);
5598 			return (rc);
5599 		}
5600 		sc->vres.srq.start = val[0];
5601 		sc->vres.srq.size = val[1] - val[0] + 1;
5602 		sc->params.max_ordird_qp = val[2];
5603 		sc->params.max_ird_adapter = val[3];
5604 	}
5605 	if (sc->iscsicaps) {
5606 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5607 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5608 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5609 		if (rc != 0) {
5610 			device_printf(sc->dev,
5611 			    "failed to query iSCSI parameters: %d.\n", rc);
5612 			return (rc);
5613 		}
5614 		sc->vres.iscsi.start = val[0];
5615 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5616 	}
5617 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5618 		param[0] = FW_PARAM_PFVF(TLS_START);
5619 		param[1] = FW_PARAM_PFVF(TLS_END);
5620 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5621 		if (rc != 0) {
5622 			device_printf(sc->dev,
5623 			    "failed to query TLS parameters: %d.\n", rc);
5624 			return (rc);
5625 		}
5626 		sc->vres.key.start = val[0];
5627 		sc->vres.key.size = val[1] - val[0] + 1;
5628 	}
5629 
5630 	/*
5631 	 * We've got the params we wanted to query directly from the firmware.
5632 	 * Grab some others via other means.
5633 	 */
5634 	t4_init_sge_params(sc);
5635 	t4_init_tp_params(sc);
5636 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5637 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5638 
5639 	rc = t4_verify_chip_settings(sc);
5640 	if (rc != 0)
5641 		return (rc);
5642 	t4_init_rx_buf_info(sc);
5643 
5644 	return (rc);
5645 }
5646 
5647 #ifdef KERN_TLS
5648 static void
5649 ktls_tick(void *arg)
5650 {
5651 	struct adapter *sc;
5652 	uint32_t tstamp;
5653 
5654 	sc = arg;
5655 	tstamp = tcp_ts_getticks();
5656 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5657 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5658 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5659 }
5660 
5661 static int
5662 t6_config_kern_tls(struct adapter *sc, bool enable)
5663 {
5664 	int rc;
5665 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5666 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5667 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5668 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5669 
5670 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5671 	if (rc != 0) {
5672 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5673 		    enable ?  "enable" : "disable", rc);
5674 		return (rc);
5675 	}
5676 
5677 	if (enable) {
5678 		sc->flags |= KERN_TLS_ON;
5679 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5680 		    C_HARDCLOCK);
5681 	} else {
5682 		sc->flags &= ~KERN_TLS_ON;
5683 		callout_stop(&sc->ktls_tick);
5684 	}
5685 
5686 	return (rc);
5687 }
5688 #endif
5689 
5690 static int
5691 set_params__post_init(struct adapter *sc)
5692 {
5693 	uint32_t mask, param, val;
5694 #ifdef TCP_OFFLOAD
5695 	int i, v, shift;
5696 #endif
5697 
5698 	/* ask for encapsulated CPLs */
5699 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5700 	val = 1;
5701 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5702 
5703 	/* Enable 32b port caps if the firmware supports it. */
5704 	param = FW_PARAM_PFVF(PORT_CAPS32);
5705 	val = 1;
5706 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5707 		sc->params.port_caps32 = 1;
5708 
5709 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5710 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5711 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5712 	    V_MASKFILTER(val - 1));
5713 
5714 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5715 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5716 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5717 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5718 	val = 0;
5719 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5720 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5721 		    F_ATTACKFILTERENABLE);
5722 		val |= F_DROPERRORATTACK;
5723 	}
5724 	if (t4_drop_ip_fragments != 0) {
5725 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5726 		    F_FRAGMENTDROP);
5727 		val |= F_DROPERRORFRAG;
5728 	}
5729 	if (t4_drop_pkts_with_l2_errors != 0)
5730 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5731 	if (t4_drop_pkts_with_l3_errors != 0) {
5732 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5733 		    F_DROPERRORCSUMIP;
5734 	}
5735 	if (t4_drop_pkts_with_l4_errors != 0) {
5736 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5737 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5738 	}
5739 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5740 
5741 #ifdef TCP_OFFLOAD
5742 	/*
5743 	 * Override the TOE timers with user provided tunables.  This is not the
5744 	 * recommended way to change the timers (the firmware config file is) so
5745 	 * these tunables are not documented.
5746 	 *
5747 	 * All the timer tunables are in microseconds.
5748 	 */
5749 	if (t4_toe_keepalive_idle != 0) {
5750 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5751 		v &= M_KEEPALIVEIDLE;
5752 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5753 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5754 	}
5755 	if (t4_toe_keepalive_interval != 0) {
5756 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5757 		v &= M_KEEPALIVEINTVL;
5758 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5759 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5760 	}
5761 	if (t4_toe_keepalive_count != 0) {
5762 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5763 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5764 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5765 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5766 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5767 	}
5768 	if (t4_toe_rexmt_min != 0) {
5769 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5770 		v &= M_RXTMIN;
5771 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5772 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5773 	}
5774 	if (t4_toe_rexmt_max != 0) {
5775 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5776 		v &= M_RXTMAX;
5777 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5778 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5779 	}
5780 	if (t4_toe_rexmt_count != 0) {
5781 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5782 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5783 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5784 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5785 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5786 	}
5787 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5788 		if (t4_toe_rexmt_backoff[i] != -1) {
5789 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5790 			shift = (i & 3) << 3;
5791 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5792 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5793 		}
5794 	}
5795 #endif
5796 
5797 	/*
5798 	 * Limit TOE connections to 2 reassembly "islands".  This is
5799 	 * required to permit migrating TOE connections to either
5800 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5801 	 */
5802 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5803 	    V_PASSMODE(2));
5804 
5805 #ifdef KERN_TLS
5806 	if (is_ktls(sc)) {
5807 		sc->tlst.inline_keys = t4_tls_inline_keys;
5808 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5809 		if (t4_kern_tls != 0 && is_t6(sc))
5810 			t6_config_kern_tls(sc, true);
5811 	}
5812 #endif
5813 	return (0);
5814 }
5815 
5816 #undef FW_PARAM_PFVF
5817 #undef FW_PARAM_DEV
5818 
5819 static void
5820 t4_set_desc(struct adapter *sc)
5821 {
5822 	struct adapter_params *p = &sc->params;
5823 
5824 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5825 }
5826 
5827 static inline void
5828 ifmedia_add4(struct ifmedia *ifm, int m)
5829 {
5830 
5831 	ifmedia_add(ifm, m, 0, NULL);
5832 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5833 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5834 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5835 }
5836 
5837 /*
5838  * This is the selected media, which is not quite the same as the active media.
5839  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5840  * and active are not the same, and "media: Ethernet selected" otherwise.
5841  */
5842 static void
5843 set_current_media(struct port_info *pi)
5844 {
5845 	struct link_config *lc;
5846 	struct ifmedia *ifm;
5847 	int mword;
5848 	u_int speed;
5849 
5850 	PORT_LOCK_ASSERT_OWNED(pi);
5851 
5852 	/* Leave current media alone if it's already set to IFM_NONE. */
5853 	ifm = &pi->media;
5854 	if (ifm->ifm_cur != NULL &&
5855 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5856 		return;
5857 
5858 	lc = &pi->link_cfg;
5859 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5860 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5861 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5862 		return;
5863 	}
5864 	mword = IFM_ETHER | IFM_FDX;
5865 	if (lc->requested_fc & PAUSE_TX)
5866 		mword |= IFM_ETH_TXPAUSE;
5867 	if (lc->requested_fc & PAUSE_RX)
5868 		mword |= IFM_ETH_RXPAUSE;
5869 	if (lc->requested_speed == 0)
5870 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5871 	else
5872 		speed = lc->requested_speed;
5873 	mword |= port_mword(pi, speed_to_fwcap(speed));
5874 	ifmedia_set(ifm, mword);
5875 }
5876 
5877 /*
5878  * Returns true if the ifmedia list for the port cannot change.
5879  */
5880 static bool
5881 fixed_ifmedia(struct port_info *pi)
5882 {
5883 
5884 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5885 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5886 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5887 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5888 	    pi->port_type == FW_PORT_TYPE_KX ||
5889 	    pi->port_type == FW_PORT_TYPE_KR ||
5890 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5891 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5892 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5893 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5894 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5895 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5896 }
5897 
5898 static void
5899 build_medialist(struct port_info *pi)
5900 {
5901 	uint32_t ss, speed;
5902 	int unknown, mword, bit;
5903 	struct link_config *lc;
5904 	struct ifmedia *ifm;
5905 
5906 	PORT_LOCK_ASSERT_OWNED(pi);
5907 
5908 	if (pi->flags & FIXED_IFMEDIA)
5909 		return;
5910 
5911 	/*
5912 	 * Rebuild the ifmedia list.
5913 	 */
5914 	ifm = &pi->media;
5915 	ifmedia_removeall(ifm);
5916 	lc = &pi->link_cfg;
5917 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5918 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5919 		MPASS(ss != 0);
5920 no_media:
5921 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5922 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5923 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5924 		return;
5925 	}
5926 
5927 	unknown = 0;
5928 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5929 		speed = 1 << bit;
5930 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5931 		if (ss & speed) {
5932 			mword = port_mword(pi, speed);
5933 			if (mword == IFM_NONE) {
5934 				goto no_media;
5935 			} else if (mword == IFM_UNKNOWN)
5936 				unknown++;
5937 			else
5938 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5939 		}
5940 	}
5941 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5942 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5943 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5944 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5945 
5946 	set_current_media(pi);
5947 }
5948 
5949 /*
5950  * Initialize the requested fields in the link config based on driver tunables.
5951  */
5952 static void
5953 init_link_config(struct port_info *pi)
5954 {
5955 	struct link_config *lc = &pi->link_cfg;
5956 
5957 	PORT_LOCK_ASSERT_OWNED(pi);
5958 
5959 	lc->requested_caps = 0;
5960 	lc->requested_speed = 0;
5961 
5962 	if (t4_autoneg == 0)
5963 		lc->requested_aneg = AUTONEG_DISABLE;
5964 	else if (t4_autoneg == 1)
5965 		lc->requested_aneg = AUTONEG_ENABLE;
5966 	else
5967 		lc->requested_aneg = AUTONEG_AUTO;
5968 
5969 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5970 	    PAUSE_AUTONEG);
5971 
5972 	if (t4_fec & FEC_AUTO)
5973 		lc->requested_fec = FEC_AUTO;
5974 	else if (t4_fec == 0)
5975 		lc->requested_fec = FEC_NONE;
5976 	else {
5977 		/* -1 is handled by the FEC_AUTO block above and not here. */
5978 		lc->requested_fec = t4_fec &
5979 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5980 		if (lc->requested_fec == 0)
5981 			lc->requested_fec = FEC_AUTO;
5982 	}
5983 	if (t4_force_fec < 0)
5984 		lc->force_fec = -1;
5985 	else if (t4_force_fec > 0)
5986 		lc->force_fec = 1;
5987 	else
5988 		lc->force_fec = 0;
5989 }
5990 
5991 /*
5992  * Makes sure that all requested settings comply with what's supported by the
5993  * port.  Returns the number of settings that were invalid and had to be fixed.
5994  */
5995 static int
5996 fixup_link_config(struct port_info *pi)
5997 {
5998 	int n = 0;
5999 	struct link_config *lc = &pi->link_cfg;
6000 	uint32_t fwspeed;
6001 
6002 	PORT_LOCK_ASSERT_OWNED(pi);
6003 
6004 	/* Speed (when not autonegotiating) */
6005 	if (lc->requested_speed != 0) {
6006 		fwspeed = speed_to_fwcap(lc->requested_speed);
6007 		if ((fwspeed & lc->pcaps) == 0) {
6008 			n++;
6009 			lc->requested_speed = 0;
6010 		}
6011 	}
6012 
6013 	/* Link autonegotiation */
6014 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6015 	    lc->requested_aneg == AUTONEG_DISABLE ||
6016 	    lc->requested_aneg == AUTONEG_AUTO);
6017 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6018 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6019 		n++;
6020 		lc->requested_aneg = AUTONEG_AUTO;
6021 	}
6022 
6023 	/* Flow control */
6024 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6025 	if (lc->requested_fc & PAUSE_TX &&
6026 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6027 		n++;
6028 		lc->requested_fc &= ~PAUSE_TX;
6029 	}
6030 	if (lc->requested_fc & PAUSE_RX &&
6031 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6032 		n++;
6033 		lc->requested_fc &= ~PAUSE_RX;
6034 	}
6035 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6036 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6037 		n++;
6038 		lc->requested_fc |= PAUSE_AUTONEG;
6039 	}
6040 
6041 	/* FEC */
6042 	if ((lc->requested_fec & FEC_RS &&
6043 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6044 	    (lc->requested_fec & FEC_BASER_RS &&
6045 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6046 		n++;
6047 		lc->requested_fec = FEC_AUTO;
6048 	}
6049 
6050 	return (n);
6051 }
6052 
6053 /*
6054  * Apply the requested L1 settings, which are expected to be valid, to the
6055  * hardware.
6056  */
6057 static int
6058 apply_link_config(struct port_info *pi)
6059 {
6060 	struct adapter *sc = pi->adapter;
6061 	struct link_config *lc = &pi->link_cfg;
6062 	int rc;
6063 
6064 #ifdef INVARIANTS
6065 	ASSERT_SYNCHRONIZED_OP(sc);
6066 	PORT_LOCK_ASSERT_OWNED(pi);
6067 
6068 	if (lc->requested_aneg == AUTONEG_ENABLE)
6069 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6070 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6071 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6072 	if (lc->requested_fc & PAUSE_TX)
6073 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6074 	if (lc->requested_fc & PAUSE_RX)
6075 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6076 	if (lc->requested_fec & FEC_RS)
6077 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6078 	if (lc->requested_fec & FEC_BASER_RS)
6079 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6080 #endif
6081 	if (!(sc->flags & IS_VF)) {
6082 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6083 		if (rc != 0) {
6084 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6085 			return (rc);
6086 		}
6087 	}
6088 
6089 	/*
6090 	 * An L1_CFG will almost always result in a link-change event if the
6091 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6092 	 * the notification is processed.  If the link is down then the actual
6093 	 * settings are meaningless.
6094 	 *
6095 	 * This takes care of the case where a change in the L1 settings may not
6096 	 * result in a notification.
6097 	 */
6098 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6099 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6100 
6101 	return (0);
6102 }
6103 
6104 #define FW_MAC_EXACT_CHUNK	7
6105 struct mcaddr_ctx {
6106 	if_t ifp;
6107 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6108 	uint64_t hash;
6109 	int i;
6110 	int del;
6111 	int rc;
6112 };
6113 
6114 static u_int
6115 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6116 {
6117 	struct mcaddr_ctx *ctx = arg;
6118 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6119 	struct port_info *pi = vi->pi;
6120 	struct adapter *sc = pi->adapter;
6121 
6122 	if (ctx->rc < 0)
6123 		return (0);
6124 
6125 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6126 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6127 	ctx->i++;
6128 
6129 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6130 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6131 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6132 		if (ctx->rc < 0) {
6133 			int j;
6134 
6135 			for (j = 0; j < ctx->i; j++) {
6136 				if_printf(ctx->ifp,
6137 				    "failed to add mc address"
6138 				    " %02x:%02x:%02x:"
6139 				    "%02x:%02x:%02x rc=%d\n",
6140 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6141 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6142 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6143 				    -ctx->rc);
6144 			}
6145 			return (0);
6146 		}
6147 		ctx->del = 0;
6148 		ctx->i = 0;
6149 	}
6150 
6151 	return (1);
6152 }
6153 
6154 /*
6155  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6156  * indicates which parameters should be programmed (the rest are left alone).
6157  */
6158 int
6159 update_mac_settings(if_t ifp, int flags)
6160 {
6161 	int rc = 0;
6162 	struct vi_info *vi = if_getsoftc(ifp);
6163 	struct port_info *pi = vi->pi;
6164 	struct adapter *sc = pi->adapter;
6165 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6166 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6167 
6168 	ASSERT_SYNCHRONIZED_OP(sc);
6169 	KASSERT(flags, ("%s: not told what to update.", __func__));
6170 
6171 	if (flags & XGMAC_MTU)
6172 		mtu = if_getmtu(ifp);
6173 
6174 	if (flags & XGMAC_PROMISC)
6175 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6176 
6177 	if (flags & XGMAC_ALLMULTI)
6178 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6179 
6180 	if (flags & XGMAC_VLANEX)
6181 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6182 
6183 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6184 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6185 		    allmulti, 1, vlanex, false);
6186 		if (rc) {
6187 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6188 			    rc);
6189 			return (rc);
6190 		}
6191 	}
6192 
6193 	if (flags & XGMAC_UCADDR) {
6194 		uint8_t ucaddr[ETHER_ADDR_LEN];
6195 
6196 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6197 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6198 		    ucaddr, true, &vi->smt_idx);
6199 		if (rc < 0) {
6200 			rc = -rc;
6201 			if_printf(ifp, "change_mac failed: %d\n", rc);
6202 			return (rc);
6203 		} else {
6204 			vi->xact_addr_filt = rc;
6205 			rc = 0;
6206 		}
6207 	}
6208 
6209 	if (flags & XGMAC_MCADDRS) {
6210 		struct epoch_tracker et;
6211 		struct mcaddr_ctx ctx;
6212 		int j;
6213 
6214 		ctx.ifp = ifp;
6215 		ctx.hash = 0;
6216 		ctx.i = 0;
6217 		ctx.del = 1;
6218 		ctx.rc = 0;
6219 		/*
6220 		 * Unlike other drivers, we accumulate list of pointers into
6221 		 * interface address lists and we need to keep it safe even
6222 		 * after if_foreach_llmaddr() returns, thus we must enter the
6223 		 * network epoch.
6224 		 */
6225 		NET_EPOCH_ENTER(et);
6226 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6227 		if (ctx.rc < 0) {
6228 			NET_EPOCH_EXIT(et);
6229 			rc = -ctx.rc;
6230 			return (rc);
6231 		}
6232 		if (ctx.i > 0) {
6233 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6234 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6235 			NET_EPOCH_EXIT(et);
6236 			if (rc < 0) {
6237 				rc = -rc;
6238 				for (j = 0; j < ctx.i; j++) {
6239 					if_printf(ifp,
6240 					    "failed to add mcast address"
6241 					    " %02x:%02x:%02x:"
6242 					    "%02x:%02x:%02x rc=%d\n",
6243 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6244 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6245 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6246 					    rc);
6247 				}
6248 				return (rc);
6249 			}
6250 			ctx.del = 0;
6251 		} else
6252 			NET_EPOCH_EXIT(et);
6253 
6254 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6255 		if (rc != 0)
6256 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6257 			    rc);
6258 		if (ctx.del == 0) {
6259 			/* We clobbered the VXLAN entry if there was one. */
6260 			pi->vxlan_tcam_entry = false;
6261 		}
6262 	}
6263 
6264 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6265 	    pi->vxlan_tcam_entry == false) {
6266 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6267 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6268 		    true);
6269 		if (rc < 0) {
6270 			rc = -rc;
6271 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6272 			    rc);
6273 		} else {
6274 			MPASS(rc == sc->rawf_base + pi->port_id);
6275 			rc = 0;
6276 			pi->vxlan_tcam_entry = true;
6277 		}
6278 	}
6279 
6280 	return (rc);
6281 }
6282 
6283 /*
6284  * {begin|end}_synchronized_op must be called from the same thread.
6285  */
6286 int
6287 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6288     char *wmesg)
6289 {
6290 	int rc, pri;
6291 
6292 #ifdef WITNESS
6293 	/* the caller thinks it's ok to sleep, but is it really? */
6294 	if (flags & SLEEP_OK)
6295 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6296 		    "begin_synchronized_op");
6297 #endif
6298 
6299 	if (INTR_OK)
6300 		pri = PCATCH;
6301 	else
6302 		pri = 0;
6303 
6304 	ADAPTER_LOCK(sc);
6305 	for (;;) {
6306 
6307 		if (vi && IS_DETACHING(vi)) {
6308 			rc = ENXIO;
6309 			goto done;
6310 		}
6311 
6312 		if (!IS_BUSY(sc)) {
6313 			rc = 0;
6314 			break;
6315 		}
6316 
6317 		if (!(flags & SLEEP_OK)) {
6318 			rc = EBUSY;
6319 			goto done;
6320 		}
6321 
6322 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6323 			rc = EINTR;
6324 			goto done;
6325 		}
6326 	}
6327 
6328 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6329 	SET_BUSY(sc);
6330 #ifdef INVARIANTS
6331 	sc->last_op = wmesg;
6332 	sc->last_op_thr = curthread;
6333 	sc->last_op_flags = flags;
6334 #endif
6335 
6336 done:
6337 	if (!(flags & HOLD_LOCK) || rc)
6338 		ADAPTER_UNLOCK(sc);
6339 
6340 	return (rc);
6341 }
6342 
6343 /*
6344  * Tell if_ioctl and if_init that the VI is going away.  This is
6345  * special variant of begin_synchronized_op and must be paired with a
6346  * call to end_vi_detach.
6347  */
6348 void
6349 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6350 {
6351 	ADAPTER_LOCK(sc);
6352 	SET_DETACHING(vi);
6353 	wakeup(&sc->flags);
6354 	while (IS_BUSY(sc))
6355 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6356 	SET_BUSY(sc);
6357 #ifdef INVARIANTS
6358 	sc->last_op = "t4detach";
6359 	sc->last_op_thr = curthread;
6360 	sc->last_op_flags = 0;
6361 #endif
6362 	ADAPTER_UNLOCK(sc);
6363 }
6364 
6365 void
6366 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6367 {
6368 	ADAPTER_LOCK(sc);
6369 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6370 	CLR_BUSY(sc);
6371 	CLR_DETACHING(vi);
6372 	wakeup(&sc->flags);
6373 	ADAPTER_UNLOCK(sc);
6374 }
6375 
6376 /*
6377  * {begin|end}_synchronized_op must be called from the same thread.
6378  */
6379 void
6380 end_synchronized_op(struct adapter *sc, int flags)
6381 {
6382 
6383 	if (flags & LOCK_HELD)
6384 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6385 	else
6386 		ADAPTER_LOCK(sc);
6387 
6388 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6389 	CLR_BUSY(sc);
6390 	wakeup(&sc->flags);
6391 	ADAPTER_UNLOCK(sc);
6392 }
6393 
6394 static int
6395 cxgbe_init_synchronized(struct vi_info *vi)
6396 {
6397 	struct port_info *pi = vi->pi;
6398 	struct adapter *sc = pi->adapter;
6399 	if_t ifp = vi->ifp;
6400 	int rc = 0, i;
6401 	struct sge_txq *txq;
6402 
6403 	ASSERT_SYNCHRONIZED_OP(sc);
6404 
6405 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6406 		return (0);	/* already running */
6407 
6408 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6409 		return (rc);	/* error message displayed already */
6410 
6411 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6412 		return (rc); /* error message displayed already */
6413 
6414 	rc = update_mac_settings(ifp, XGMAC_ALL);
6415 	if (rc)
6416 		goto done;	/* error message displayed already */
6417 
6418 	PORT_LOCK(pi);
6419 	if (pi->up_vis == 0) {
6420 		t4_update_port_info(pi);
6421 		fixup_link_config(pi);
6422 		build_medialist(pi);
6423 		apply_link_config(pi);
6424 	}
6425 
6426 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6427 	if (rc != 0) {
6428 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6429 		PORT_UNLOCK(pi);
6430 		goto done;
6431 	}
6432 
6433 	/*
6434 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6435 	 * if this changes.
6436 	 */
6437 
6438 	for_each_txq(vi, i, txq) {
6439 		TXQ_LOCK(txq);
6440 		txq->eq.flags |= EQ_ENABLED;
6441 		TXQ_UNLOCK(txq);
6442 	}
6443 
6444 	/*
6445 	 * The first iq of the first port to come up is used for tracing.
6446 	 */
6447 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6448 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6449 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6450 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6451 		    V_QUEUENUMBER(sc->traceq));
6452 		pi->flags |= HAS_TRACEQ;
6453 	}
6454 
6455 	/* all ok */
6456 	pi->up_vis++;
6457 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6458 	if (pi->link_cfg.link_ok)
6459 		t4_os_link_changed(pi);
6460 	PORT_UNLOCK(pi);
6461 
6462 	mtx_lock(&vi->tick_mtx);
6463 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6464 		callout_reset(&vi->tick, hz, vi_tick, vi);
6465 	else
6466 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6467 	mtx_unlock(&vi->tick_mtx);
6468 done:
6469 	if (rc != 0)
6470 		cxgbe_uninit_synchronized(vi);
6471 
6472 	return (rc);
6473 }
6474 
6475 /*
6476  * Idempotent.
6477  */
6478 static int
6479 cxgbe_uninit_synchronized(struct vi_info *vi)
6480 {
6481 	struct port_info *pi = vi->pi;
6482 	struct adapter *sc = pi->adapter;
6483 	if_t ifp = vi->ifp;
6484 	int rc, i;
6485 	struct sge_txq *txq;
6486 
6487 	ASSERT_SYNCHRONIZED_OP(sc);
6488 
6489 	if (!(vi->flags & VI_INIT_DONE)) {
6490 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6491 			KASSERT(0, ("uninited VI is running"));
6492 			if_printf(ifp, "uninited VI with running ifnet.  "
6493 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6494 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6495 			    if_getdrvflags(ifp));
6496 		}
6497 		return (0);
6498 	}
6499 
6500 	/*
6501 	 * Disable the VI so that all its data in either direction is discarded
6502 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6503 	 * tick) intact as the TP can deliver negative advice or data that it's
6504 	 * holding in its RAM (for an offloaded connection) even after the VI is
6505 	 * disabled.
6506 	 */
6507 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6508 	if (rc) {
6509 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6510 		return (rc);
6511 	}
6512 
6513 	for_each_txq(vi, i, txq) {
6514 		TXQ_LOCK(txq);
6515 		txq->eq.flags &= ~EQ_ENABLED;
6516 		TXQ_UNLOCK(txq);
6517 	}
6518 
6519 	mtx_lock(&vi->tick_mtx);
6520 	callout_stop(&vi->tick);
6521 	mtx_unlock(&vi->tick_mtx);
6522 
6523 	PORT_LOCK(pi);
6524 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6525 		PORT_UNLOCK(pi);
6526 		return (0);
6527 	}
6528 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6529 	pi->up_vis--;
6530 	if (pi->up_vis > 0) {
6531 		PORT_UNLOCK(pi);
6532 		return (0);
6533 	}
6534 
6535 	pi->link_cfg.link_ok = false;
6536 	pi->link_cfg.speed = 0;
6537 	pi->link_cfg.link_down_rc = 255;
6538 	t4_os_link_changed(pi);
6539 	PORT_UNLOCK(pi);
6540 
6541 	return (0);
6542 }
6543 
6544 /*
6545  * It is ok for this function to fail midway and return right away.  t4_detach
6546  * will walk the entire sc->irq list and clean up whatever is valid.
6547  */
6548 int
6549 t4_setup_intr_handlers(struct adapter *sc)
6550 {
6551 	int rc, rid, p, q, v;
6552 	char s[8];
6553 	struct irq *irq;
6554 	struct port_info *pi;
6555 	struct vi_info *vi;
6556 	struct sge *sge = &sc->sge;
6557 	struct sge_rxq *rxq;
6558 #ifdef TCP_OFFLOAD
6559 	struct sge_ofld_rxq *ofld_rxq;
6560 #endif
6561 #ifdef DEV_NETMAP
6562 	struct sge_nm_rxq *nm_rxq;
6563 #endif
6564 #ifdef RSS
6565 	int nbuckets = rss_getnumbuckets();
6566 #endif
6567 
6568 	/*
6569 	 * Setup interrupts.
6570 	 */
6571 	irq = &sc->irq[0];
6572 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6573 	if (forwarding_intr_to_fwq(sc))
6574 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6575 
6576 	/* Multiple interrupts. */
6577 	if (sc->flags & IS_VF)
6578 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6579 		    ("%s: too few intr.", __func__));
6580 	else
6581 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6582 		    ("%s: too few intr.", __func__));
6583 
6584 	/* The first one is always error intr on PFs */
6585 	if (!(sc->flags & IS_VF)) {
6586 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6587 		if (rc != 0)
6588 			return (rc);
6589 		irq++;
6590 		rid++;
6591 	}
6592 
6593 	/* The second one is always the firmware event queue (first on VFs) */
6594 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6595 	if (rc != 0)
6596 		return (rc);
6597 	irq++;
6598 	rid++;
6599 
6600 	for_each_port(sc, p) {
6601 		pi = sc->port[p];
6602 		for_each_vi(pi, v, vi) {
6603 			vi->first_intr = rid - 1;
6604 
6605 			if (vi->nnmrxq > 0) {
6606 				int n = max(vi->nrxq, vi->nnmrxq);
6607 
6608 				rxq = &sge->rxq[vi->first_rxq];
6609 #ifdef DEV_NETMAP
6610 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6611 #endif
6612 				for (q = 0; q < n; q++) {
6613 					snprintf(s, sizeof(s), "%x%c%x", p,
6614 					    'a' + v, q);
6615 					if (q < vi->nrxq)
6616 						irq->rxq = rxq++;
6617 #ifdef DEV_NETMAP
6618 					if (q < vi->nnmrxq)
6619 						irq->nm_rxq = nm_rxq++;
6620 
6621 					if (irq->nm_rxq != NULL &&
6622 					    irq->rxq == NULL) {
6623 						/* Netmap rx only */
6624 						rc = t4_alloc_irq(sc, irq, rid,
6625 						    t4_nm_intr, irq->nm_rxq, s);
6626 					}
6627 					if (irq->nm_rxq != NULL &&
6628 					    irq->rxq != NULL) {
6629 						/* NIC and Netmap rx */
6630 						rc = t4_alloc_irq(sc, irq, rid,
6631 						    t4_vi_intr, irq, s);
6632 					}
6633 #endif
6634 					if (irq->rxq != NULL &&
6635 					    irq->nm_rxq == NULL) {
6636 						/* NIC rx only */
6637 						rc = t4_alloc_irq(sc, irq, rid,
6638 						    t4_intr, irq->rxq, s);
6639 					}
6640 					if (rc != 0)
6641 						return (rc);
6642 #ifdef RSS
6643 					if (q < vi->nrxq) {
6644 						bus_bind_intr(sc->dev, irq->res,
6645 						    rss_getcpu(q % nbuckets));
6646 					}
6647 #endif
6648 					irq++;
6649 					rid++;
6650 					vi->nintr++;
6651 				}
6652 			} else {
6653 				for_each_rxq(vi, q, rxq) {
6654 					snprintf(s, sizeof(s), "%x%c%x", p,
6655 					    'a' + v, q);
6656 					rc = t4_alloc_irq(sc, irq, rid,
6657 					    t4_intr, rxq, s);
6658 					if (rc != 0)
6659 						return (rc);
6660 #ifdef RSS
6661 					bus_bind_intr(sc->dev, irq->res,
6662 					    rss_getcpu(q % nbuckets));
6663 #endif
6664 					irq++;
6665 					rid++;
6666 					vi->nintr++;
6667 				}
6668 			}
6669 #ifdef TCP_OFFLOAD
6670 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6671 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6672 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6673 				    ofld_rxq, s);
6674 				if (rc != 0)
6675 					return (rc);
6676 				irq++;
6677 				rid++;
6678 				vi->nintr++;
6679 			}
6680 #endif
6681 		}
6682 	}
6683 	MPASS(irq == &sc->irq[sc->intr_count]);
6684 
6685 	return (0);
6686 }
6687 
6688 static void
6689 write_global_rss_key(struct adapter *sc)
6690 {
6691 #ifdef RSS
6692 	int i;
6693 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6694 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6695 
6696 	CTASSERT(RSS_KEYSIZE == 40);
6697 
6698 	rss_getkey((void *)&raw_rss_key[0]);
6699 	for (i = 0; i < nitems(rss_key); i++) {
6700 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6701 	}
6702 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6703 #endif
6704 }
6705 
6706 /*
6707  * Idempotent.
6708  */
6709 static int
6710 adapter_full_init(struct adapter *sc)
6711 {
6712 	int rc, i;
6713 
6714 	ASSERT_SYNCHRONIZED_OP(sc);
6715 
6716 	/*
6717 	 * queues that belong to the adapter (not any particular port).
6718 	 */
6719 	rc = t4_setup_adapter_queues(sc);
6720 	if (rc != 0)
6721 		return (rc);
6722 
6723 	MPASS(sc->params.nports <= nitems(sc->tq));
6724 	for (i = 0; i < sc->params.nports; i++) {
6725 		if (sc->tq[i] != NULL)
6726 			continue;
6727 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6728 		    taskqueue_thread_enqueue, &sc->tq[i]);
6729 		if (sc->tq[i] == NULL) {
6730 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6731 			return (ENOMEM);
6732 		}
6733 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6734 		    device_get_nameunit(sc->dev), i);
6735 	}
6736 
6737 	if (!(sc->flags & IS_VF)) {
6738 		write_global_rss_key(sc);
6739 		t4_intr_enable(sc);
6740 	}
6741 	return (0);
6742 }
6743 
6744 int
6745 adapter_init(struct adapter *sc)
6746 {
6747 	int rc;
6748 
6749 	ASSERT_SYNCHRONIZED_OP(sc);
6750 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6751 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6752 	    ("%s: FULL_INIT_DONE already", __func__));
6753 
6754 	rc = adapter_full_init(sc);
6755 	if (rc != 0)
6756 		adapter_full_uninit(sc);
6757 	else
6758 		sc->flags |= FULL_INIT_DONE;
6759 
6760 	return (rc);
6761 }
6762 
6763 /*
6764  * Idempotent.
6765  */
6766 static void
6767 adapter_full_uninit(struct adapter *sc)
6768 {
6769 	int i;
6770 
6771 	t4_teardown_adapter_queues(sc);
6772 
6773 	for (i = 0; i < nitems(sc->tq); i++) {
6774 		if (sc->tq[i] == NULL)
6775 			continue;
6776 		taskqueue_free(sc->tq[i]);
6777 		sc->tq[i] = NULL;
6778 	}
6779 
6780 	sc->flags &= ~FULL_INIT_DONE;
6781 }
6782 
6783 #ifdef RSS
6784 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6785     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6786     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6787     RSS_HASHTYPE_RSS_UDP_IPV6)
6788 
6789 /* Translates kernel hash types to hardware. */
6790 static int
6791 hashconfig_to_hashen(int hashconfig)
6792 {
6793 	int hashen = 0;
6794 
6795 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6796 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6797 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6798 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6799 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6800 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6801 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6802 	}
6803 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6804 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6805 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6806 	}
6807 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6808 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6809 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6810 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6811 
6812 	return (hashen);
6813 }
6814 
6815 /* Translates hardware hash types to kernel. */
6816 static int
6817 hashen_to_hashconfig(int hashen)
6818 {
6819 	int hashconfig = 0;
6820 
6821 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6822 		/*
6823 		 * If UDP hashing was enabled it must have been enabled for
6824 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6825 		 * enabling any 4-tuple hash is nonsense configuration.
6826 		 */
6827 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6828 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6829 
6830 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6831 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6832 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6833 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6834 	}
6835 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6836 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6837 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6838 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6839 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6840 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6841 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6842 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6843 
6844 	return (hashconfig);
6845 }
6846 #endif
6847 
6848 /*
6849  * Idempotent.
6850  */
6851 static int
6852 vi_full_init(struct vi_info *vi)
6853 {
6854 	struct adapter *sc = vi->adapter;
6855 	struct sge_rxq *rxq;
6856 	int rc, i, j;
6857 #ifdef RSS
6858 	int nbuckets = rss_getnumbuckets();
6859 	int hashconfig = rss_gethashconfig();
6860 	int extra;
6861 #endif
6862 
6863 	ASSERT_SYNCHRONIZED_OP(sc);
6864 
6865 	/*
6866 	 * Allocate tx/rx/fl queues for this VI.
6867 	 */
6868 	rc = t4_setup_vi_queues(vi);
6869 	if (rc != 0)
6870 		return (rc);
6871 
6872 	/*
6873 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6874 	 */
6875 	if (vi->nrxq > vi->rss_size) {
6876 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6877 		    "some queues will never receive traffic.\n", vi->nrxq,
6878 		    vi->rss_size);
6879 	} else if (vi->rss_size % vi->nrxq) {
6880 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6881 		    "expect uneven traffic distribution.\n", vi->nrxq,
6882 		    vi->rss_size);
6883 	}
6884 #ifdef RSS
6885 	if (vi->nrxq != nbuckets) {
6886 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6887 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6888 	}
6889 #endif
6890 	if (vi->rss == NULL)
6891 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6892 		    M_ZERO | M_WAITOK);
6893 	for (i = 0; i < vi->rss_size;) {
6894 #ifdef RSS
6895 		j = rss_get_indirection_to_bucket(i);
6896 		j %= vi->nrxq;
6897 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6898 		vi->rss[i++] = rxq->iq.abs_id;
6899 #else
6900 		for_each_rxq(vi, j, rxq) {
6901 			vi->rss[i++] = rxq->iq.abs_id;
6902 			if (i == vi->rss_size)
6903 				break;
6904 		}
6905 #endif
6906 	}
6907 
6908 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6909 	    vi->rss, vi->rss_size);
6910 	if (rc != 0) {
6911 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6912 		return (rc);
6913 	}
6914 
6915 #ifdef RSS
6916 	vi->hashen = hashconfig_to_hashen(hashconfig);
6917 
6918 	/*
6919 	 * We may have had to enable some hashes even though the global config
6920 	 * wants them disabled.  This is a potential problem that must be
6921 	 * reported to the user.
6922 	 */
6923 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6924 
6925 	/*
6926 	 * If we consider only the supported hash types, then the enabled hashes
6927 	 * are a superset of the requested hashes.  In other words, there cannot
6928 	 * be any supported hash that was requested but not enabled, but there
6929 	 * can be hashes that were not requested but had to be enabled.
6930 	 */
6931 	extra &= SUPPORTED_RSS_HASHTYPES;
6932 	MPASS((extra & hashconfig) == 0);
6933 
6934 	if (extra) {
6935 		CH_ALERT(vi,
6936 		    "global RSS config (0x%x) cannot be accommodated.\n",
6937 		    hashconfig);
6938 	}
6939 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6940 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6941 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6942 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6943 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6944 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6945 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6946 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6947 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6948 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6949 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6950 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6951 #else
6952 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6953 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6954 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6955 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6956 #endif
6957 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6958 	    0, 0);
6959 	if (rc != 0) {
6960 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6961 		return (rc);
6962 	}
6963 
6964 	return (0);
6965 }
6966 
6967 int
6968 vi_init(struct vi_info *vi)
6969 {
6970 	int rc;
6971 
6972 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6973 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6974 	    ("%s: VI_INIT_DONE already", __func__));
6975 
6976 	rc = vi_full_init(vi);
6977 	if (rc != 0)
6978 		vi_full_uninit(vi);
6979 	else
6980 		vi->flags |= VI_INIT_DONE;
6981 
6982 	return (rc);
6983 }
6984 
6985 /*
6986  * Idempotent.
6987  */
6988 static void
6989 vi_full_uninit(struct vi_info *vi)
6990 {
6991 
6992 	if (vi->flags & VI_INIT_DONE) {
6993 		quiesce_vi(vi);
6994 		free(vi->rss, M_CXGBE);
6995 		free(vi->nm_rss, M_CXGBE);
6996 	}
6997 
6998 	t4_teardown_vi_queues(vi);
6999 	vi->flags &= ~VI_INIT_DONE;
7000 }
7001 
7002 static void
7003 quiesce_txq(struct sge_txq *txq)
7004 {
7005 	struct sge_eq *eq = &txq->eq;
7006 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7007 
7008 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7009 	MPASS(!(eq->flags & EQ_ENABLED));
7010 
7011 	/* Wait for the mp_ring to empty. */
7012 	while (!mp_ring_is_idle(txq->r)) {
7013 		mp_ring_check_drainage(txq->r, 4096);
7014 		pause("rquiesce", 1);
7015 	}
7016 	MPASS(txq->txp.npkt == 0);
7017 
7018 	if (eq->flags & EQ_HW_ALLOCATED) {
7019 		/*
7020 		 * Hardware is alive and working normally.  Wait for it to
7021 		 * finish and then wait for the driver to catch up and reclaim
7022 		 * all descriptors.
7023 		 */
7024 		while (spg->cidx != htobe16(eq->pidx))
7025 			pause("equiesce", 1);
7026 		while (eq->cidx != eq->pidx)
7027 			pause("dquiesce", 1);
7028 	} else {
7029 		/*
7030 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7031 		 * descriptors directly.
7032 		 */
7033 		TXQ_LOCK(txq);
7034 		while (eq->cidx != eq->pidx) {
7035 			struct mbuf *m, *nextpkt;
7036 			struct tx_sdesc *txsd;
7037 
7038 			txsd = &txq->sdesc[eq->cidx];
7039 			for (m = txsd->m; m != NULL; m = nextpkt) {
7040 				nextpkt = m->m_nextpkt;
7041 				m->m_nextpkt = NULL;
7042 				m_freem(m);
7043 			}
7044 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7045 		}
7046 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7047 		TXQ_UNLOCK(txq);
7048 	}
7049 }
7050 
7051 static void
7052 quiesce_wrq(struct sge_wrq *wrq)
7053 {
7054 	struct wrqe *wr;
7055 
7056 	TXQ_LOCK(wrq);
7057 	while ((wr = STAILQ_FIRST(&wrq->wr_list)) != NULL) {
7058 		STAILQ_REMOVE_HEAD(&wrq->wr_list, link);
7059 #ifdef INVARIANTS
7060 		wrq->nwr_pending--;
7061 		wrq->ndesc_needed -= howmany(wr->wr_len, EQ_ESIZE);
7062 #endif
7063 		free(wr, M_CXGBE);
7064 	}
7065 	MPASS(wrq->nwr_pending == 0);
7066 	MPASS(wrq->ndesc_needed == 0);
7067 	wrq->nwr_pending = 0;
7068 	wrq->ndesc_needed = 0;
7069 	TXQ_UNLOCK(wrq);
7070 }
7071 
7072 static void
7073 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7074 {
7075 	/* Synchronize with the interrupt handler */
7076 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7077 		pause("iqfree", 1);
7078 
7079 	if (fl != NULL) {
7080 		MPASS(iq->flags & IQ_HAS_FL);
7081 
7082 		mtx_lock(&sc->sfl_lock);
7083 		FL_LOCK(fl);
7084 		fl->flags |= FL_DOOMED;
7085 		FL_UNLOCK(fl);
7086 		callout_stop(&sc->sfl_callout);
7087 		mtx_unlock(&sc->sfl_lock);
7088 
7089 		KASSERT((fl->flags & FL_STARVING) == 0,
7090 		    ("%s: still starving", __func__));
7091 
7092 		/* Release all buffers if hardware is no longer available. */
7093 		if (!(iq->flags & IQ_HW_ALLOCATED))
7094 			free_fl_buffers(sc, fl);
7095 	}
7096 }
7097 
7098 /*
7099  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7100  * that no new work is being enqueued by the hardware or the driver.  That part
7101  * should be arranged before calling this function.
7102  */
7103 static void
7104 quiesce_vi(struct vi_info *vi)
7105 {
7106 	int i;
7107 	struct adapter *sc = vi->adapter;
7108 	struct sge_rxq *rxq;
7109 	struct sge_txq *txq;
7110 #ifdef TCP_OFFLOAD
7111 	struct sge_ofld_rxq *ofld_rxq;
7112 #endif
7113 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7114 	struct sge_ofld_txq *ofld_txq;
7115 #endif
7116 
7117 	if (!(vi->flags & VI_INIT_DONE))
7118 		return;
7119 
7120 	for_each_txq(vi, i, txq) {
7121 		quiesce_txq(txq);
7122 	}
7123 
7124 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7125 	for_each_ofld_txq(vi, i, ofld_txq) {
7126 		quiesce_wrq(&ofld_txq->wrq);
7127 	}
7128 #endif
7129 
7130 	for_each_rxq(vi, i, rxq) {
7131 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7132 	}
7133 
7134 #ifdef TCP_OFFLOAD
7135 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7136 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7137 	}
7138 #endif
7139 }
7140 
7141 static int
7142 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7143     driver_intr_t *handler, void *arg, char *name)
7144 {
7145 	int rc;
7146 
7147 	irq->rid = rid;
7148 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7149 	    RF_SHAREABLE | RF_ACTIVE);
7150 	if (irq->res == NULL) {
7151 		device_printf(sc->dev,
7152 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7153 		return (ENOMEM);
7154 	}
7155 
7156 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7157 	    NULL, handler, arg, &irq->tag);
7158 	if (rc != 0) {
7159 		device_printf(sc->dev,
7160 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7161 		    rid, name, rc);
7162 	} else if (name)
7163 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7164 
7165 	return (rc);
7166 }
7167 
7168 static int
7169 t4_free_irq(struct adapter *sc, struct irq *irq)
7170 {
7171 	if (irq->tag)
7172 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7173 	if (irq->res)
7174 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7175 
7176 	bzero(irq, sizeof(*irq));
7177 
7178 	return (0);
7179 }
7180 
7181 static void
7182 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7183 {
7184 
7185 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7186 	t4_get_regs(sc, buf, regs->len);
7187 }
7188 
7189 #define	A_PL_INDIR_CMD	0x1f8
7190 
7191 #define	S_PL_AUTOINC	31
7192 #define	M_PL_AUTOINC	0x1U
7193 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7194 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7195 
7196 #define	S_PL_VFID	20
7197 #define	M_PL_VFID	0xffU
7198 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7199 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7200 
7201 #define	S_PL_ADDR	0
7202 #define	M_PL_ADDR	0xfffffU
7203 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7204 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7205 
7206 #define	A_PL_INDIR_DATA	0x1fc
7207 
7208 static uint64_t
7209 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7210 {
7211 	u32 stats[2];
7212 
7213 	if (sc->flags & IS_VF) {
7214 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7215 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7216 	} else {
7217 		mtx_assert(&sc->reg_lock, MA_OWNED);
7218 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7219 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7220 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7221 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7222 	}
7223 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7224 }
7225 
7226 static void
7227 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7228 {
7229 
7230 #define GET_STAT(name) \
7231 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7232 
7233 	if (!(sc->flags & IS_VF))
7234 		mtx_lock(&sc->reg_lock);
7235 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7236 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7237 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7238 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7239 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7240 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7241 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7242 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7243 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7244 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7245 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7246 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7247 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7248 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7249 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7250 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7251 	if (!(sc->flags & IS_VF))
7252 		mtx_unlock(&sc->reg_lock);
7253 
7254 #undef GET_STAT
7255 }
7256 
7257 static void
7258 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7259 {
7260 	int reg;
7261 
7262 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7263 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7264 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7265 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7266 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7267 }
7268 
7269 static void
7270 vi_refresh_stats(struct vi_info *vi)
7271 {
7272 	struct timeval tv;
7273 	const struct timeval interval = {0, 250000};	/* 250ms */
7274 
7275 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7276 
7277 	if (vi->flags & VI_SKIP_STATS)
7278 		return;
7279 
7280 	getmicrotime(&tv);
7281 	timevalsub(&tv, &interval);
7282 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7283 		return;
7284 
7285 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7286 	getmicrotime(&vi->last_refreshed);
7287 }
7288 
7289 static void
7290 cxgbe_refresh_stats(struct vi_info *vi)
7291 {
7292 	u_int i, v, tnl_cong_drops, chan_map;
7293 	struct timeval tv;
7294 	const struct timeval interval = {0, 250000};	/* 250ms */
7295 	struct port_info *pi;
7296 	struct adapter *sc;
7297 
7298 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7299 
7300 	if (vi->flags & VI_SKIP_STATS)
7301 		return;
7302 
7303 	getmicrotime(&tv);
7304 	timevalsub(&tv, &interval);
7305 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7306 		return;
7307 
7308 	pi = vi->pi;
7309 	sc = vi->adapter;
7310 	tnl_cong_drops = 0;
7311 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7312 	chan_map = pi->rx_e_chan_map;
7313 	while (chan_map) {
7314 		i = ffs(chan_map) - 1;
7315 		mtx_lock(&sc->reg_lock);
7316 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7317 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7318 		mtx_unlock(&sc->reg_lock);
7319 		tnl_cong_drops += v;
7320 		chan_map &= ~(1 << i);
7321 	}
7322 	pi->tnl_cong_drops = tnl_cong_drops;
7323 	getmicrotime(&vi->last_refreshed);
7324 }
7325 
7326 static void
7327 cxgbe_tick(void *arg)
7328 {
7329 	struct vi_info *vi = arg;
7330 
7331 	MPASS(IS_MAIN_VI(vi));
7332 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7333 
7334 	cxgbe_refresh_stats(vi);
7335 	callout_schedule(&vi->tick, hz);
7336 }
7337 
7338 static void
7339 vi_tick(void *arg)
7340 {
7341 	struct vi_info *vi = arg;
7342 
7343 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7344 
7345 	vi_refresh_stats(vi);
7346 	callout_schedule(&vi->tick, hz);
7347 }
7348 
7349 /*
7350  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7351  */
7352 static char *caps_decoder[] = {
7353 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7354 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7355 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7356 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7357 	    "\006HASHFILTER\007ETHOFLD",
7358 	"\20\001TOE",					/* 4: TOE */
7359 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7360 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7361 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7362 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7363 	    "\007T10DIF"
7364 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7365 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7366 	    "\004TLS_HW",
7367 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7368 		    "\004PO_INITIATOR\005PO_TARGET",
7369 };
7370 
7371 void
7372 t4_sysctls(struct adapter *sc)
7373 {
7374 	struct sysctl_ctx_list *ctx = &sc->ctx;
7375 	struct sysctl_oid *oid;
7376 	struct sysctl_oid_list *children, *c0;
7377 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7378 
7379 	/*
7380 	 * dev.t4nex.X.
7381 	 */
7382 	oid = device_get_sysctl_tree(sc->dev);
7383 	c0 = children = SYSCTL_CHILDREN(oid);
7384 
7385 	sc->sc_do_rxcopy = 1;
7386 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7387 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7388 
7389 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7390 	    sc->params.nports, "# of ports");
7391 
7392 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7393 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7394 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7395 	    "available doorbells");
7396 
7397 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7398 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7399 
7400 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7401 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7402 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7403 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7404 
7405 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7406 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7407 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7408 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7409 
7410 	t4_sge_sysctls(sc, ctx, children);
7411 
7412 	sc->lro_timeout = 100;
7413 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7414 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7415 
7416 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7417 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7418 
7419 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7420 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7421 
7422 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7423 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7424 
7425 	if (sc->flags & IS_VF)
7426 		return;
7427 
7428 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7429 	    NULL, chip_rev(sc), "chip hardware revision");
7430 
7431 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7432 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7433 
7434 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7435 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7436 
7437 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7438 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7439 
7440 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7441 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7442 
7443 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7444 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7445 
7446 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7447 	    sc->er_version, 0, "expansion ROM version");
7448 
7449 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7450 	    sc->bs_version, 0, "bootstrap firmware version");
7451 
7452 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7453 	    NULL, sc->params.scfg_vers, "serial config version");
7454 
7455 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7456 	    NULL, sc->params.vpd_vers, "VPD version");
7457 
7458 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7459 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7460 
7461 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7462 	    sc->cfcsum, "config file checksum");
7463 
7464 #define SYSCTL_CAP(name, n, text) \
7465 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7466 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7467 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7468 	    "available " text " capabilities")
7469 
7470 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7471 	SYSCTL_CAP(linkcaps, 1, "link");
7472 	SYSCTL_CAP(switchcaps, 2, "switch");
7473 	SYSCTL_CAP(niccaps, 3, "NIC");
7474 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7475 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7476 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7477 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7478 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7479 #undef SYSCTL_CAP
7480 
7481 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7482 	    NULL, sc->tids.nftids, "number of filters");
7483 
7484 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7485 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7486 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7487 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7488 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7489 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7490 
7491 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7492 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7493 	    sysctl_loadavg, "A",
7494 	    "microprocessor load averages (debug firmwares only)");
7495 
7496 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7497 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7498 	    "I", "core Vdd (in mV)");
7499 
7500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7501 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7502 	    sysctl_cpus, "A", "local CPUs");
7503 
7504 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7505 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7506 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7507 
7508 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7509 	    &sc->swintr, 0, "software triggered interrupts");
7510 
7511 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7512 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7513 	    "1 = reset adapter, 0 = zero reset counter");
7514 
7515 	/*
7516 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7517 	 */
7518 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7519 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7520 	    "logs and miscellaneous information");
7521 	children = SYSCTL_CHILDREN(oid);
7522 
7523 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7524 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7525 	    sysctl_cctrl, "A", "congestion control");
7526 
7527 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7528 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7529 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7530 
7531 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7532 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7533 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7534 
7535 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7536 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7537 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7538 
7539 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7540 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7541 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7542 
7543 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7544 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7545 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7546 
7547 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7548 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7549 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7550 
7551 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7552 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7553 	    sysctl_cim_la, "A", "CIM logic analyzer");
7554 
7555 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7556 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7557 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7558 
7559 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7560 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7561 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7562 
7563 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7564 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7565 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7566 
7567 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7568 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7569 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7570 
7571 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7572 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7573 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7574 
7575 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7576 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7577 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7578 
7579 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7580 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7581 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7582 
7583 	if (chip_id(sc) > CHELSIO_T4) {
7584 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7585 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7586 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7587 		    "CIM OBQ 6 (SGE0-RX)");
7588 
7589 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7590 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7591 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7592 		    "CIM OBQ 7 (SGE1-RX)");
7593 	}
7594 
7595 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7596 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7597 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7598 
7599 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7600 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7601 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7602 
7603 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7604 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7605 	    sysctl_cpl_stats, "A", "CPL statistics");
7606 
7607 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7608 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7609 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7610 
7611 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7612 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7613 	    sysctl_tid_stats, "A", "tid stats");
7614 
7615 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7616 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7617 	    sysctl_devlog, "A", "firmware's device log");
7618 
7619 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7620 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7621 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7622 
7623 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7624 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7625 	    sysctl_hw_sched, "A", "hardware scheduler ");
7626 
7627 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7628 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7629 	    sysctl_l2t, "A", "hardware L2 table");
7630 
7631 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7632 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7633 	    sysctl_smt, "A", "hardware source MAC table");
7634 
7635 #ifdef INET6
7636 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7637 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7638 	    sysctl_clip, "A", "active CLIP table entries");
7639 #endif
7640 
7641 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7642 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7643 	    sysctl_lb_stats, "A", "loopback statistics");
7644 
7645 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7646 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7647 	    sysctl_meminfo, "A", "memory regions");
7648 
7649 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7650 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7651 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7652 	    "A", "MPS TCAM entries");
7653 
7654 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7655 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7656 	    sysctl_path_mtus, "A", "path MTUs");
7657 
7658 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7659 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7660 	    sysctl_pm_stats, "A", "PM statistics");
7661 
7662 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7663 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7664 	    sysctl_rdma_stats, "A", "RDMA statistics");
7665 
7666 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7667 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7668 	    sysctl_tcp_stats, "A", "TCP statistics");
7669 
7670 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7671 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7672 	    sysctl_tids, "A", "TID information");
7673 
7674 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7675 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7676 	    sysctl_tp_err_stats, "A", "TP error statistics");
7677 
7678 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7679 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7680 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7681 
7682 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7683 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7684 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7685 
7686 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7687 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7688 	    sysctl_tp_la, "A", "TP logic analyzer");
7689 
7690 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7691 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7692 	    sysctl_tx_rate, "A", "Tx rate");
7693 
7694 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7695 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7696 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7697 
7698 	if (chip_id(sc) >= CHELSIO_T5) {
7699 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7700 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7701 		    sysctl_wcwr_stats, "A", "write combined work requests");
7702 	}
7703 
7704 #ifdef KERN_TLS
7705 	if (is_ktls(sc)) {
7706 		/*
7707 		 * dev.t4nex.0.tls.
7708 		 */
7709 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7710 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7711 		children = SYSCTL_CHILDREN(oid);
7712 
7713 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7714 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7715 		    "keys in work requests (1) or attempt to store TLS keys "
7716 		    "in card memory.");
7717 
7718 		if (is_t6(sc))
7719 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7720 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7721 			    "combine TCB field updates with TLS record work "
7722 			    "requests.");
7723 	}
7724 #endif
7725 
7726 #ifdef TCP_OFFLOAD
7727 	if (is_offload(sc)) {
7728 		int i;
7729 		char s[4];
7730 
7731 		/*
7732 		 * dev.t4nex.X.toe.
7733 		 */
7734 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7735 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7736 		children = SYSCTL_CHILDREN(oid);
7737 
7738 		sc->tt.cong_algorithm = -1;
7739 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7740 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7741 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7742 		    "3 = highspeed)");
7743 
7744 		sc->tt.sndbuf = -1;
7745 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7746 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7747 
7748 		sc->tt.ddp = 0;
7749 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7750 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7751 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7752 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7753 
7754 		sc->tt.rx_coalesce = -1;
7755 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7756 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7757 
7758 		sc->tt.tls = 0;
7759 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7760 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7761 		    "Inline TLS allowed");
7762 
7763 		sc->tt.tx_align = -1;
7764 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7765 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7766 
7767 		sc->tt.tx_zcopy = 0;
7768 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7769 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7770 		    "Enable zero-copy aio_write(2)");
7771 
7772 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7773 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7774 		    "cop_managed_offloading", CTLFLAG_RW,
7775 		    &sc->tt.cop_managed_offloading, 0,
7776 		    "COP (Connection Offload Policy) controls all TOE offload");
7777 
7778 		sc->tt.autorcvbuf_inc = 16 * 1024;
7779 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7780 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7781 		    "autorcvbuf increment");
7782 
7783 		sc->tt.update_hc_on_pmtu_change = 1;
7784 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7785 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7786 		    &sc->tt.update_hc_on_pmtu_change, 0,
7787 		    "Update hostcache entry if the PMTU changes");
7788 
7789 		sc->tt.iso = 1;
7790 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7791 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7792 
7793 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7794 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7795 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7796 
7797 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7798 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7799 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7800 
7801 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7802 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7803 		    sysctl_tp_tick, "A", "DACK tick (us)");
7804 
7805 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7806 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7807 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7808 
7809 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7810 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7811 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7812 		    "Minimum retransmit interval (us)");
7813 
7814 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7815 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7816 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7817 		    "Maximum retransmit interval (us)");
7818 
7819 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7820 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7821 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7822 		    "Persist timer min (us)");
7823 
7824 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7825 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7826 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7827 		    "Persist timer max (us)");
7828 
7829 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7830 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7831 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7832 		    "Keepalive idle timer (us)");
7833 
7834 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7835 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7836 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7837 		    "Keepalive interval timer (us)");
7838 
7839 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7840 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7841 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7842 
7843 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7844 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7845 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7846 		    "FINWAIT2 timer (us)");
7847 
7848 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7849 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7850 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7851 		    "Number of SYN retransmissions before abort");
7852 
7853 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7854 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7855 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7856 		    "Number of retransmissions before abort");
7857 
7858 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7859 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7860 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7861 		    "Number of keepalive probes before abort");
7862 
7863 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7864 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7865 		    "TOE retransmit backoffs");
7866 		children = SYSCTL_CHILDREN(oid);
7867 		for (i = 0; i < 16; i++) {
7868 			snprintf(s, sizeof(s), "%u", i);
7869 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7870 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7871 			    i, sysctl_tp_backoff, "IU",
7872 			    "TOE retransmit backoff");
7873 		}
7874 	}
7875 #endif
7876 }
7877 
7878 void
7879 vi_sysctls(struct vi_info *vi)
7880 {
7881 	struct sysctl_ctx_list *ctx = &vi->ctx;
7882 	struct sysctl_oid *oid;
7883 	struct sysctl_oid_list *children;
7884 
7885 	/*
7886 	 * dev.v?(cxgbe|cxl).X.
7887 	 */
7888 	oid = device_get_sysctl_tree(vi->dev);
7889 	children = SYSCTL_CHILDREN(oid);
7890 
7891 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7892 	    vi->viid, "VI identifer");
7893 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7894 	    &vi->nrxq, 0, "# of rx queues");
7895 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7896 	    &vi->ntxq, 0, "# of tx queues");
7897 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7898 	    &vi->first_rxq, 0, "index of first rx queue");
7899 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7900 	    &vi->first_txq, 0, "index of first tx queue");
7901 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7902 	    vi->rss_base, "start of RSS indirection table");
7903 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7904 	    vi->rss_size, "size of RSS indirection table");
7905 
7906 	if (IS_MAIN_VI(vi)) {
7907 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7908 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7909 		    sysctl_noflowq, "IU",
7910 		    "Reserve queue 0 for non-flowid packets");
7911 	}
7912 
7913 	if (vi->adapter->flags & IS_VF) {
7914 		MPASS(vi->flags & TX_USES_VM_WR);
7915 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7916 		    NULL, 1, "use VM work requests for transmit");
7917 	} else {
7918 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7919 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7920 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7921 	}
7922 
7923 #ifdef TCP_OFFLOAD
7924 	if (vi->nofldrxq != 0) {
7925 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7926 		    &vi->nofldrxq, 0,
7927 		    "# of rx queues for offloaded TCP connections");
7928 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7929 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7930 		    "index of first TOE rx queue");
7931 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7932 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7933 		    sysctl_holdoff_tmr_idx_ofld, "I",
7934 		    "holdoff timer index for TOE queues");
7935 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7936 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7937 		    sysctl_holdoff_pktc_idx_ofld, "I",
7938 		    "holdoff packet counter index for TOE queues");
7939 	}
7940 #endif
7941 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7942 	if (vi->nofldtxq != 0) {
7943 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7944 		    &vi->nofldtxq, 0,
7945 		    "# of tx queues for TOE/ETHOFLD");
7946 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7947 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7948 		    "index of first TOE/ETHOFLD tx queue");
7949 	}
7950 #endif
7951 #ifdef DEV_NETMAP
7952 	if (vi->nnmrxq != 0) {
7953 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7954 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7955 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7956 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7957 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7958 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7959 		    "index of first netmap rx queue");
7960 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7961 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7962 		    "index of first netmap tx queue");
7963 	}
7964 #endif
7965 
7966 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7967 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7968 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7969 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7970 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7971 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7972 
7973 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7974 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7975 	    sysctl_qsize_rxq, "I", "rx queue size");
7976 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7977 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7978 	    sysctl_qsize_txq, "I", "tx queue size");
7979 }
7980 
7981 static void
7982 cxgbe_sysctls(struct port_info *pi)
7983 {
7984 	struct sysctl_ctx_list *ctx = &pi->ctx;
7985 	struct sysctl_oid *oid;
7986 	struct sysctl_oid_list *children, *children2;
7987 	struct adapter *sc = pi->adapter;
7988 	int i;
7989 	char name[16];
7990 	static char *tc_flags = {"\20\1USER"};
7991 
7992 	/*
7993 	 * dev.cxgbe.X.
7994 	 */
7995 	oid = device_get_sysctl_tree(pi->dev);
7996 	children = SYSCTL_CHILDREN(oid);
7997 
7998 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7999 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8000 	    sysctl_linkdnrc, "A", "reason why link is down");
8001 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
8002 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
8003 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
8004 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
8005 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
8006 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
8007 		    sysctl_btphy, "I", "PHY firmware version");
8008 	}
8009 
8010 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
8011 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8012 	    sysctl_pause_settings, "A",
8013 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
8014 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
8015 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
8016 	    "FEC in use on the link");
8017 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8018 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8019 	    sysctl_requested_fec, "A",
8020 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8021 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8022 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8023 	    "FEC recommended by the cable/transceiver");
8024 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8025 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8026 	    sysctl_autoneg, "I",
8027 	    "autonegotiation (-1 = not supported)");
8028 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8029 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8030 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8031 
8032 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8033 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8034 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8035 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8036 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8037 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8038 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8039 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8040 
8041 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8042 	    port_top_speed(pi), "max speed (in Gbps)");
8043 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8044 	    pi->mps_bg_map, "MPS buffer group map");
8045 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8046 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8047 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8048 	    pi->tx_chan, "TP tx c-channel");
8049 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8050 	    pi->rx_chan, "TP rx c-channel");
8051 
8052 	if (sc->flags & IS_VF)
8053 		return;
8054 
8055 	/*
8056 	 * dev.(cxgbe|cxl).X.tc.
8057 	 */
8058 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8059 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8060 	    "Tx scheduler traffic classes (cl_rl)");
8061 	children2 = SYSCTL_CHILDREN(oid);
8062 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8063 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8064 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8065 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8066 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8067 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8068 	for (i = 0; i < sc->params.nsched_cls; i++) {
8069 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8070 
8071 		snprintf(name, sizeof(name), "%d", i);
8072 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8073 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8074 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8075 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8076 		    CTLFLAG_RD, &tc->state, 0, "current state");
8077 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8078 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8079 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8080 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8081 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8082 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8083 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8084 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8085 		    "traffic class parameters");
8086 	}
8087 
8088 	/*
8089 	 * dev.cxgbe.X.stats.
8090 	 */
8091 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8092 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8093 	children = SYSCTL_CHILDREN(oid);
8094 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8095 	    &pi->tx_parse_error, 0,
8096 	    "# of tx packets with invalid length or # of segments");
8097 
8098 #define T4_REGSTAT(name, stat, desc) \
8099     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8100 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8101 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8102         sysctl_handle_t4_reg64, "QU", desc)
8103 
8104 /* We get these from port_stats and they may be stale by up to 1s */
8105 #define T4_PORTSTAT(name, desc) \
8106 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8107 	    &pi->stats.name, desc)
8108 
8109 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8110 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8111 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8112 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8113 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8114 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8115 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8116 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8117 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8118 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8119 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8120 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8121 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8122 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8123 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8124 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8125 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8126 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8127 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8128 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8129 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8130 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8131 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8132 
8133 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8134 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8135 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8136 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8137 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8138 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8139 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8140 	if (is_t6(sc)) {
8141 		T4_PORTSTAT(rx_fcs_err,
8142 		    "# of frames received with bad FCS since last link up");
8143 	} else {
8144 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8145 		    "# of frames received with bad FCS");
8146 	}
8147 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8148 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8149 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8150 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8151 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8152 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8153 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8154 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8155 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8156 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8157 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8158 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8159 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8160 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8161 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8162 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8163 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8164 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8165 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8166 
8167 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8168 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8169 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8170 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8171 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8172 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8173 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8174 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8175 
8176 #undef T4_REGSTAT
8177 #undef T4_PORTSTAT
8178 }
8179 
8180 static int
8181 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8182 {
8183 	int rc, *i, space = 0;
8184 	struct sbuf sb;
8185 
8186 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8187 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8188 		if (space)
8189 			sbuf_printf(&sb, " ");
8190 		sbuf_printf(&sb, "%d", *i);
8191 		space = 1;
8192 	}
8193 	rc = sbuf_finish(&sb);
8194 	sbuf_delete(&sb);
8195 	return (rc);
8196 }
8197 
8198 static int
8199 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8200 {
8201 	int rc;
8202 	struct sbuf *sb;
8203 
8204 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8205 	if (sb == NULL)
8206 		return (ENOMEM);
8207 
8208 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8209 	rc = sbuf_finish(sb);
8210 	sbuf_delete(sb);
8211 
8212 	return (rc);
8213 }
8214 
8215 static int
8216 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8217 {
8218 	int rc;
8219 	struct sbuf *sb;
8220 
8221 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8222 	if (sb == NULL)
8223 		return (ENOMEM);
8224 
8225 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8226 	rc = sbuf_finish(sb);
8227 	sbuf_delete(sb);
8228 
8229 	return (rc);
8230 }
8231 
8232 static int
8233 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8234 {
8235 	struct port_info *pi = arg1;
8236 	int op = arg2;
8237 	struct adapter *sc = pi->adapter;
8238 	u_int v;
8239 	int rc;
8240 
8241 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8242 	if (rc)
8243 		return (rc);
8244 	if (hw_off_limits(sc))
8245 		rc = ENXIO;
8246 	else {
8247 		/* XXX: magic numbers */
8248 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8249 		    op ? 0x20 : 0xc820, &v);
8250 	}
8251 	end_synchronized_op(sc, 0);
8252 	if (rc)
8253 		return (rc);
8254 	if (op == 0)
8255 		v /= 256;
8256 
8257 	rc = sysctl_handle_int(oidp, &v, 0, req);
8258 	return (rc);
8259 }
8260 
8261 static int
8262 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8263 {
8264 	struct vi_info *vi = arg1;
8265 	int rc, val;
8266 
8267 	val = vi->rsrv_noflowq;
8268 	rc = sysctl_handle_int(oidp, &val, 0, req);
8269 	if (rc != 0 || req->newptr == NULL)
8270 		return (rc);
8271 
8272 	if ((val >= 1) && (vi->ntxq > 1))
8273 		vi->rsrv_noflowq = 1;
8274 	else
8275 		vi->rsrv_noflowq = 0;
8276 
8277 	return (rc);
8278 }
8279 
8280 static int
8281 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8282 {
8283 	struct vi_info *vi = arg1;
8284 	struct adapter *sc = vi->adapter;
8285 	int rc, val, i;
8286 
8287 	MPASS(!(sc->flags & IS_VF));
8288 
8289 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8290 	rc = sysctl_handle_int(oidp, &val, 0, req);
8291 	if (rc != 0 || req->newptr == NULL)
8292 		return (rc);
8293 
8294 	if (val != 0 && val != 1)
8295 		return (EINVAL);
8296 
8297 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8298 	    "t4txvm");
8299 	if (rc)
8300 		return (rc);
8301 	if (hw_off_limits(sc))
8302 		rc = ENXIO;
8303 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8304 		/*
8305 		 * We don't want parse_pkt to run with one setting (VF or PF)
8306 		 * and then eth_tx to see a different setting but still use
8307 		 * stale information calculated by parse_pkt.
8308 		 */
8309 		rc = EBUSY;
8310 	} else {
8311 		struct port_info *pi = vi->pi;
8312 		struct sge_txq *txq;
8313 		uint32_t ctrl0;
8314 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8315 
8316 		if (val) {
8317 			vi->flags |= TX_USES_VM_WR;
8318 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8319 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8320 			    V_TXPKT_INTF(pi->tx_chan));
8321 			if (!(sc->flags & IS_VF))
8322 				npkt--;
8323 		} else {
8324 			vi->flags &= ~TX_USES_VM_WR;
8325 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8326 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8327 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8328 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8329 		}
8330 		for_each_txq(vi, i, txq) {
8331 			txq->cpl_ctrl0 = ctrl0;
8332 			txq->txp.max_npkt = npkt;
8333 		}
8334 	}
8335 	end_synchronized_op(sc, LOCK_HELD);
8336 	return (rc);
8337 }
8338 
8339 static int
8340 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8341 {
8342 	struct vi_info *vi = arg1;
8343 	struct adapter *sc = vi->adapter;
8344 	int idx, rc, i;
8345 	struct sge_rxq *rxq;
8346 	uint8_t v;
8347 
8348 	idx = vi->tmr_idx;
8349 
8350 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8351 	if (rc != 0 || req->newptr == NULL)
8352 		return (rc);
8353 
8354 	if (idx < 0 || idx >= SGE_NTIMERS)
8355 		return (EINVAL);
8356 
8357 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8358 	    "t4tmr");
8359 	if (rc)
8360 		return (rc);
8361 
8362 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8363 	for_each_rxq(vi, i, rxq) {
8364 #ifdef atomic_store_rel_8
8365 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8366 #else
8367 		rxq->iq.intr_params = v;
8368 #endif
8369 	}
8370 	vi->tmr_idx = idx;
8371 
8372 	end_synchronized_op(sc, LOCK_HELD);
8373 	return (0);
8374 }
8375 
8376 static int
8377 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8378 {
8379 	struct vi_info *vi = arg1;
8380 	struct adapter *sc = vi->adapter;
8381 	int idx, rc;
8382 
8383 	idx = vi->pktc_idx;
8384 
8385 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8386 	if (rc != 0 || req->newptr == NULL)
8387 		return (rc);
8388 
8389 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8390 		return (EINVAL);
8391 
8392 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8393 	    "t4pktc");
8394 	if (rc)
8395 		return (rc);
8396 
8397 	if (vi->flags & VI_INIT_DONE)
8398 		rc = EBUSY; /* cannot be changed once the queues are created */
8399 	else
8400 		vi->pktc_idx = idx;
8401 
8402 	end_synchronized_op(sc, LOCK_HELD);
8403 	return (rc);
8404 }
8405 
8406 static int
8407 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8408 {
8409 	struct vi_info *vi = arg1;
8410 	struct adapter *sc = vi->adapter;
8411 	int qsize, rc;
8412 
8413 	qsize = vi->qsize_rxq;
8414 
8415 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8416 	if (rc != 0 || req->newptr == NULL)
8417 		return (rc);
8418 
8419 	if (qsize < 128 || (qsize & 7))
8420 		return (EINVAL);
8421 
8422 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8423 	    "t4rxqs");
8424 	if (rc)
8425 		return (rc);
8426 
8427 	if (vi->flags & VI_INIT_DONE)
8428 		rc = EBUSY; /* cannot be changed once the queues are created */
8429 	else
8430 		vi->qsize_rxq = qsize;
8431 
8432 	end_synchronized_op(sc, LOCK_HELD);
8433 	return (rc);
8434 }
8435 
8436 static int
8437 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8438 {
8439 	struct vi_info *vi = arg1;
8440 	struct adapter *sc = vi->adapter;
8441 	int qsize, rc;
8442 
8443 	qsize = vi->qsize_txq;
8444 
8445 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8446 	if (rc != 0 || req->newptr == NULL)
8447 		return (rc);
8448 
8449 	if (qsize < 128 || qsize > 65536)
8450 		return (EINVAL);
8451 
8452 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8453 	    "t4txqs");
8454 	if (rc)
8455 		return (rc);
8456 
8457 	if (vi->flags & VI_INIT_DONE)
8458 		rc = EBUSY; /* cannot be changed once the queues are created */
8459 	else
8460 		vi->qsize_txq = qsize;
8461 
8462 	end_synchronized_op(sc, LOCK_HELD);
8463 	return (rc);
8464 }
8465 
8466 static int
8467 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8468 {
8469 	struct port_info *pi = arg1;
8470 	struct adapter *sc = pi->adapter;
8471 	struct link_config *lc = &pi->link_cfg;
8472 	int rc;
8473 
8474 	if (req->newptr == NULL) {
8475 		struct sbuf *sb;
8476 		static char *bits = "\20\1RX\2TX\3AUTO";
8477 
8478 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8479 		if (sb == NULL)
8480 			return (ENOMEM);
8481 
8482 		if (lc->link_ok) {
8483 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8484 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8485 		} else {
8486 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8487 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8488 		}
8489 		rc = sbuf_finish(sb);
8490 		sbuf_delete(sb);
8491 	} else {
8492 		char s[2];
8493 		int n;
8494 
8495 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8496 		    PAUSE_AUTONEG));
8497 		s[1] = 0;
8498 
8499 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8500 		if (rc != 0)
8501 			return(rc);
8502 
8503 		if (s[1] != 0)
8504 			return (EINVAL);
8505 		if (s[0] < '0' || s[0] > '9')
8506 			return (EINVAL);	/* not a number */
8507 		n = s[0] - '0';
8508 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8509 			return (EINVAL);	/* some other bit is set too */
8510 
8511 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8512 		    "t4PAUSE");
8513 		if (rc)
8514 			return (rc);
8515 		if (!hw_off_limits(sc)) {
8516 			PORT_LOCK(pi);
8517 			lc->requested_fc = n;
8518 			fixup_link_config(pi);
8519 			if (pi->up_vis > 0)
8520 				rc = apply_link_config(pi);
8521 			set_current_media(pi);
8522 			PORT_UNLOCK(pi);
8523 		}
8524 		end_synchronized_op(sc, 0);
8525 	}
8526 
8527 	return (rc);
8528 }
8529 
8530 static int
8531 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8532 {
8533 	struct port_info *pi = arg1;
8534 	struct link_config *lc = &pi->link_cfg;
8535 	int rc;
8536 	struct sbuf *sb;
8537 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8538 
8539 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8540 	if (sb == NULL)
8541 		return (ENOMEM);
8542 	if (lc->link_ok)
8543 		sbuf_printf(sb, "%b", lc->fec, bits);
8544 	else
8545 		sbuf_printf(sb, "no link");
8546 	rc = sbuf_finish(sb);
8547 	sbuf_delete(sb);
8548 
8549 	return (rc);
8550 }
8551 
8552 static int
8553 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8554 {
8555 	struct port_info *pi = arg1;
8556 	struct adapter *sc = pi->adapter;
8557 	struct link_config *lc = &pi->link_cfg;
8558 	int rc;
8559 	int8_t old;
8560 
8561 	if (req->newptr == NULL) {
8562 		struct sbuf *sb;
8563 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8564 		    "\5RSVD3\6auto\7module";
8565 
8566 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8567 		if (sb == NULL)
8568 			return (ENOMEM);
8569 
8570 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8571 		rc = sbuf_finish(sb);
8572 		sbuf_delete(sb);
8573 	} else {
8574 		char s[8];
8575 		int n;
8576 
8577 		snprintf(s, sizeof(s), "%d",
8578 		    lc->requested_fec == FEC_AUTO ? -1 :
8579 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8580 
8581 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8582 		if (rc != 0)
8583 			return(rc);
8584 
8585 		n = strtol(&s[0], NULL, 0);
8586 		if (n < 0 || n & FEC_AUTO)
8587 			n = FEC_AUTO;
8588 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8589 			return (EINVAL);/* some other bit is set too */
8590 
8591 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8592 		    "t4reqf");
8593 		if (rc)
8594 			return (rc);
8595 		PORT_LOCK(pi);
8596 		old = lc->requested_fec;
8597 		if (n == FEC_AUTO)
8598 			lc->requested_fec = FEC_AUTO;
8599 		else if (n == 0 || n == FEC_NONE)
8600 			lc->requested_fec = FEC_NONE;
8601 		else {
8602 			if ((lc->pcaps |
8603 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8604 			    lc->pcaps) {
8605 				rc = ENOTSUP;
8606 				goto done;
8607 			}
8608 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8609 			    FEC_MODULE);
8610 		}
8611 		if (!hw_off_limits(sc)) {
8612 			fixup_link_config(pi);
8613 			if (pi->up_vis > 0) {
8614 				rc = apply_link_config(pi);
8615 				if (rc != 0) {
8616 					lc->requested_fec = old;
8617 					if (rc == FW_EPROTO)
8618 						rc = ENOTSUP;
8619 				}
8620 			}
8621 		}
8622 done:
8623 		PORT_UNLOCK(pi);
8624 		end_synchronized_op(sc, 0);
8625 	}
8626 
8627 	return (rc);
8628 }
8629 
8630 static int
8631 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8632 {
8633 	struct port_info *pi = arg1;
8634 	struct adapter *sc = pi->adapter;
8635 	struct link_config *lc = &pi->link_cfg;
8636 	int rc;
8637 	int8_t fec;
8638 	struct sbuf *sb;
8639 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8640 
8641 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8642 	if (sb == NULL)
8643 		return (ENOMEM);
8644 
8645 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8646 		rc = EBUSY;
8647 		goto done;
8648 	}
8649 	if (hw_off_limits(sc)) {
8650 		rc = ENXIO;
8651 		goto done;
8652 	}
8653 	PORT_LOCK(pi);
8654 	if (pi->up_vis == 0) {
8655 		/*
8656 		 * If all the interfaces are administratively down the firmware
8657 		 * does not report transceiver changes.  Refresh port info here.
8658 		 * This is the only reason we have a synchronized op in this
8659 		 * function.  Just PORT_LOCK would have been enough otherwise.
8660 		 */
8661 		t4_update_port_info(pi);
8662 	}
8663 
8664 	fec = lc->fec_hint;
8665 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8666 	    !fec_supported(lc->pcaps)) {
8667 		PORT_UNLOCK(pi);
8668 		sbuf_printf(sb, "n/a");
8669 	} else {
8670 		if (fec == 0)
8671 			fec = FEC_NONE;
8672 		PORT_UNLOCK(pi);
8673 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8674 	}
8675 	rc = sbuf_finish(sb);
8676 done:
8677 	sbuf_delete(sb);
8678 	end_synchronized_op(sc, 0);
8679 
8680 	return (rc);
8681 }
8682 
8683 static int
8684 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8685 {
8686 	struct port_info *pi = arg1;
8687 	struct adapter *sc = pi->adapter;
8688 	struct link_config *lc = &pi->link_cfg;
8689 	int rc, val;
8690 
8691 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8692 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8693 	else
8694 		val = -1;
8695 	rc = sysctl_handle_int(oidp, &val, 0, req);
8696 	if (rc != 0 || req->newptr == NULL)
8697 		return (rc);
8698 	if (val == 0)
8699 		val = AUTONEG_DISABLE;
8700 	else if (val == 1)
8701 		val = AUTONEG_ENABLE;
8702 	else
8703 		val = AUTONEG_AUTO;
8704 
8705 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8706 	    "t4aneg");
8707 	if (rc)
8708 		return (rc);
8709 	PORT_LOCK(pi);
8710 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8711 		rc = ENOTSUP;
8712 		goto done;
8713 	}
8714 	lc->requested_aneg = val;
8715 	if (!hw_off_limits(sc)) {
8716 		fixup_link_config(pi);
8717 		if (pi->up_vis > 0)
8718 			rc = apply_link_config(pi);
8719 		set_current_media(pi);
8720 	}
8721 done:
8722 	PORT_UNLOCK(pi);
8723 	end_synchronized_op(sc, 0);
8724 	return (rc);
8725 }
8726 
8727 static int
8728 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8729 {
8730 	struct port_info *pi = arg1;
8731 	struct adapter *sc = pi->adapter;
8732 	struct link_config *lc = &pi->link_cfg;
8733 	int rc, val;
8734 
8735 	val = lc->force_fec;
8736 	MPASS(val >= -1 && val <= 1);
8737 	rc = sysctl_handle_int(oidp, &val, 0, req);
8738 	if (rc != 0 || req->newptr == NULL)
8739 		return (rc);
8740 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8741 		return (ENOTSUP);
8742 	if (val < -1 || val > 1)
8743 		return (EINVAL);
8744 
8745 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8746 	if (rc)
8747 		return (rc);
8748 	PORT_LOCK(pi);
8749 	lc->force_fec = val;
8750 	if (!hw_off_limits(sc)) {
8751 		fixup_link_config(pi);
8752 		if (pi->up_vis > 0)
8753 			rc = apply_link_config(pi);
8754 	}
8755 	PORT_UNLOCK(pi);
8756 	end_synchronized_op(sc, 0);
8757 	return (rc);
8758 }
8759 
8760 static int
8761 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8762 {
8763 	struct adapter *sc = arg1;
8764 	int rc, reg = arg2;
8765 	uint64_t val;
8766 
8767 	mtx_lock(&sc->reg_lock);
8768 	if (hw_off_limits(sc))
8769 		rc = ENXIO;
8770 	else {
8771 		rc = 0;
8772 		val = t4_read_reg64(sc, reg);
8773 	}
8774 	mtx_unlock(&sc->reg_lock);
8775 	if (rc == 0)
8776 		rc = sysctl_handle_64(oidp, &val, 0, req);
8777 	return (rc);
8778 }
8779 
8780 static int
8781 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8782 {
8783 	struct adapter *sc = arg1;
8784 	int rc, t;
8785 	uint32_t param, val;
8786 
8787 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8788 	if (rc)
8789 		return (rc);
8790 	if (hw_off_limits(sc))
8791 		rc = ENXIO;
8792 	else {
8793 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8794 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8795 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8796 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8797 	}
8798 	end_synchronized_op(sc, 0);
8799 	if (rc)
8800 		return (rc);
8801 
8802 	/* unknown is returned as 0 but we display -1 in that case */
8803 	t = val == 0 ? -1 : val;
8804 
8805 	rc = sysctl_handle_int(oidp, &t, 0, req);
8806 	return (rc);
8807 }
8808 
8809 static int
8810 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8811 {
8812 	struct adapter *sc = arg1;
8813 	int rc;
8814 	uint32_t param, val;
8815 
8816 	if (sc->params.core_vdd == 0) {
8817 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8818 		    "t4vdd");
8819 		if (rc)
8820 			return (rc);
8821 		if (hw_off_limits(sc))
8822 			rc = ENXIO;
8823 		else {
8824 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8825 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8826 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8827 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8828 			    &param, &val);
8829 		}
8830 		end_synchronized_op(sc, 0);
8831 		if (rc)
8832 			return (rc);
8833 		sc->params.core_vdd = val;
8834 	}
8835 
8836 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8837 }
8838 
8839 static int
8840 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8841 {
8842 	struct adapter *sc = arg1;
8843 	int rc, v;
8844 	uint32_t param, val;
8845 
8846 	v = sc->sensor_resets;
8847 	rc = sysctl_handle_int(oidp, &v, 0, req);
8848 	if (rc != 0 || req->newptr == NULL || v <= 0)
8849 		return (rc);
8850 
8851 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8852 	    chip_id(sc) < CHELSIO_T5)
8853 		return (ENOTSUP);
8854 
8855 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8856 	if (rc)
8857 		return (rc);
8858 	if (hw_off_limits(sc))
8859 		rc = ENXIO;
8860 	else {
8861 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8862 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8863 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8864 		val = 1;
8865 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8866 	}
8867 	end_synchronized_op(sc, 0);
8868 	if (rc == 0)
8869 		sc->sensor_resets++;
8870 	return (rc);
8871 }
8872 
8873 static int
8874 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8875 {
8876 	struct adapter *sc = arg1;
8877 	struct sbuf *sb;
8878 	int rc;
8879 	uint32_t param, val;
8880 
8881 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8882 	if (rc)
8883 		return (rc);
8884 	if (hw_off_limits(sc))
8885 		rc = ENXIO;
8886 	else {
8887 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8888 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8889 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8890 	}
8891 	end_synchronized_op(sc, 0);
8892 	if (rc)
8893 		return (rc);
8894 
8895 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8896 	if (sb == NULL)
8897 		return (ENOMEM);
8898 
8899 	if (val == 0xffffffff) {
8900 		/* Only debug and custom firmwares report load averages. */
8901 		sbuf_printf(sb, "not available");
8902 	} else {
8903 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8904 		    (val >> 16) & 0xff);
8905 	}
8906 	rc = sbuf_finish(sb);
8907 	sbuf_delete(sb);
8908 
8909 	return (rc);
8910 }
8911 
8912 static int
8913 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8914 {
8915 	struct adapter *sc = arg1;
8916 	struct sbuf *sb;
8917 	int rc, i;
8918 	uint16_t incr[NMTUS][NCCTRL_WIN];
8919 	static const char *dec_fac[] = {
8920 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8921 		"0.9375"
8922 	};
8923 
8924 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8925 	if (sb == NULL)
8926 		return (ENOMEM);
8927 
8928 	rc = 0;
8929 	mtx_lock(&sc->reg_lock);
8930 	if (hw_off_limits(sc))
8931 		rc = ENXIO;
8932 	else
8933 		t4_read_cong_tbl(sc, incr);
8934 	mtx_unlock(&sc->reg_lock);
8935 	if (rc)
8936 		goto done;
8937 
8938 	for (i = 0; i < NCCTRL_WIN; ++i) {
8939 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8940 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8941 		    incr[5][i], incr[6][i], incr[7][i]);
8942 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8943 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8944 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8945 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8946 	}
8947 
8948 	rc = sbuf_finish(sb);
8949 done:
8950 	sbuf_delete(sb);
8951 	return (rc);
8952 }
8953 
8954 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8955 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8956 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8957 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8958 };
8959 
8960 static int
8961 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8962 {
8963 	struct adapter *sc = arg1;
8964 	struct sbuf *sb;
8965 	int rc, i, n, qid = arg2;
8966 	uint32_t *buf, *p;
8967 	char *qtype;
8968 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8969 
8970 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8971 	    ("%s: bad qid %d\n", __func__, qid));
8972 
8973 	if (qid < CIM_NUM_IBQ) {
8974 		/* inbound queue */
8975 		qtype = "IBQ";
8976 		n = 4 * CIM_IBQ_SIZE;
8977 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8978 		mtx_lock(&sc->reg_lock);
8979 		if (hw_off_limits(sc))
8980 			rc = -ENXIO;
8981 		else
8982 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8983 		mtx_unlock(&sc->reg_lock);
8984 	} else {
8985 		/* outbound queue */
8986 		qtype = "OBQ";
8987 		qid -= CIM_NUM_IBQ;
8988 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8989 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8990 		mtx_lock(&sc->reg_lock);
8991 		if (hw_off_limits(sc))
8992 			rc = -ENXIO;
8993 		else
8994 			rc = t4_read_cim_obq(sc, qid, buf, n);
8995 		mtx_unlock(&sc->reg_lock);
8996 	}
8997 
8998 	if (rc < 0) {
8999 		rc = -rc;
9000 		goto done;
9001 	}
9002 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
9003 
9004 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9005 	if (sb == NULL) {
9006 		rc = ENOMEM;
9007 		goto done;
9008 	}
9009 
9010 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
9011 	for (i = 0, p = buf; i < n; i += 16, p += 4)
9012 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
9013 		    p[2], p[3]);
9014 
9015 	rc = sbuf_finish(sb);
9016 	sbuf_delete(sb);
9017 done:
9018 	free(buf, M_CXGBE);
9019 	return (rc);
9020 }
9021 
9022 static void
9023 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9024 {
9025 	uint32_t *p;
9026 
9027 	sbuf_printf(sb, "Status   Data      PC%s",
9028 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9029 	    "     LS0Stat  LS0Addr             LS0Data");
9030 
9031 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9032 		if (cfg & F_UPDBGLACAPTPCONLY) {
9033 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9034 			    p[6], p[7]);
9035 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9036 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9037 			    p[4] & 0xff, p[5] >> 8);
9038 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9039 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9040 			    p[1] & 0xf, p[2] >> 4);
9041 		} else {
9042 			sbuf_printf(sb,
9043 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9044 			    "%08x%08x%08x%08x",
9045 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9046 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9047 			    p[6], p[7]);
9048 		}
9049 	}
9050 }
9051 
9052 static void
9053 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9054 {
9055 	uint32_t *p;
9056 
9057 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9058 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9059 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9060 
9061 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9062 		if (cfg & F_UPDBGLACAPTPCONLY) {
9063 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9064 			    p[3] & 0xff, p[2], p[1], p[0]);
9065 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9066 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9067 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9068 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9069 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9070 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9071 			    p[6] >> 16);
9072 		} else {
9073 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9074 			    "%08x %08x %08x %08x %08x %08x",
9075 			    (p[9] >> 16) & 0xff,
9076 			    p[9] & 0xffff, p[8] >> 16,
9077 			    p[8] & 0xffff, p[7] >> 16,
9078 			    p[7] & 0xffff, p[6] >> 16,
9079 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9080 		}
9081 	}
9082 }
9083 
9084 static int
9085 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9086 {
9087 	uint32_t cfg, *buf;
9088 	int rc;
9089 
9090 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9091 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9092 	    M_ZERO | flags);
9093 	if (buf == NULL)
9094 		return (ENOMEM);
9095 
9096 	mtx_lock(&sc->reg_lock);
9097 	if (hw_off_limits(sc))
9098 		rc = ENXIO;
9099 	else {
9100 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9101 		if (rc == 0)
9102 			rc = -t4_cim_read_la(sc, buf, NULL);
9103 	}
9104 	mtx_unlock(&sc->reg_lock);
9105 	if (rc == 0) {
9106 		if (chip_id(sc) < CHELSIO_T6)
9107 			sbuf_cim_la4(sc, sb, buf, cfg);
9108 		else
9109 			sbuf_cim_la6(sc, sb, buf, cfg);
9110 	}
9111 	free(buf, M_CXGBE);
9112 	return (rc);
9113 }
9114 
9115 static int
9116 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9117 {
9118 	struct adapter *sc = arg1;
9119 	struct sbuf *sb;
9120 	int rc;
9121 
9122 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9123 	if (sb == NULL)
9124 		return (ENOMEM);
9125 
9126 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9127 	if (rc == 0)
9128 		rc = sbuf_finish(sb);
9129 	sbuf_delete(sb);
9130 	return (rc);
9131 }
9132 
9133 static void
9134 dump_cim_regs(struct adapter *sc)
9135 {
9136 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9137 	    device_get_nameunit(sc->dev),
9138 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9139 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9140 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9141 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9142 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9143 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9144 	    device_get_nameunit(sc->dev),
9145 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9146 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9147 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9148 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9149 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9150 }
9151 
9152 static void
9153 dump_cimla(struct adapter *sc)
9154 {
9155 	struct sbuf sb;
9156 	int rc;
9157 
9158 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9159 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9160 		    device_get_nameunit(sc->dev));
9161 		return;
9162 	}
9163 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9164 	if (rc == 0) {
9165 		rc = sbuf_finish(&sb);
9166 		if (rc == 0) {
9167 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9168 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9169 		}
9170 	}
9171 	sbuf_delete(&sb);
9172 }
9173 
9174 void
9175 t4_os_cim_err(struct adapter *sc)
9176 {
9177 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9178 }
9179 
9180 static int
9181 sysctl_cim_ma_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 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9190 	if (sb == NULL)
9191 		return (ENOMEM);
9192 
9193 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9194 	    M_ZERO | M_WAITOK);
9195 
9196 	rc = 0;
9197 	mtx_lock(&sc->reg_lock);
9198 	if (hw_off_limits(sc))
9199 		rc = ENXIO;
9200 	else
9201 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9202 	mtx_unlock(&sc->reg_lock);
9203 	if (rc)
9204 		goto done;
9205 
9206 	p = buf;
9207 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9208 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9209 		    p[1], p[0]);
9210 	}
9211 
9212 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9213 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9214 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9215 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9216 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9217 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9218 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9219 		    p[0] & 1);
9220 	}
9221 	rc = sbuf_finish(sb);
9222 done:
9223 	sbuf_delete(sb);
9224 	free(buf, M_CXGBE);
9225 	return (rc);
9226 }
9227 
9228 static int
9229 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9230 {
9231 	struct adapter *sc = arg1;
9232 	u_int i;
9233 	struct sbuf *sb;
9234 	uint32_t *buf, *p;
9235 	int rc;
9236 
9237 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9238 	if (sb == NULL)
9239 		return (ENOMEM);
9240 
9241 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9242 	    M_ZERO | M_WAITOK);
9243 
9244 	rc = 0;
9245 	mtx_lock(&sc->reg_lock);
9246 	if (hw_off_limits(sc))
9247 		rc = ENXIO;
9248 	else
9249 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9250 	mtx_unlock(&sc->reg_lock);
9251 	if (rc)
9252 		goto done;
9253 
9254 	p = buf;
9255 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9256 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9257 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9258 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9259 		    p[4], p[3], p[2], p[1], p[0]);
9260 	}
9261 
9262 	sbuf_printf(sb, "\n\nCntl ID               Data");
9263 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9264 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9265 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9266 	}
9267 
9268 	rc = sbuf_finish(sb);
9269 done:
9270 	sbuf_delete(sb);
9271 	free(buf, M_CXGBE);
9272 	return (rc);
9273 }
9274 
9275 static int
9276 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9277 {
9278 	struct adapter *sc = arg1;
9279 	struct sbuf *sb;
9280 	int rc, i;
9281 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9282 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9283 	uint16_t thres[CIM_NUM_IBQ];
9284 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9285 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9286 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9287 
9288 	cim_num_obq = sc->chip_params->cim_num_obq;
9289 	if (is_t4(sc)) {
9290 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9291 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9292 	} else {
9293 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9294 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9295 	}
9296 	nq = CIM_NUM_IBQ + cim_num_obq;
9297 
9298 	mtx_lock(&sc->reg_lock);
9299 	if (hw_off_limits(sc))
9300 		rc = ENXIO;
9301 	else {
9302 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9303 		if (rc == 0) {
9304 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9305 			    obq_wr);
9306 			if (rc == 0)
9307 				t4_read_cimq_cfg(sc, base, size, thres);
9308 		}
9309 	}
9310 	mtx_unlock(&sc->reg_lock);
9311 	if (rc)
9312 		return (rc);
9313 
9314 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9315 	if (sb == NULL)
9316 		return (ENOMEM);
9317 
9318 	sbuf_printf(sb,
9319 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9320 
9321 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9322 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9323 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9324 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9325 		    G_QUEREMFLITS(p[2]) * 16);
9326 	for ( ; i < nq; i++, p += 4, wr += 2)
9327 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9328 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9329 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9330 		    G_QUEREMFLITS(p[2]) * 16);
9331 
9332 	rc = sbuf_finish(sb);
9333 	sbuf_delete(sb);
9334 
9335 	return (rc);
9336 }
9337 
9338 static int
9339 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9340 {
9341 	struct adapter *sc = arg1;
9342 	struct sbuf *sb;
9343 	int rc;
9344 	struct tp_cpl_stats stats;
9345 
9346 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9347 	if (sb == NULL)
9348 		return (ENOMEM);
9349 
9350 	rc = 0;
9351 	mtx_lock(&sc->reg_lock);
9352 	if (hw_off_limits(sc))
9353 		rc = ENXIO;
9354 	else
9355 		t4_tp_get_cpl_stats(sc, &stats, 0);
9356 	mtx_unlock(&sc->reg_lock);
9357 	if (rc)
9358 		goto done;
9359 
9360 	if (sc->chip_params->nchan > 2) {
9361 		sbuf_printf(sb, "                 channel 0  channel 1"
9362 		    "  channel 2  channel 3");
9363 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9364 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9365 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9366 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9367 	} else {
9368 		sbuf_printf(sb, "                 channel 0  channel 1");
9369 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9370 		    stats.req[0], stats.req[1]);
9371 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9372 		    stats.rsp[0], stats.rsp[1]);
9373 	}
9374 
9375 	rc = sbuf_finish(sb);
9376 done:
9377 	sbuf_delete(sb);
9378 	return (rc);
9379 }
9380 
9381 static int
9382 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9383 {
9384 	struct adapter *sc = arg1;
9385 	struct sbuf *sb;
9386 	int rc;
9387 	struct tp_usm_stats stats;
9388 
9389 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9390 	if (sb == NULL)
9391 		return (ENOMEM);
9392 
9393 	rc = 0;
9394 	mtx_lock(&sc->reg_lock);
9395 	if (hw_off_limits(sc))
9396 		rc = ENXIO;
9397 	else
9398 		t4_get_usm_stats(sc, &stats, 1);
9399 	mtx_unlock(&sc->reg_lock);
9400 	if (rc == 0) {
9401 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9402 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9403 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9404 		rc = sbuf_finish(sb);
9405 	}
9406 	sbuf_delete(sb);
9407 
9408 	return (rc);
9409 }
9410 
9411 static int
9412 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9413 {
9414 	struct adapter *sc = arg1;
9415 	struct sbuf *sb;
9416 	int rc;
9417 	struct tp_tid_stats stats;
9418 
9419 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9420 	if (sb == NULL)
9421 		return (ENOMEM);
9422 
9423 	rc = 0;
9424 	mtx_lock(&sc->reg_lock);
9425 	if (hw_off_limits(sc))
9426 		rc = ENXIO;
9427 	else
9428 		t4_tp_get_tid_stats(sc, &stats, 1);
9429 	mtx_unlock(&sc->reg_lock);
9430 	if (rc == 0) {
9431 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9432 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9433 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9434 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9435 		rc = sbuf_finish(sb);
9436 	}
9437 	sbuf_delete(sb);
9438 
9439 	return (rc);
9440 }
9441 
9442 static const char * const devlog_level_strings[] = {
9443 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9444 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9445 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9446 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9447 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9448 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9449 };
9450 
9451 static const char * const devlog_facility_strings[] = {
9452 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9453 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9454 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9455 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9456 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9457 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9458 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9459 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9460 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9461 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9462 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9463 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9464 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9465 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9466 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9467 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9468 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9469 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9470 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9471 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9472 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9473 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9474 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9475 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9476 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9477 };
9478 
9479 static int
9480 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9481 {
9482 	int i, j, rc, nentries, first = 0;
9483 	struct devlog_params *dparams = &sc->params.devlog;
9484 	struct fw_devlog_e *buf, *e;
9485 	uint64_t ftstamp = UINT64_MAX;
9486 
9487 	if (dparams->addr == 0)
9488 		return (ENXIO);
9489 
9490 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9491 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9492 	if (buf == NULL)
9493 		return (ENOMEM);
9494 
9495 	mtx_lock(&sc->reg_lock);
9496 	if (hw_off_limits(sc))
9497 		rc = ENXIO;
9498 	else
9499 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9500 		    dparams->size);
9501 	mtx_unlock(&sc->reg_lock);
9502 	if (rc != 0)
9503 		goto done;
9504 
9505 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9506 	for (i = 0; i < nentries; i++) {
9507 		e = &buf[i];
9508 
9509 		if (e->timestamp == 0)
9510 			break;	/* end */
9511 
9512 		e->timestamp = be64toh(e->timestamp);
9513 		e->seqno = be32toh(e->seqno);
9514 		for (j = 0; j < 8; j++)
9515 			e->params[j] = be32toh(e->params[j]);
9516 
9517 		if (e->timestamp < ftstamp) {
9518 			ftstamp = e->timestamp;
9519 			first = i;
9520 		}
9521 	}
9522 
9523 	if (buf[first].timestamp == 0)
9524 		goto done;	/* nothing in the log */
9525 
9526 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9527 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9528 
9529 	i = first;
9530 	do {
9531 		e = &buf[i];
9532 		if (e->timestamp == 0)
9533 			break;	/* end */
9534 
9535 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9536 		    e->seqno, e->timestamp,
9537 		    (e->level < nitems(devlog_level_strings) ?
9538 			devlog_level_strings[e->level] : "UNKNOWN"),
9539 		    (e->facility < nitems(devlog_facility_strings) ?
9540 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9541 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9542 		    e->params[2], e->params[3], e->params[4],
9543 		    e->params[5], e->params[6], e->params[7]);
9544 
9545 		if (++i == nentries)
9546 			i = 0;
9547 	} while (i != first);
9548 done:
9549 	free(buf, M_CXGBE);
9550 	return (rc);
9551 }
9552 
9553 static int
9554 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9555 {
9556 	struct adapter *sc = arg1;
9557 	int rc;
9558 	struct sbuf *sb;
9559 
9560 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9561 	if (sb == NULL)
9562 		return (ENOMEM);
9563 
9564 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9565 	if (rc == 0)
9566 		rc = sbuf_finish(sb);
9567 	sbuf_delete(sb);
9568 	return (rc);
9569 }
9570 
9571 static void
9572 dump_devlog(struct adapter *sc)
9573 {
9574 	int rc;
9575 	struct sbuf sb;
9576 
9577 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9578 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9579 		    device_get_nameunit(sc->dev));
9580 		return;
9581 	}
9582 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9583 	if (rc == 0) {
9584 		rc = sbuf_finish(&sb);
9585 		if (rc == 0) {
9586 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9587 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9588 		}
9589 	}
9590 	sbuf_delete(&sb);
9591 }
9592 
9593 static int
9594 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9595 {
9596 	struct adapter *sc = arg1;
9597 	struct sbuf *sb;
9598 	int rc;
9599 	struct tp_fcoe_stats stats[MAX_NCHAN];
9600 	int i, nchan = sc->chip_params->nchan;
9601 
9602 	rc = 0;
9603 	mtx_lock(&sc->reg_lock);
9604 	if (hw_off_limits(sc))
9605 		rc = ENXIO;
9606 	else {
9607 		for (i = 0; i < nchan; i++)
9608 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9609 	}
9610 	mtx_unlock(&sc->reg_lock);
9611 	if (rc != 0)
9612 		return (rc);
9613 
9614 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9615 	if (sb == NULL)
9616 		return (ENOMEM);
9617 
9618 	if (nchan > 2) {
9619 		sbuf_printf(sb, "                   channel 0        channel 1"
9620 		    "        channel 2        channel 3");
9621 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9622 		    stats[0].octets_ddp, stats[1].octets_ddp,
9623 		    stats[2].octets_ddp, stats[3].octets_ddp);
9624 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9625 		    stats[0].frames_ddp, stats[1].frames_ddp,
9626 		    stats[2].frames_ddp, stats[3].frames_ddp);
9627 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9628 		    stats[0].frames_drop, stats[1].frames_drop,
9629 		    stats[2].frames_drop, stats[3].frames_drop);
9630 	} else {
9631 		sbuf_printf(sb, "                   channel 0        channel 1");
9632 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9633 		    stats[0].octets_ddp, stats[1].octets_ddp);
9634 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9635 		    stats[0].frames_ddp, stats[1].frames_ddp);
9636 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9637 		    stats[0].frames_drop, stats[1].frames_drop);
9638 	}
9639 
9640 	rc = sbuf_finish(sb);
9641 	sbuf_delete(sb);
9642 
9643 	return (rc);
9644 }
9645 
9646 static int
9647 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9648 {
9649 	struct adapter *sc = arg1;
9650 	struct sbuf *sb;
9651 	int rc, i;
9652 	unsigned int map, kbps, ipg, mode;
9653 	unsigned int pace_tab[NTX_SCHED];
9654 
9655 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9656 	if (sb == NULL)
9657 		return (ENOMEM);
9658 
9659 	mtx_lock(&sc->reg_lock);
9660 	if (hw_off_limits(sc)) {
9661 		mtx_unlock(&sc->reg_lock);
9662 		rc = ENXIO;
9663 		goto done;
9664 	}
9665 
9666 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9667 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9668 	t4_read_pace_tbl(sc, pace_tab);
9669 	mtx_unlock(&sc->reg_lock);
9670 
9671 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9672 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9673 
9674 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9675 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9676 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9677 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9678 		if (kbps)
9679 			sbuf_printf(sb, "%9u     ", kbps);
9680 		else
9681 			sbuf_printf(sb, " disabled     ");
9682 
9683 		if (ipg)
9684 			sbuf_printf(sb, "%13u        ", ipg);
9685 		else
9686 			sbuf_printf(sb, "     disabled        ");
9687 
9688 		if (pace_tab[i])
9689 			sbuf_printf(sb, "%10u", pace_tab[i]);
9690 		else
9691 			sbuf_printf(sb, "  disabled");
9692 	}
9693 	rc = sbuf_finish(sb);
9694 done:
9695 	sbuf_delete(sb);
9696 	return (rc);
9697 }
9698 
9699 static int
9700 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9701 {
9702 	struct adapter *sc = arg1;
9703 	struct sbuf *sb;
9704 	int rc, i, j;
9705 	uint64_t *p0, *p1;
9706 	struct lb_port_stats s[2];
9707 	static const char *stat_name[] = {
9708 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9709 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9710 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9711 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9712 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9713 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9714 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9715 	};
9716 
9717 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9718 	if (sb == NULL)
9719 		return (ENOMEM);
9720 
9721 	memset(s, 0, sizeof(s));
9722 
9723 	rc = 0;
9724 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9725 		mtx_lock(&sc->reg_lock);
9726 		if (hw_off_limits(sc))
9727 			rc = ENXIO;
9728 		else {
9729 			t4_get_lb_stats(sc, i, &s[0]);
9730 			t4_get_lb_stats(sc, i + 1, &s[1]);
9731 		}
9732 		mtx_unlock(&sc->reg_lock);
9733 		if (rc != 0)
9734 			break;
9735 
9736 		p0 = &s[0].octets;
9737 		p1 = &s[1].octets;
9738 		sbuf_printf(sb, "%s                       Loopback %u"
9739 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9740 
9741 		for (j = 0; j < nitems(stat_name); j++)
9742 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9743 				   *p0++, *p1++);
9744 	}
9745 
9746 	if (rc == 0)
9747 		rc = sbuf_finish(sb);
9748 	sbuf_delete(sb);
9749 
9750 	return (rc);
9751 }
9752 
9753 static int
9754 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9755 {
9756 	int rc = 0;
9757 	struct port_info *pi = arg1;
9758 	struct link_config *lc = &pi->link_cfg;
9759 	struct sbuf *sb;
9760 
9761 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9762 	if (sb == NULL)
9763 		return (ENOMEM);
9764 
9765 	if (lc->link_ok || lc->link_down_rc == 255)
9766 		sbuf_printf(sb, "n/a");
9767 	else
9768 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9769 
9770 	rc = sbuf_finish(sb);
9771 	sbuf_delete(sb);
9772 
9773 	return (rc);
9774 }
9775 
9776 struct mem_desc {
9777 	u_int base;
9778 	u_int limit;
9779 	u_int idx;
9780 };
9781 
9782 static int
9783 mem_desc_cmp(const void *a, const void *b)
9784 {
9785 	const u_int v1 = ((const struct mem_desc *)a)->base;
9786 	const u_int v2 = ((const struct mem_desc *)b)->base;
9787 
9788 	if (v1 < v2)
9789 		return (-1);
9790 	else if (v1 > v2)
9791 		return (1);
9792 
9793 	return (0);
9794 }
9795 
9796 static void
9797 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9798     unsigned int to)
9799 {
9800 	unsigned int size;
9801 
9802 	if (from == to)
9803 		return;
9804 
9805 	size = to - from + 1;
9806 	if (size == 0)
9807 		return;
9808 
9809 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9810 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9811 }
9812 
9813 static int
9814 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9815 {
9816 	struct adapter *sc = arg1;
9817 	struct sbuf *sb;
9818 	int rc, i, n;
9819 	uint32_t lo, hi, used, free, alloc;
9820 	static const char *memory[] = {
9821 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9822 	};
9823 	static const char *region[] = {
9824 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9825 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9826 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9827 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9828 		"RQUDP region:", "PBL region:", "TXPBL region:",
9829 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9830 		"ULPTX state:", "On-chip queues:",
9831 	};
9832 	struct mem_desc avail[4];
9833 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9834 	struct mem_desc *md = mem;
9835 
9836 	rc = sysctl_wire_old_buffer(req, 0);
9837 	if (rc != 0)
9838 		return (rc);
9839 
9840 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9841 	if (sb == NULL)
9842 		return (ENOMEM);
9843 
9844 	for (i = 0; i < nitems(mem); i++) {
9845 		mem[i].limit = 0;
9846 		mem[i].idx = i;
9847 	}
9848 
9849 	mtx_lock(&sc->reg_lock);
9850 	if (hw_off_limits(sc)) {
9851 		rc = ENXIO;
9852 		goto done;
9853 	}
9854 
9855 	/* Find and sort the populated memory ranges */
9856 	i = 0;
9857 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9858 	if (lo & F_EDRAM0_ENABLE) {
9859 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9860 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9861 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9862 		avail[i].idx = 0;
9863 		i++;
9864 	}
9865 	if (lo & F_EDRAM1_ENABLE) {
9866 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9867 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9868 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9869 		avail[i].idx = 1;
9870 		i++;
9871 	}
9872 	if (lo & F_EXT_MEM_ENABLE) {
9873 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9874 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9875 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9876 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9877 		i++;
9878 	}
9879 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9880 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9881 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9882 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9883 		avail[i].idx = 4;
9884 		i++;
9885 	}
9886 	if (is_t6(sc) && lo & F_HMA_MUX) {
9887 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9888 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9889 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9890 		avail[i].idx = 5;
9891 		i++;
9892 	}
9893 	MPASS(i <= nitems(avail));
9894 	if (!i)                                    /* no memory available */
9895 		goto done;
9896 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9897 
9898 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9899 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9900 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9901 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9902 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9903 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9904 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9905 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9906 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9907 
9908 	/* the next few have explicit upper bounds */
9909 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9910 	md->limit = md->base - 1 +
9911 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9912 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9913 	md++;
9914 
9915 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9916 	md->limit = md->base - 1 +
9917 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9918 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9919 	md++;
9920 
9921 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9922 		if (chip_id(sc) <= CHELSIO_T5)
9923 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9924 		else
9925 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9926 		md->limit = 0;
9927 	} else {
9928 		md->base = 0;
9929 		md->idx = nitems(region);  /* hide it */
9930 	}
9931 	md++;
9932 
9933 #define ulp_region(reg) \
9934 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9935 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9936 
9937 	ulp_region(RX_ISCSI);
9938 	ulp_region(RX_TDDP);
9939 	ulp_region(TX_TPT);
9940 	ulp_region(RX_STAG);
9941 	ulp_region(RX_RQ);
9942 	ulp_region(RX_RQUDP);
9943 	ulp_region(RX_PBL);
9944 	ulp_region(TX_PBL);
9945 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9946 		ulp_region(RX_TLS_KEY);
9947 	}
9948 #undef ulp_region
9949 
9950 	md->base = 0;
9951 	if (is_t4(sc))
9952 		md->idx = nitems(region);
9953 	else {
9954 		uint32_t size = 0;
9955 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9956 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9957 
9958 		if (is_t5(sc)) {
9959 			if (sge_ctrl & F_VFIFO_ENABLE)
9960 				size = fifo_size << 2;
9961 		} else
9962 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9963 
9964 		if (size) {
9965 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9966 			md->limit = md->base + size - 1;
9967 		} else
9968 			md->idx = nitems(region);
9969 	}
9970 	md++;
9971 
9972 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9973 	md->limit = 0;
9974 	md++;
9975 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9976 	md->limit = 0;
9977 	md++;
9978 
9979 	md->base = sc->vres.ocq.start;
9980 	if (sc->vres.ocq.size)
9981 		md->limit = md->base + sc->vres.ocq.size - 1;
9982 	else
9983 		md->idx = nitems(region);  /* hide it */
9984 	md++;
9985 
9986 	/* add any address-space holes, there can be up to 3 */
9987 	for (n = 0; n < i - 1; n++)
9988 		if (avail[n].limit < avail[n + 1].base)
9989 			(md++)->base = avail[n].limit;
9990 	if (avail[n].limit)
9991 		(md++)->base = avail[n].limit;
9992 
9993 	n = md - mem;
9994 	MPASS(n <= nitems(mem));
9995 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9996 
9997 	for (lo = 0; lo < i; lo++)
9998 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9999 				avail[lo].limit - 1);
10000 
10001 	sbuf_printf(sb, "\n");
10002 	for (i = 0; i < n; i++) {
10003 		if (mem[i].idx >= nitems(region))
10004 			continue;                        /* skip holes */
10005 		if (!mem[i].limit)
10006 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10007 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10008 				mem[i].limit);
10009 	}
10010 
10011 	sbuf_printf(sb, "\n");
10012 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10013 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10014 	mem_region_show(sb, "uP RAM:", lo, hi);
10015 
10016 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10017 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10018 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10019 
10020 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10021 	for (i = 0, free = 0; i < 2; i++)
10022 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10023 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10024 		   G_PMRXMAXPAGE(lo), free,
10025 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10026 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10027 
10028 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10029 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10030 	for (i = 0, free = 0; i < 4; i++)
10031 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10032 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10033 		   G_PMTXMAXPAGE(lo), free,
10034 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10035 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10036 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10037 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10038 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10039 
10040 	for (i = 0; i < 4; i++) {
10041 		if (chip_id(sc) > CHELSIO_T5)
10042 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10043 		else
10044 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10045 		if (is_t5(sc)) {
10046 			used = G_T5_USED(lo);
10047 			alloc = G_T5_ALLOC(lo);
10048 		} else {
10049 			used = G_USED(lo);
10050 			alloc = G_ALLOC(lo);
10051 		}
10052 		/* For T6 these are MAC buffer groups */
10053 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10054 		    i, used, alloc);
10055 	}
10056 	for (i = 0; i < sc->chip_params->nchan; i++) {
10057 		if (chip_id(sc) > CHELSIO_T5)
10058 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10059 		else
10060 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10061 		if (is_t5(sc)) {
10062 			used = G_T5_USED(lo);
10063 			alloc = G_T5_ALLOC(lo);
10064 		} else {
10065 			used = G_USED(lo);
10066 			alloc = G_ALLOC(lo);
10067 		}
10068 		/* For T6 these are MAC buffer groups */
10069 		sbuf_printf(sb,
10070 		    "\nLoopback %d using %u pages out of %u allocated",
10071 		    i, used, alloc);
10072 	}
10073 done:
10074 	mtx_unlock(&sc->reg_lock);
10075 	if (rc == 0)
10076 		rc = sbuf_finish(sb);
10077 	sbuf_delete(sb);
10078 	return (rc);
10079 }
10080 
10081 static inline void
10082 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10083 {
10084 	*mask = x | y;
10085 	y = htobe64(y);
10086 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10087 }
10088 
10089 static int
10090 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10091 {
10092 	struct adapter *sc = arg1;
10093 	struct sbuf *sb;
10094 	int rc, i;
10095 
10096 	MPASS(chip_id(sc) <= CHELSIO_T5);
10097 
10098 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10099 	if (sb == NULL)
10100 		return (ENOMEM);
10101 
10102 	sbuf_printf(sb,
10103 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10104 	    "  VF              Replication             P0 P1 P2 P3  ML");
10105 	rc = 0;
10106 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10107 		uint64_t tcamx, tcamy, mask;
10108 		uint32_t cls_lo, cls_hi;
10109 		uint8_t addr[ETHER_ADDR_LEN];
10110 
10111 		mtx_lock(&sc->reg_lock);
10112 		if (hw_off_limits(sc))
10113 			rc = ENXIO;
10114 		else {
10115 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10116 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10117 		}
10118 		mtx_unlock(&sc->reg_lock);
10119 		if (rc != 0)
10120 			break;
10121 		if (tcamx & tcamy)
10122 			continue;
10123 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10124 		mtx_lock(&sc->reg_lock);
10125 		if (hw_off_limits(sc))
10126 			rc = ENXIO;
10127 		else {
10128 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10129 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10130 		}
10131 		mtx_unlock(&sc->reg_lock);
10132 		if (rc != 0)
10133 			break;
10134 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10135 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10136 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10137 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10138 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10139 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10140 
10141 		if (cls_lo & F_REPLICATE) {
10142 			struct fw_ldst_cmd ldst_cmd;
10143 
10144 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10145 			ldst_cmd.op_to_addrspace =
10146 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10147 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10148 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10149 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10150 			ldst_cmd.u.mps.rplc.fid_idx =
10151 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10152 				V_FW_LDST_CMD_IDX(i));
10153 
10154 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10155 			    "t4mps");
10156 			if (rc)
10157 				break;
10158 			if (hw_off_limits(sc))
10159 				rc = ENXIO;
10160 			else
10161 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10162 				    sizeof(ldst_cmd), &ldst_cmd);
10163 			end_synchronized_op(sc, 0);
10164 			if (rc != 0)
10165 				break;
10166 			else {
10167 				sbuf_printf(sb, " %08x %08x %08x %08x",
10168 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10169 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10170 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10171 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10172 			}
10173 		} else
10174 			sbuf_printf(sb, "%36s", "");
10175 
10176 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10177 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10178 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10179 	}
10180 
10181 	if (rc)
10182 		(void) sbuf_finish(sb);
10183 	else
10184 		rc = sbuf_finish(sb);
10185 	sbuf_delete(sb);
10186 
10187 	return (rc);
10188 }
10189 
10190 static int
10191 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10192 {
10193 	struct adapter *sc = arg1;
10194 	struct sbuf *sb;
10195 	int rc, i;
10196 
10197 	MPASS(chip_id(sc) > CHELSIO_T5);
10198 
10199 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10200 	if (sb == NULL)
10201 		return (ENOMEM);
10202 
10203 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10204 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10205 	    "                           Replication"
10206 	    "                                    P0 P1 P2 P3  ML\n");
10207 
10208 	rc = 0;
10209 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10210 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10211 		uint16_t ivlan;
10212 		uint64_t tcamx, tcamy, val, mask;
10213 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10214 		uint8_t addr[ETHER_ADDR_LEN];
10215 
10216 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10217 		if (i < 256)
10218 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10219 		else
10220 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10221 		mtx_lock(&sc->reg_lock);
10222 		if (hw_off_limits(sc))
10223 			rc = ENXIO;
10224 		else {
10225 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10226 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10227 			tcamy = G_DMACH(val) << 32;
10228 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10229 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10230 		}
10231 		mtx_unlock(&sc->reg_lock);
10232 		if (rc != 0)
10233 			break;
10234 
10235 		lookup_type = G_DATALKPTYPE(data2);
10236 		port_num = G_DATAPORTNUM(data2);
10237 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10238 			/* Inner header VNI */
10239 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10240 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10241 			dip_hit = data2 & F_DATADIPHIT;
10242 			vlan_vld = 0;
10243 		} else {
10244 			vniy = 0;
10245 			dip_hit = 0;
10246 			vlan_vld = data2 & F_DATAVIDH2;
10247 			ivlan = G_VIDL(val);
10248 		}
10249 
10250 		ctl |= V_CTLXYBITSEL(1);
10251 		mtx_lock(&sc->reg_lock);
10252 		if (hw_off_limits(sc))
10253 			rc = ENXIO;
10254 		else {
10255 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10256 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10257 			tcamx = G_DMACH(val) << 32;
10258 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10259 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10260 		}
10261 		mtx_unlock(&sc->reg_lock);
10262 		if (rc != 0)
10263 			break;
10264 
10265 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10266 			/* Inner header VNI mask */
10267 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10268 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10269 		} else
10270 			vnix = 0;
10271 
10272 		if (tcamx & tcamy)
10273 			continue;
10274 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10275 
10276 		mtx_lock(&sc->reg_lock);
10277 		if (hw_off_limits(sc))
10278 			rc = ENXIO;
10279 		else {
10280 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10281 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10282 		}
10283 		mtx_unlock(&sc->reg_lock);
10284 		if (rc != 0)
10285 			break;
10286 
10287 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10288 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10289 			    "%012jx %06x %06x    -    -   %3c"
10290 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10291 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10292 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10293 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10294 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10295 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10296 		} else {
10297 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10298 			    "%012jx    -       -   ", i, addr[0], addr[1],
10299 			    addr[2], addr[3], addr[4], addr[5],
10300 			    (uintmax_t)mask);
10301 
10302 			if (vlan_vld)
10303 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10304 			else
10305 				sbuf_printf(sb, "  -    N     ");
10306 
10307 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10308 			    lookup_type ? 'I' : 'O', port_num,
10309 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10310 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10311 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10312 		}
10313 
10314 
10315 		if (cls_lo & F_T6_REPLICATE) {
10316 			struct fw_ldst_cmd ldst_cmd;
10317 
10318 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10319 			ldst_cmd.op_to_addrspace =
10320 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10321 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10322 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10323 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10324 			ldst_cmd.u.mps.rplc.fid_idx =
10325 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10326 				V_FW_LDST_CMD_IDX(i));
10327 
10328 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10329 			    "t6mps");
10330 			if (rc)
10331 				break;
10332 			if (hw_off_limits(sc))
10333 				rc = ENXIO;
10334 			else
10335 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10336 				    sizeof(ldst_cmd), &ldst_cmd);
10337 			end_synchronized_op(sc, 0);
10338 			if (rc != 0)
10339 				break;
10340 			else {
10341 				sbuf_printf(sb, " %08x %08x %08x %08x"
10342 				    " %08x %08x %08x %08x",
10343 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10344 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10345 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10346 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10347 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10348 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10349 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10350 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10351 			}
10352 		} else
10353 			sbuf_printf(sb, "%72s", "");
10354 
10355 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10356 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10357 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10358 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10359 	}
10360 
10361 	if (rc)
10362 		(void) sbuf_finish(sb);
10363 	else
10364 		rc = sbuf_finish(sb);
10365 	sbuf_delete(sb);
10366 
10367 	return (rc);
10368 }
10369 
10370 static int
10371 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10372 {
10373 	struct adapter *sc = arg1;
10374 	struct sbuf *sb;
10375 	int rc;
10376 	uint16_t mtus[NMTUS];
10377 
10378 	rc = 0;
10379 	mtx_lock(&sc->reg_lock);
10380 	if (hw_off_limits(sc))
10381 		rc = ENXIO;
10382 	else
10383 		t4_read_mtu_tbl(sc, mtus, NULL);
10384 	mtx_unlock(&sc->reg_lock);
10385 	if (rc != 0)
10386 		return (rc);
10387 
10388 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10389 	if (sb == NULL)
10390 		return (ENOMEM);
10391 
10392 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10393 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10394 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10395 	    mtus[14], mtus[15]);
10396 
10397 	rc = sbuf_finish(sb);
10398 	sbuf_delete(sb);
10399 
10400 	return (rc);
10401 }
10402 
10403 static int
10404 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10405 {
10406 	struct adapter *sc = arg1;
10407 	struct sbuf *sb;
10408 	int rc, i;
10409 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10410 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10411 	static const char *tx_stats[MAX_PM_NSTATS] = {
10412 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10413 		"Tx FIFO wait", NULL, "Tx latency"
10414 	};
10415 	static const char *rx_stats[MAX_PM_NSTATS] = {
10416 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10417 		"Rx FIFO wait", NULL, "Rx latency"
10418 	};
10419 
10420 	rc = 0;
10421 	mtx_lock(&sc->reg_lock);
10422 	if (hw_off_limits(sc))
10423 		rc = ENXIO;
10424 	else {
10425 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10426 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10427 	}
10428 	mtx_unlock(&sc->reg_lock);
10429 	if (rc != 0)
10430 		return (rc);
10431 
10432 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10433 	if (sb == NULL)
10434 		return (ENOMEM);
10435 
10436 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10437 	for (i = 0; i < 4; i++) {
10438 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10439 		    tx_cyc[i]);
10440 	}
10441 
10442 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10443 	for (i = 0; i < 4; i++) {
10444 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10445 		    rx_cyc[i]);
10446 	}
10447 
10448 	if (chip_id(sc) > CHELSIO_T5) {
10449 		sbuf_printf(sb,
10450 		    "\n              Total wait      Total occupancy");
10451 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10452 		    tx_cyc[i]);
10453 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10454 		    rx_cyc[i]);
10455 
10456 		i += 2;
10457 		MPASS(i < nitems(tx_stats));
10458 
10459 		sbuf_printf(sb,
10460 		    "\n                   Reads           Total wait");
10461 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10462 		    tx_cyc[i]);
10463 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10464 		    rx_cyc[i]);
10465 	}
10466 
10467 	rc = sbuf_finish(sb);
10468 	sbuf_delete(sb);
10469 
10470 	return (rc);
10471 }
10472 
10473 static int
10474 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10475 {
10476 	struct adapter *sc = arg1;
10477 	struct sbuf *sb;
10478 	int rc;
10479 	struct tp_rdma_stats stats;
10480 
10481 	rc = 0;
10482 	mtx_lock(&sc->reg_lock);
10483 	if (hw_off_limits(sc))
10484 		rc = ENXIO;
10485 	else
10486 		t4_tp_get_rdma_stats(sc, &stats, 0);
10487 	mtx_unlock(&sc->reg_lock);
10488 	if (rc != 0)
10489 		return (rc);
10490 
10491 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10492 	if (sb == NULL)
10493 		return (ENOMEM);
10494 
10495 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10496 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10497 
10498 	rc = sbuf_finish(sb);
10499 	sbuf_delete(sb);
10500 
10501 	return (rc);
10502 }
10503 
10504 static int
10505 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10506 {
10507 	struct adapter *sc = arg1;
10508 	struct sbuf *sb;
10509 	int rc;
10510 	struct tp_tcp_stats v4, v6;
10511 
10512 	rc = 0;
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 = 0;
10553 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10554 	if (sb == NULL)
10555 		return (ENOMEM);
10556 
10557 	if (t->natids) {
10558 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10559 		    t->atids_in_use);
10560 	}
10561 
10562 	if (t->nhpftids) {
10563 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10564 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10565 	}
10566 
10567 	if (t->ntids) {
10568 		bool hashen = false;
10569 
10570 		mtx_lock(&sc->reg_lock);
10571 		if (hw_off_limits(sc))
10572 			rc = ENXIO;
10573 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10574 			hashen = true;
10575 			if (chip_id(sc) <= CHELSIO_T5) {
10576 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10577 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10578 			} else {
10579 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10580 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10581 			}
10582 		}
10583 		mtx_unlock(&sc->reg_lock);
10584 		if (rc != 0)
10585 			goto done;
10586 
10587 		sbuf_printf(sb, "TID range: ");
10588 		if (hashen) {
10589 			if (x)
10590 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10591 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10592 		} else {
10593 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10594 			    t->ntids - 1);
10595 		}
10596 		sbuf_printf(sb, ", in use: %u\n",
10597 		    atomic_load_acq_int(&t->tids_in_use));
10598 	}
10599 
10600 	if (t->nstids) {
10601 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10602 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10603 	}
10604 
10605 	if (t->nftids) {
10606 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10607 		    t->ftid_end, t->ftids_in_use);
10608 	}
10609 
10610 	if (t->netids) {
10611 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10612 		    t->etid_base + t->netids - 1, t->etids_in_use);
10613 	}
10614 
10615 	mtx_lock(&sc->reg_lock);
10616 	if (hw_off_limits(sc))
10617 		rc = ENXIO;
10618 	else {
10619 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10620 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10621 	}
10622 	mtx_unlock(&sc->reg_lock);
10623 	if (rc != 0)
10624 		goto done;
10625 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10626 done:
10627 	if (rc == 0)
10628 		rc = sbuf_finish(sb);
10629 	else
10630 		(void)sbuf_finish(sb);
10631 	sbuf_delete(sb);
10632 
10633 	return (rc);
10634 }
10635 
10636 static int
10637 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10638 {
10639 	struct adapter *sc = arg1;
10640 	struct sbuf *sb;
10641 	int rc;
10642 	struct tp_err_stats stats;
10643 
10644 	rc = 0;
10645 	mtx_lock(&sc->reg_lock);
10646 	if (hw_off_limits(sc))
10647 		rc = ENXIO;
10648 	else
10649 		t4_tp_get_err_stats(sc, &stats, 0);
10650 	mtx_unlock(&sc->reg_lock);
10651 	if (rc != 0)
10652 		return (rc);
10653 
10654 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10655 	if (sb == NULL)
10656 		return (ENOMEM);
10657 
10658 	if (sc->chip_params->nchan > 2) {
10659 		sbuf_printf(sb, "                 channel 0  channel 1"
10660 		    "  channel 2  channel 3\n");
10661 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10662 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10663 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10664 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10665 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10666 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10667 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10668 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10669 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10670 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10671 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10672 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10673 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10674 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10675 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10676 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10677 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10678 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10679 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10680 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10681 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10682 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10683 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10684 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10685 	} else {
10686 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10687 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10688 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10689 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10690 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10691 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10692 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10693 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10694 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10695 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10696 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10697 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10698 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10699 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10700 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10701 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10702 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10703 	}
10704 
10705 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10706 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10707 
10708 	rc = sbuf_finish(sb);
10709 	sbuf_delete(sb);
10710 
10711 	return (rc);
10712 }
10713 
10714 static int
10715 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10716 {
10717 	struct adapter *sc = arg1;
10718 	struct sbuf *sb;
10719 	int rc;
10720 	struct tp_tnl_stats stats;
10721 
10722 	rc = 0;
10723 	mtx_lock(&sc->reg_lock);
10724 	if (hw_off_limits(sc))
10725 		rc = ENXIO;
10726 	else
10727 		t4_tp_get_tnl_stats(sc, &stats, 1);
10728 	mtx_unlock(&sc->reg_lock);
10729 	if (rc != 0)
10730 		return (rc);
10731 
10732 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10733 	if (sb == NULL)
10734 		return (ENOMEM);
10735 
10736 	if (sc->chip_params->nchan > 2) {
10737 		sbuf_printf(sb, "           channel 0  channel 1"
10738 		    "  channel 2  channel 3\n");
10739 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10740 		    stats.out_pkt[0], stats.out_pkt[1],
10741 		    stats.out_pkt[2], stats.out_pkt[3]);
10742 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10743 		    stats.in_pkt[0], stats.in_pkt[1],
10744 		    stats.in_pkt[2], stats.in_pkt[3]);
10745 	} else {
10746 		sbuf_printf(sb, "           channel 0  channel 1\n");
10747 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10748 		    stats.out_pkt[0], stats.out_pkt[1]);
10749 		sbuf_printf(sb, "InPkts:   %10u %10u",
10750 		    stats.in_pkt[0], stats.in_pkt[1]);
10751 	}
10752 
10753 	rc = sbuf_finish(sb);
10754 	sbuf_delete(sb);
10755 
10756 	return (rc);
10757 }
10758 
10759 static int
10760 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10761 {
10762 	struct adapter *sc = arg1;
10763 	struct tp_params *tpp = &sc->params.tp;
10764 	u_int mask;
10765 	int rc;
10766 
10767 	mask = tpp->la_mask >> 16;
10768 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10769 	if (rc != 0 || req->newptr == NULL)
10770 		return (rc);
10771 	if (mask > 0xffff)
10772 		return (EINVAL);
10773 	mtx_lock(&sc->reg_lock);
10774 	if (hw_off_limits(sc))
10775 		rc = ENXIO;
10776 	else {
10777 		tpp->la_mask = mask << 16;
10778 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10779 		    tpp->la_mask);
10780 	}
10781 	mtx_unlock(&sc->reg_lock);
10782 
10783 	return (rc);
10784 }
10785 
10786 struct field_desc {
10787 	const char *name;
10788 	u_int start;
10789 	u_int width;
10790 };
10791 
10792 static void
10793 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10794 {
10795 	char buf[32];
10796 	int line_size = 0;
10797 
10798 	while (f->name) {
10799 		uint64_t mask = (1ULL << f->width) - 1;
10800 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10801 		    ((uintmax_t)v >> f->start) & mask);
10802 
10803 		if (line_size + len >= 79) {
10804 			line_size = 8;
10805 			sbuf_printf(sb, "\n        ");
10806 		}
10807 		sbuf_printf(sb, "%s ", buf);
10808 		line_size += len + 1;
10809 		f++;
10810 	}
10811 	sbuf_printf(sb, "\n");
10812 }
10813 
10814 static const struct field_desc tp_la0[] = {
10815 	{ "RcfOpCodeOut", 60, 4 },
10816 	{ "State", 56, 4 },
10817 	{ "WcfState", 52, 4 },
10818 	{ "RcfOpcSrcOut", 50, 2 },
10819 	{ "CRxError", 49, 1 },
10820 	{ "ERxError", 48, 1 },
10821 	{ "SanityFailed", 47, 1 },
10822 	{ "SpuriousMsg", 46, 1 },
10823 	{ "FlushInputMsg", 45, 1 },
10824 	{ "FlushInputCpl", 44, 1 },
10825 	{ "RssUpBit", 43, 1 },
10826 	{ "RssFilterHit", 42, 1 },
10827 	{ "Tid", 32, 10 },
10828 	{ "InitTcb", 31, 1 },
10829 	{ "LineNumber", 24, 7 },
10830 	{ "Emsg", 23, 1 },
10831 	{ "EdataOut", 22, 1 },
10832 	{ "Cmsg", 21, 1 },
10833 	{ "CdataOut", 20, 1 },
10834 	{ "EreadPdu", 19, 1 },
10835 	{ "CreadPdu", 18, 1 },
10836 	{ "TunnelPkt", 17, 1 },
10837 	{ "RcfPeerFin", 16, 1 },
10838 	{ "RcfReasonOut", 12, 4 },
10839 	{ "TxCchannel", 10, 2 },
10840 	{ "RcfTxChannel", 8, 2 },
10841 	{ "RxEchannel", 6, 2 },
10842 	{ "RcfRxChannel", 5, 1 },
10843 	{ "RcfDataOutSrdy", 4, 1 },
10844 	{ "RxDvld", 3, 1 },
10845 	{ "RxOoDvld", 2, 1 },
10846 	{ "RxCongestion", 1, 1 },
10847 	{ "TxCongestion", 0, 1 },
10848 	{ NULL }
10849 };
10850 
10851 static const struct field_desc tp_la1[] = {
10852 	{ "CplCmdIn", 56, 8 },
10853 	{ "CplCmdOut", 48, 8 },
10854 	{ "ESynOut", 47, 1 },
10855 	{ "EAckOut", 46, 1 },
10856 	{ "EFinOut", 45, 1 },
10857 	{ "ERstOut", 44, 1 },
10858 	{ "SynIn", 43, 1 },
10859 	{ "AckIn", 42, 1 },
10860 	{ "FinIn", 41, 1 },
10861 	{ "RstIn", 40, 1 },
10862 	{ "DataIn", 39, 1 },
10863 	{ "DataInVld", 38, 1 },
10864 	{ "PadIn", 37, 1 },
10865 	{ "RxBufEmpty", 36, 1 },
10866 	{ "RxDdp", 35, 1 },
10867 	{ "RxFbCongestion", 34, 1 },
10868 	{ "TxFbCongestion", 33, 1 },
10869 	{ "TxPktSumSrdy", 32, 1 },
10870 	{ "RcfUlpType", 28, 4 },
10871 	{ "Eread", 27, 1 },
10872 	{ "Ebypass", 26, 1 },
10873 	{ "Esave", 25, 1 },
10874 	{ "Static0", 24, 1 },
10875 	{ "Cread", 23, 1 },
10876 	{ "Cbypass", 22, 1 },
10877 	{ "Csave", 21, 1 },
10878 	{ "CPktOut", 20, 1 },
10879 	{ "RxPagePoolFull", 18, 2 },
10880 	{ "RxLpbkPkt", 17, 1 },
10881 	{ "TxLpbkPkt", 16, 1 },
10882 	{ "RxVfValid", 15, 1 },
10883 	{ "SynLearned", 14, 1 },
10884 	{ "SetDelEntry", 13, 1 },
10885 	{ "SetInvEntry", 12, 1 },
10886 	{ "CpcmdDvld", 11, 1 },
10887 	{ "CpcmdSave", 10, 1 },
10888 	{ "RxPstructsFull", 8, 2 },
10889 	{ "EpcmdDvld", 7, 1 },
10890 	{ "EpcmdFlush", 6, 1 },
10891 	{ "EpcmdTrimPrefix", 5, 1 },
10892 	{ "EpcmdTrimPostfix", 4, 1 },
10893 	{ "ERssIp4Pkt", 3, 1 },
10894 	{ "ERssIp6Pkt", 2, 1 },
10895 	{ "ERssTcpUdpPkt", 1, 1 },
10896 	{ "ERssFceFipPkt", 0, 1 },
10897 	{ NULL }
10898 };
10899 
10900 static const struct field_desc tp_la2[] = {
10901 	{ "CplCmdIn", 56, 8 },
10902 	{ "MpsVfVld", 55, 1 },
10903 	{ "MpsPf", 52, 3 },
10904 	{ "MpsVf", 44, 8 },
10905 	{ "SynIn", 43, 1 },
10906 	{ "AckIn", 42, 1 },
10907 	{ "FinIn", 41, 1 },
10908 	{ "RstIn", 40, 1 },
10909 	{ "DataIn", 39, 1 },
10910 	{ "DataInVld", 38, 1 },
10911 	{ "PadIn", 37, 1 },
10912 	{ "RxBufEmpty", 36, 1 },
10913 	{ "RxDdp", 35, 1 },
10914 	{ "RxFbCongestion", 34, 1 },
10915 	{ "TxFbCongestion", 33, 1 },
10916 	{ "TxPktSumSrdy", 32, 1 },
10917 	{ "RcfUlpType", 28, 4 },
10918 	{ "Eread", 27, 1 },
10919 	{ "Ebypass", 26, 1 },
10920 	{ "Esave", 25, 1 },
10921 	{ "Static0", 24, 1 },
10922 	{ "Cread", 23, 1 },
10923 	{ "Cbypass", 22, 1 },
10924 	{ "Csave", 21, 1 },
10925 	{ "CPktOut", 20, 1 },
10926 	{ "RxPagePoolFull", 18, 2 },
10927 	{ "RxLpbkPkt", 17, 1 },
10928 	{ "TxLpbkPkt", 16, 1 },
10929 	{ "RxVfValid", 15, 1 },
10930 	{ "SynLearned", 14, 1 },
10931 	{ "SetDelEntry", 13, 1 },
10932 	{ "SetInvEntry", 12, 1 },
10933 	{ "CpcmdDvld", 11, 1 },
10934 	{ "CpcmdSave", 10, 1 },
10935 	{ "RxPstructsFull", 8, 2 },
10936 	{ "EpcmdDvld", 7, 1 },
10937 	{ "EpcmdFlush", 6, 1 },
10938 	{ "EpcmdTrimPrefix", 5, 1 },
10939 	{ "EpcmdTrimPostfix", 4, 1 },
10940 	{ "ERssIp4Pkt", 3, 1 },
10941 	{ "ERssIp6Pkt", 2, 1 },
10942 	{ "ERssTcpUdpPkt", 1, 1 },
10943 	{ "ERssFceFipPkt", 0, 1 },
10944 	{ NULL }
10945 };
10946 
10947 static void
10948 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10949 {
10950 
10951 	field_desc_show(sb, *p, tp_la0);
10952 }
10953 
10954 static void
10955 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10956 {
10957 
10958 	if (idx)
10959 		sbuf_printf(sb, "\n");
10960 	field_desc_show(sb, p[0], tp_la0);
10961 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10962 		field_desc_show(sb, p[1], tp_la0);
10963 }
10964 
10965 static void
10966 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10967 {
10968 
10969 	if (idx)
10970 		sbuf_printf(sb, "\n");
10971 	field_desc_show(sb, p[0], tp_la0);
10972 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10973 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10974 }
10975 
10976 static int
10977 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10978 {
10979 	struct adapter *sc = arg1;
10980 	struct sbuf *sb;
10981 	uint64_t *buf, *p;
10982 	int rc;
10983 	u_int i, inc;
10984 	void (*show_func)(struct sbuf *, uint64_t *, int);
10985 
10986 	rc = 0;
10987 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10988 	if (sb == NULL)
10989 		return (ENOMEM);
10990 
10991 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10992 
10993 	mtx_lock(&sc->reg_lock);
10994 	if (hw_off_limits(sc))
10995 		rc = ENXIO;
10996 	else {
10997 		t4_tp_read_la(sc, buf, NULL);
10998 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10999 		case 2:
11000 			inc = 2;
11001 			show_func = tp_la_show2;
11002 			break;
11003 		case 3:
11004 			inc = 2;
11005 			show_func = tp_la_show3;
11006 			break;
11007 		default:
11008 			inc = 1;
11009 			show_func = tp_la_show;
11010 		}
11011 	}
11012 	mtx_unlock(&sc->reg_lock);
11013 	if (rc != 0)
11014 		goto done;
11015 
11016 	p = buf;
11017 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11018 		(*show_func)(sb, p, i);
11019 	rc = sbuf_finish(sb);
11020 done:
11021 	sbuf_delete(sb);
11022 	free(buf, M_CXGBE);
11023 	return (rc);
11024 }
11025 
11026 static int
11027 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11028 {
11029 	struct adapter *sc = arg1;
11030 	struct sbuf *sb;
11031 	int rc;
11032 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11033 
11034 	rc = 0;
11035 	mtx_lock(&sc->reg_lock);
11036 	if (hw_off_limits(sc))
11037 		rc = ENXIO;
11038 	else
11039 		t4_get_chan_txrate(sc, nrate, orate);
11040 	mtx_unlock(&sc->reg_lock);
11041 	if (rc != 0)
11042 		return (rc);
11043 
11044 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11045 	if (sb == NULL)
11046 		return (ENOMEM);
11047 
11048 	if (sc->chip_params->nchan > 2) {
11049 		sbuf_printf(sb, "              channel 0   channel 1"
11050 		    "   channel 2   channel 3\n");
11051 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11052 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11053 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11054 		    orate[0], orate[1], orate[2], orate[3]);
11055 	} else {
11056 		sbuf_printf(sb, "              channel 0   channel 1\n");
11057 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11058 		    nrate[0], nrate[1]);
11059 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11060 		    orate[0], orate[1]);
11061 	}
11062 
11063 	rc = sbuf_finish(sb);
11064 	sbuf_delete(sb);
11065 
11066 	return (rc);
11067 }
11068 
11069 static int
11070 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11071 {
11072 	struct adapter *sc = arg1;
11073 	struct sbuf *sb;
11074 	uint32_t *buf, *p;
11075 	int rc, i;
11076 
11077 	rc = 0;
11078 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11079 	if (sb == NULL)
11080 		return (ENOMEM);
11081 
11082 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11083 	    M_ZERO | M_WAITOK);
11084 
11085 	mtx_lock(&sc->reg_lock);
11086 	if (hw_off_limits(sc))
11087 		rc = ENXIO;
11088 	else
11089 		t4_ulprx_read_la(sc, buf);
11090 	mtx_unlock(&sc->reg_lock);
11091 	if (rc != 0)
11092 		goto done;
11093 
11094 	p = buf;
11095 	sbuf_printf(sb, "      Pcmd        Type   Message"
11096 	    "                Data");
11097 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11098 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11099 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11100 	}
11101 	rc = sbuf_finish(sb);
11102 done:
11103 	sbuf_delete(sb);
11104 	free(buf, M_CXGBE);
11105 	return (rc);
11106 }
11107 
11108 static int
11109 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11110 {
11111 	struct adapter *sc = arg1;
11112 	struct sbuf *sb;
11113 	int rc;
11114 	uint32_t cfg, s1, s2;
11115 
11116 	MPASS(chip_id(sc) >= CHELSIO_T5);
11117 
11118 	rc = 0;
11119 	mtx_lock(&sc->reg_lock);
11120 	if (hw_off_limits(sc))
11121 		rc = ENXIO;
11122 	else {
11123 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11124 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11125 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11126 	}
11127 	mtx_unlock(&sc->reg_lock);
11128 	if (rc != 0)
11129 		return (rc);
11130 
11131 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11132 	if (sb == NULL)
11133 		return (ENOMEM);
11134 
11135 	if (G_STATSOURCE_T5(cfg) == 7) {
11136 		int mode;
11137 
11138 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11139 		if (mode == 0)
11140 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11141 		else if (mode == 1)
11142 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11143 		else
11144 			sbuf_printf(sb, "unknown mode %d", mode);
11145 	}
11146 	rc = sbuf_finish(sb);
11147 	sbuf_delete(sb);
11148 
11149 	return (rc);
11150 }
11151 
11152 static int
11153 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11154 {
11155 	struct adapter *sc = arg1;
11156 	enum cpu_sets op = arg2;
11157 	cpuset_t cpuset;
11158 	struct sbuf *sb;
11159 	int i, rc;
11160 
11161 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11162 
11163 	CPU_ZERO(&cpuset);
11164 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11165 	if (rc != 0)
11166 		return (rc);
11167 
11168 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11169 	if (sb == NULL)
11170 		return (ENOMEM);
11171 
11172 	CPU_FOREACH(i)
11173 		sbuf_printf(sb, "%d ", i);
11174 	rc = sbuf_finish(sb);
11175 	sbuf_delete(sb);
11176 
11177 	return (rc);
11178 }
11179 
11180 static int
11181 sysctl_reset(SYSCTL_HANDLER_ARGS)
11182 {
11183 	struct adapter *sc = arg1;
11184 	u_int val;
11185 	int rc;
11186 
11187 	val = atomic_load_int(&sc->num_resets);
11188 	rc = sysctl_handle_int(oidp, &val, 0, req);
11189 	if (rc != 0 || req->newptr == NULL)
11190 		return (rc);
11191 
11192 	if (val == 0) {
11193 		/* Zero out the counter that tracks reset. */
11194 		atomic_store_int(&sc->num_resets, 0);
11195 		return (0);
11196 	}
11197 
11198 	if (val != 1)
11199 		return (EINVAL);	/* 0 or 1 are the only legal values */
11200 
11201 	if (hw_off_limits(sc))		/* harmless race */
11202 		return (EALREADY);
11203 
11204 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11205 	return (0);
11206 }
11207 
11208 #ifdef TCP_OFFLOAD
11209 static int
11210 sysctl_tls(SYSCTL_HANDLER_ARGS)
11211 {
11212 	struct adapter *sc = arg1;
11213 	int i, j, v, rc;
11214 	struct vi_info *vi;
11215 
11216 	v = sc->tt.tls;
11217 	rc = sysctl_handle_int(oidp, &v, 0, req);
11218 	if (rc != 0 || req->newptr == NULL)
11219 		return (rc);
11220 
11221 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11222 		return (ENOTSUP);
11223 
11224 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11225 	if (rc)
11226 		return (rc);
11227 	if (hw_off_limits(sc))
11228 		rc = ENXIO;
11229 	else {
11230 		sc->tt.tls = !!v;
11231 		for_each_port(sc, i) {
11232 			for_each_vi(sc->port[i], j, vi) {
11233 				if (vi->flags & VI_INIT_DONE)
11234 					t4_update_fl_bufsize(vi->ifp);
11235 			}
11236 		}
11237 	}
11238 	end_synchronized_op(sc, 0);
11239 
11240 	return (rc);
11241 
11242 }
11243 
11244 static void
11245 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11246 {
11247 	u_int rem = val % factor;
11248 
11249 	if (rem == 0)
11250 		snprintf(buf, len, "%u", val / factor);
11251 	else {
11252 		while (rem % 10 == 0)
11253 			rem /= 10;
11254 		snprintf(buf, len, "%u.%u", val / factor, rem);
11255 	}
11256 }
11257 
11258 static int
11259 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11260 {
11261 	struct adapter *sc = arg1;
11262 	char buf[16];
11263 	u_int res, re;
11264 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11265 
11266 	mtx_lock(&sc->reg_lock);
11267 	if (hw_off_limits(sc))
11268 		res = (u_int)-1;
11269 	else
11270 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11271 	mtx_unlock(&sc->reg_lock);
11272 	if (res == (u_int)-1)
11273 		return (ENXIO);
11274 
11275 	switch (arg2) {
11276 	case 0:
11277 		/* timer_tick */
11278 		re = G_TIMERRESOLUTION(res);
11279 		break;
11280 	case 1:
11281 		/* TCP timestamp tick */
11282 		re = G_TIMESTAMPRESOLUTION(res);
11283 		break;
11284 	case 2:
11285 		/* DACK tick */
11286 		re = G_DELAYEDACKRESOLUTION(res);
11287 		break;
11288 	default:
11289 		return (EDOOFUS);
11290 	}
11291 
11292 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11293 
11294 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11295 }
11296 
11297 static int
11298 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11299 {
11300 	struct adapter *sc = arg1;
11301 	int rc;
11302 	u_int dack_tmr, dack_re, v;
11303 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11304 
11305 	mtx_lock(&sc->reg_lock);
11306 	if (hw_off_limits(sc))
11307 		rc = ENXIO;
11308 	else {
11309 		rc = 0;
11310 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11311 		    A_TP_TIMER_RESOLUTION));
11312 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11313 	}
11314 	mtx_unlock(&sc->reg_lock);
11315 	if (rc != 0)
11316 		return (rc);
11317 
11318 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11319 
11320 	return (sysctl_handle_int(oidp, &v, 0, req));
11321 }
11322 
11323 static int
11324 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11325 {
11326 	struct adapter *sc = arg1;
11327 	int rc, reg = arg2;
11328 	u_int tre;
11329 	u_long tp_tick_us, v;
11330 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11331 
11332 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11333 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11334 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11335 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11336 
11337 	mtx_lock(&sc->reg_lock);
11338 	if (hw_off_limits(sc))
11339 		rc = ENXIO;
11340 	else {
11341 		rc = 0;
11342 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11343 		tp_tick_us = (cclk_ps << tre) / 1000000;
11344 		if (reg == A_TP_INIT_SRTT)
11345 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11346 		else
11347 			v = tp_tick_us * t4_read_reg(sc, reg);
11348 	}
11349 	mtx_unlock(&sc->reg_lock);
11350 	if (rc != 0)
11351 		return (rc);
11352 	else
11353 		return (sysctl_handle_long(oidp, &v, 0, req));
11354 }
11355 
11356 /*
11357  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11358  * passed to this function.
11359  */
11360 static int
11361 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11362 {
11363 	struct adapter *sc = arg1;
11364 	int rc, idx = arg2;
11365 	u_int v;
11366 
11367 	MPASS(idx >= 0 && idx <= 24);
11368 
11369 	mtx_lock(&sc->reg_lock);
11370 	if (hw_off_limits(sc))
11371 		rc = ENXIO;
11372 	else {
11373 		rc = 0;
11374 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11375 	}
11376 	mtx_unlock(&sc->reg_lock);
11377 	if (rc != 0)
11378 		return (rc);
11379 	else
11380 		return (sysctl_handle_int(oidp, &v, 0, req));
11381 }
11382 
11383 static int
11384 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11385 {
11386 	struct adapter *sc = arg1;
11387 	int rc, idx = arg2;
11388 	u_int shift, v, r;
11389 
11390 	MPASS(idx >= 0 && idx < 16);
11391 
11392 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11393 	shift = (idx & 3) << 3;
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, r) >> shift) & M_TIMERBACKOFFINDEX0;
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_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11410 {
11411 	struct vi_info *vi = arg1;
11412 	struct adapter *sc = vi->adapter;
11413 	int idx, rc, i;
11414 	struct sge_ofld_rxq *ofld_rxq;
11415 	uint8_t v;
11416 
11417 	idx = vi->ofld_tmr_idx;
11418 
11419 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11420 	if (rc != 0 || req->newptr == NULL)
11421 		return (rc);
11422 
11423 	if (idx < 0 || idx >= SGE_NTIMERS)
11424 		return (EINVAL);
11425 
11426 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11427 	    "t4otmr");
11428 	if (rc)
11429 		return (rc);
11430 
11431 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11432 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11433 #ifdef atomic_store_rel_8
11434 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11435 #else
11436 		ofld_rxq->iq.intr_params = v;
11437 #endif
11438 	}
11439 	vi->ofld_tmr_idx = idx;
11440 
11441 	end_synchronized_op(sc, LOCK_HELD);
11442 	return (0);
11443 }
11444 
11445 static int
11446 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11447 {
11448 	struct vi_info *vi = arg1;
11449 	struct adapter *sc = vi->adapter;
11450 	int idx, rc;
11451 
11452 	idx = vi->ofld_pktc_idx;
11453 
11454 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11455 	if (rc != 0 || req->newptr == NULL)
11456 		return (rc);
11457 
11458 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11459 		return (EINVAL);
11460 
11461 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11462 	    "t4opktc");
11463 	if (rc)
11464 		return (rc);
11465 
11466 	if (vi->flags & VI_INIT_DONE)
11467 		rc = EBUSY; /* cannot be changed once the queues are created */
11468 	else
11469 		vi->ofld_pktc_idx = idx;
11470 
11471 	end_synchronized_op(sc, LOCK_HELD);
11472 	return (rc);
11473 }
11474 #endif
11475 
11476 static int
11477 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11478 {
11479 	int rc;
11480 
11481 	if (cntxt->cid > M_CTXTQID)
11482 		return (EINVAL);
11483 
11484 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11485 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11486 		return (EINVAL);
11487 
11488 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11489 	if (rc)
11490 		return (rc);
11491 
11492 	if (hw_off_limits(sc)) {
11493 		rc = ENXIO;
11494 		goto done;
11495 	}
11496 
11497 	if (sc->flags & FW_OK) {
11498 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11499 		    &cntxt->data[0]);
11500 		if (rc == 0)
11501 			goto done;
11502 	}
11503 
11504 	/*
11505 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11506 	 * the backdoor.
11507 	 */
11508 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11509 done:
11510 	end_synchronized_op(sc, 0);
11511 	return (rc);
11512 }
11513 
11514 static int
11515 load_fw(struct adapter *sc, struct t4_data *fw)
11516 {
11517 	int rc;
11518 	uint8_t *fw_data;
11519 
11520 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11521 	if (rc)
11522 		return (rc);
11523 
11524 	if (hw_off_limits(sc)) {
11525 		rc = ENXIO;
11526 		goto done;
11527 	}
11528 
11529 	/*
11530 	 * The firmware, with the sole exception of the memory parity error
11531 	 * handler, runs from memory and not flash.  It is almost always safe to
11532 	 * install a new firmware on a running system.  Just set bit 1 in
11533 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11534 	 */
11535 	if (sc->flags & FULL_INIT_DONE &&
11536 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11537 		rc = EBUSY;
11538 		goto done;
11539 	}
11540 
11541 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11542 
11543 	rc = copyin(fw->data, fw_data, fw->len);
11544 	if (rc == 0)
11545 		rc = -t4_load_fw(sc, fw_data, fw->len);
11546 
11547 	free(fw_data, M_CXGBE);
11548 done:
11549 	end_synchronized_op(sc, 0);
11550 	return (rc);
11551 }
11552 
11553 static int
11554 load_cfg(struct adapter *sc, struct t4_data *cfg)
11555 {
11556 	int rc;
11557 	uint8_t *cfg_data = NULL;
11558 
11559 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11560 	if (rc)
11561 		return (rc);
11562 
11563 	if (hw_off_limits(sc)) {
11564 		rc = ENXIO;
11565 		goto done;
11566 	}
11567 
11568 	if (cfg->len == 0) {
11569 		/* clear */
11570 		rc = -t4_load_cfg(sc, NULL, 0);
11571 		goto done;
11572 	}
11573 
11574 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11575 
11576 	rc = copyin(cfg->data, cfg_data, cfg->len);
11577 	if (rc == 0)
11578 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11579 
11580 	free(cfg_data, M_CXGBE);
11581 done:
11582 	end_synchronized_op(sc, 0);
11583 	return (rc);
11584 }
11585 
11586 static int
11587 load_boot(struct adapter *sc, struct t4_bootrom *br)
11588 {
11589 	int rc;
11590 	uint8_t *br_data = NULL;
11591 	u_int offset;
11592 
11593 	if (br->len > 1024 * 1024)
11594 		return (EFBIG);
11595 
11596 	if (br->pf_offset == 0) {
11597 		/* pfidx */
11598 		if (br->pfidx_addr > 7)
11599 			return (EINVAL);
11600 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11601 		    A_PCIE_PF_EXPROM_OFST)));
11602 	} else if (br->pf_offset == 1) {
11603 		/* offset */
11604 		offset = G_OFFSET(br->pfidx_addr);
11605 	} else {
11606 		return (EINVAL);
11607 	}
11608 
11609 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11610 	if (rc)
11611 		return (rc);
11612 
11613 	if (hw_off_limits(sc)) {
11614 		rc = ENXIO;
11615 		goto done;
11616 	}
11617 
11618 	if (br->len == 0) {
11619 		/* clear */
11620 		rc = -t4_load_boot(sc, NULL, offset, 0);
11621 		goto done;
11622 	}
11623 
11624 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11625 
11626 	rc = copyin(br->data, br_data, br->len);
11627 	if (rc == 0)
11628 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11629 
11630 	free(br_data, M_CXGBE);
11631 done:
11632 	end_synchronized_op(sc, 0);
11633 	return (rc);
11634 }
11635 
11636 static int
11637 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11638 {
11639 	int rc;
11640 	uint8_t *bc_data = NULL;
11641 
11642 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11643 	if (rc)
11644 		return (rc);
11645 
11646 	if (hw_off_limits(sc)) {
11647 		rc = ENXIO;
11648 		goto done;
11649 	}
11650 
11651 	if (bc->len == 0) {
11652 		/* clear */
11653 		rc = -t4_load_bootcfg(sc, NULL, 0);
11654 		goto done;
11655 	}
11656 
11657 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11658 
11659 	rc = copyin(bc->data, bc_data, bc->len);
11660 	if (rc == 0)
11661 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11662 
11663 	free(bc_data, M_CXGBE);
11664 done:
11665 	end_synchronized_op(sc, 0);
11666 	return (rc);
11667 }
11668 
11669 static int
11670 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11671 {
11672 	int rc;
11673 	struct cudbg_init *cudbg;
11674 	void *handle, *buf;
11675 
11676 	/* buf is large, don't block if no memory is available */
11677 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11678 	if (buf == NULL)
11679 		return (ENOMEM);
11680 
11681 	handle = cudbg_alloc_handle();
11682 	if (handle == NULL) {
11683 		rc = ENOMEM;
11684 		goto done;
11685 	}
11686 
11687 	cudbg = cudbg_get_init(handle);
11688 	cudbg->adap = sc;
11689 	cudbg->print = (cudbg_print_cb)printf;
11690 
11691 #ifndef notyet
11692 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11693 	    __func__, dump->wr_flash, dump->len, dump->data);
11694 #endif
11695 
11696 	if (dump->wr_flash)
11697 		cudbg->use_flash = 1;
11698 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11699 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11700 
11701 	rc = cudbg_collect(handle, buf, &dump->len);
11702 	if (rc != 0)
11703 		goto done;
11704 
11705 	rc = copyout(buf, dump->data, dump->len);
11706 done:
11707 	cudbg_free_handle(handle);
11708 	free(buf, M_CXGBE);
11709 	return (rc);
11710 }
11711 
11712 static void
11713 free_offload_policy(struct t4_offload_policy *op)
11714 {
11715 	struct offload_rule *r;
11716 	int i;
11717 
11718 	if (op == NULL)
11719 		return;
11720 
11721 	r = &op->rule[0];
11722 	for (i = 0; i < op->nrules; i++, r++) {
11723 		free(r->bpf_prog.bf_insns, M_CXGBE);
11724 	}
11725 	free(op->rule, M_CXGBE);
11726 	free(op, M_CXGBE);
11727 }
11728 
11729 static int
11730 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11731 {
11732 	int i, rc, len;
11733 	struct t4_offload_policy *op, *old;
11734 	struct bpf_program *bf;
11735 	const struct offload_settings *s;
11736 	struct offload_rule *r;
11737 	void *u;
11738 
11739 	if (!is_offload(sc))
11740 		return (ENODEV);
11741 
11742 	if (uop->nrules == 0) {
11743 		/* Delete installed policies. */
11744 		op = NULL;
11745 		goto set_policy;
11746 	} else if (uop->nrules > 256) { /* arbitrary */
11747 		return (E2BIG);
11748 	}
11749 
11750 	/* Copy userspace offload policy to kernel */
11751 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11752 	op->nrules = uop->nrules;
11753 	len = op->nrules * sizeof(struct offload_rule);
11754 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11755 	rc = copyin(uop->rule, op->rule, len);
11756 	if (rc) {
11757 		free(op->rule, M_CXGBE);
11758 		free(op, M_CXGBE);
11759 		return (rc);
11760 	}
11761 
11762 	r = &op->rule[0];
11763 	for (i = 0; i < op->nrules; i++, r++) {
11764 
11765 		/* Validate open_type */
11766 		if (r->open_type != OPEN_TYPE_LISTEN &&
11767 		    r->open_type != OPEN_TYPE_ACTIVE &&
11768 		    r->open_type != OPEN_TYPE_PASSIVE &&
11769 		    r->open_type != OPEN_TYPE_DONTCARE) {
11770 error:
11771 			/*
11772 			 * Rules 0 to i have malloc'd filters that need to be
11773 			 * freed.  Rules i+1 to nrules have userspace pointers
11774 			 * and should be left alone.
11775 			 */
11776 			op->nrules = i;
11777 			free_offload_policy(op);
11778 			return (rc);
11779 		}
11780 
11781 		/* Validate settings */
11782 		s = &r->settings;
11783 		if ((s->offload != 0 && s->offload != 1) ||
11784 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11785 		    s->sched_class < -1 ||
11786 		    s->sched_class >= sc->params.nsched_cls) {
11787 			rc = EINVAL;
11788 			goto error;
11789 		}
11790 
11791 		bf = &r->bpf_prog;
11792 		u = bf->bf_insns;	/* userspace ptr */
11793 		bf->bf_insns = NULL;
11794 		if (bf->bf_len == 0) {
11795 			/* legal, matches everything */
11796 			continue;
11797 		}
11798 		len = bf->bf_len * sizeof(*bf->bf_insns);
11799 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11800 		rc = copyin(u, bf->bf_insns, len);
11801 		if (rc != 0)
11802 			goto error;
11803 
11804 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11805 			rc = EINVAL;
11806 			goto error;
11807 		}
11808 	}
11809 set_policy:
11810 	rw_wlock(&sc->policy_lock);
11811 	old = sc->policy;
11812 	sc->policy = op;
11813 	rw_wunlock(&sc->policy_lock);
11814 	free_offload_policy(old);
11815 
11816 	return (0);
11817 }
11818 
11819 #define MAX_READ_BUF_SIZE (128 * 1024)
11820 static int
11821 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11822 {
11823 	uint32_t addr, remaining, n;
11824 	uint32_t *buf;
11825 	int rc;
11826 	uint8_t *dst;
11827 
11828 	mtx_lock(&sc->reg_lock);
11829 	if (hw_off_limits(sc))
11830 		rc = ENXIO;
11831 	else
11832 		rc = validate_mem_range(sc, mr->addr, mr->len);
11833 	mtx_unlock(&sc->reg_lock);
11834 	if (rc != 0)
11835 		return (rc);
11836 
11837 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11838 	addr = mr->addr;
11839 	remaining = mr->len;
11840 	dst = (void *)mr->data;
11841 
11842 	while (remaining) {
11843 		n = min(remaining, MAX_READ_BUF_SIZE);
11844 		mtx_lock(&sc->reg_lock);
11845 		if (hw_off_limits(sc))
11846 			rc = ENXIO;
11847 		else
11848 			read_via_memwin(sc, 2, addr, buf, n);
11849 		mtx_unlock(&sc->reg_lock);
11850 		if (rc != 0)
11851 			break;
11852 
11853 		rc = copyout(buf, dst, n);
11854 		if (rc != 0)
11855 			break;
11856 
11857 		dst += n;
11858 		remaining -= n;
11859 		addr += n;
11860 	}
11861 
11862 	free(buf, M_CXGBE);
11863 	return (rc);
11864 }
11865 #undef MAX_READ_BUF_SIZE
11866 
11867 static int
11868 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11869 {
11870 	int rc;
11871 
11872 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11873 		return (EINVAL);
11874 
11875 	if (i2cd->len > sizeof(i2cd->data))
11876 		return (EFBIG);
11877 
11878 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11879 	if (rc)
11880 		return (rc);
11881 	if (hw_off_limits(sc))
11882 		rc = ENXIO;
11883 	else
11884 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11885 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11886 	end_synchronized_op(sc, 0);
11887 
11888 	return (rc);
11889 }
11890 
11891 static int
11892 clear_stats(struct adapter *sc, u_int port_id)
11893 {
11894 	int i, v, chan_map;
11895 	struct port_info *pi;
11896 	struct vi_info *vi;
11897 	struct sge_rxq *rxq;
11898 	struct sge_txq *txq;
11899 	struct sge_wrq *wrq;
11900 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11901 	struct sge_ofld_txq *ofld_txq;
11902 #endif
11903 #ifdef TCP_OFFLOAD
11904 	struct sge_ofld_rxq *ofld_rxq;
11905 #endif
11906 
11907 	if (port_id >= sc->params.nports)
11908 		return (EINVAL);
11909 	pi = sc->port[port_id];
11910 	if (pi == NULL)
11911 		return (EIO);
11912 
11913 	mtx_lock(&sc->reg_lock);
11914 	if (!hw_off_limits(sc)) {
11915 		/* MAC stats */
11916 		t4_clr_port_stats(sc, pi->tx_chan);
11917 		if (is_t6(sc)) {
11918 			if (pi->fcs_reg != -1)
11919 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11920 			else
11921 				pi->stats.rx_fcs_err = 0;
11922 		}
11923 		for_each_vi(pi, v, vi) {
11924 			if (vi->flags & VI_INIT_DONE)
11925 				t4_clr_vi_stats(sc, vi->vin);
11926 		}
11927 		chan_map = pi->rx_e_chan_map;
11928 		v = 0;	/* reuse */
11929 		while (chan_map) {
11930 			i = ffs(chan_map) - 1;
11931 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11932 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11933 			chan_map &= ~(1 << i);
11934 		}
11935 	}
11936 	mtx_unlock(&sc->reg_lock);
11937 	pi->tx_parse_error = 0;
11938 	pi->tnl_cong_drops = 0;
11939 
11940 	/*
11941 	 * Since this command accepts a port, clear stats for
11942 	 * all VIs on this port.
11943 	 */
11944 	for_each_vi(pi, v, vi) {
11945 		if (vi->flags & VI_INIT_DONE) {
11946 
11947 			for_each_rxq(vi, i, rxq) {
11948 #if defined(INET) || defined(INET6)
11949 				rxq->lro.lro_queued = 0;
11950 				rxq->lro.lro_flushed = 0;
11951 #endif
11952 				rxq->rxcsum = 0;
11953 				rxq->vlan_extraction = 0;
11954 				rxq->vxlan_rxcsum = 0;
11955 
11956 				rxq->fl.cl_allocated = 0;
11957 				rxq->fl.cl_recycled = 0;
11958 				rxq->fl.cl_fast_recycled = 0;
11959 			}
11960 
11961 			for_each_txq(vi, i, txq) {
11962 				txq->txcsum = 0;
11963 				txq->tso_wrs = 0;
11964 				txq->vlan_insertion = 0;
11965 				txq->imm_wrs = 0;
11966 				txq->sgl_wrs = 0;
11967 				txq->txpkt_wrs = 0;
11968 				txq->txpkts0_wrs = 0;
11969 				txq->txpkts1_wrs = 0;
11970 				txq->txpkts0_pkts = 0;
11971 				txq->txpkts1_pkts = 0;
11972 				txq->txpkts_flush = 0;
11973 				txq->raw_wrs = 0;
11974 				txq->vxlan_tso_wrs = 0;
11975 				txq->vxlan_txcsum = 0;
11976 				txq->kern_tls_records = 0;
11977 				txq->kern_tls_short = 0;
11978 				txq->kern_tls_partial = 0;
11979 				txq->kern_tls_full = 0;
11980 				txq->kern_tls_octets = 0;
11981 				txq->kern_tls_waste = 0;
11982 				txq->kern_tls_options = 0;
11983 				txq->kern_tls_header = 0;
11984 				txq->kern_tls_fin = 0;
11985 				txq->kern_tls_fin_short = 0;
11986 				txq->kern_tls_cbc = 0;
11987 				txq->kern_tls_gcm = 0;
11988 				mp_ring_reset_stats(txq->r);
11989 			}
11990 
11991 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11992 			for_each_ofld_txq(vi, i, ofld_txq) {
11993 				ofld_txq->wrq.tx_wrs_direct = 0;
11994 				ofld_txq->wrq.tx_wrs_copied = 0;
11995 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11996 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11997 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11998 				counter_u64_zero(ofld_txq->tx_aio_jobs);
11999 				counter_u64_zero(ofld_txq->tx_aio_octets);
12000 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12001 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12002 			}
12003 #endif
12004 #ifdef TCP_OFFLOAD
12005 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12006 				ofld_rxq->fl.cl_allocated = 0;
12007 				ofld_rxq->fl.cl_recycled = 0;
12008 				ofld_rxq->fl.cl_fast_recycled = 0;
12009 				counter_u64_zero(
12010 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12011 				counter_u64_zero(
12012 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12013 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12014 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12015 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12016 				ofld_rxq->rx_iscsi_fl_octets = 0;
12017 				ofld_rxq->rx_aio_ddp_jobs = 0;
12018 				ofld_rxq->rx_aio_ddp_octets = 0;
12019 				ofld_rxq->rx_toe_tls_records = 0;
12020 				ofld_rxq->rx_toe_tls_octets = 0;
12021 				ofld_rxq->rx_toe_ddp_octets = 0;
12022 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12023 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12024 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12025 			}
12026 #endif
12027 
12028 			if (IS_MAIN_VI(vi)) {
12029 				wrq = &sc->sge.ctrlq[pi->port_id];
12030 				wrq->tx_wrs_direct = 0;
12031 				wrq->tx_wrs_copied = 0;
12032 			}
12033 		}
12034 	}
12035 
12036 	return (0);
12037 }
12038 
12039 static int
12040 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12041 {
12042 #ifdef INET6
12043 	struct in6_addr in6;
12044 
12045 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12046 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12047 		return (0);
12048 	else
12049 		return (EIO);
12050 #else
12051 	return (ENOTSUP);
12052 #endif
12053 }
12054 
12055 static int
12056 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12057 {
12058 #ifdef INET6
12059 	struct in6_addr in6;
12060 
12061 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12062 	return (t4_release_clip_addr(sc, &in6));
12063 #else
12064 	return (ENOTSUP);
12065 #endif
12066 }
12067 
12068 int
12069 t4_os_find_pci_capability(struct adapter *sc, int cap)
12070 {
12071 	int i;
12072 
12073 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12074 }
12075 
12076 int
12077 t4_os_pci_save_state(struct adapter *sc)
12078 {
12079 	device_t dev;
12080 	struct pci_devinfo *dinfo;
12081 
12082 	dev = sc->dev;
12083 	dinfo = device_get_ivars(dev);
12084 
12085 	pci_cfg_save(dev, dinfo, 0);
12086 	return (0);
12087 }
12088 
12089 int
12090 t4_os_pci_restore_state(struct adapter *sc)
12091 {
12092 	device_t dev;
12093 	struct pci_devinfo *dinfo;
12094 
12095 	dev = sc->dev;
12096 	dinfo = device_get_ivars(dev);
12097 
12098 	pci_cfg_restore(dev, dinfo);
12099 	return (0);
12100 }
12101 
12102 void
12103 t4_os_portmod_changed(struct port_info *pi)
12104 {
12105 	struct adapter *sc = pi->adapter;
12106 	struct vi_info *vi;
12107 	if_t ifp;
12108 	static const char *mod_str[] = {
12109 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12110 	};
12111 
12112 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12113 	    ("%s: port_type %u", __func__, pi->port_type));
12114 
12115 	vi = &pi->vi[0];
12116 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12117 		PORT_LOCK(pi);
12118 		build_medialist(pi);
12119 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12120 			fixup_link_config(pi);
12121 			apply_link_config(pi);
12122 		}
12123 		PORT_UNLOCK(pi);
12124 		end_synchronized_op(sc, LOCK_HELD);
12125 	}
12126 
12127 	ifp = vi->ifp;
12128 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12129 		if_printf(ifp, "transceiver unplugged.\n");
12130 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12131 		if_printf(ifp, "unknown transceiver inserted.\n");
12132 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12133 		if_printf(ifp, "unsupported transceiver inserted.\n");
12134 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12135 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12136 		    port_top_speed(pi), mod_str[pi->mod_type]);
12137 	} else {
12138 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12139 		    pi->mod_type);
12140 	}
12141 }
12142 
12143 void
12144 t4_os_link_changed(struct port_info *pi)
12145 {
12146 	struct vi_info *vi;
12147 	if_t ifp;
12148 	struct link_config *lc = &pi->link_cfg;
12149 	struct adapter *sc = pi->adapter;
12150 	int v;
12151 
12152 	PORT_LOCK_ASSERT_OWNED(pi);
12153 
12154 	if (is_t6(sc)) {
12155 		if (lc->link_ok) {
12156 			if (lc->speed > 25000 ||
12157 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12158 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12159 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12160 			} else {
12161 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12162 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12163 			}
12164 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12165 			pi->stats.rx_fcs_err = 0;
12166 		} else {
12167 			pi->fcs_reg = -1;
12168 		}
12169 	} else {
12170 		MPASS(pi->fcs_reg != -1);
12171 		MPASS(pi->fcs_base == 0);
12172 	}
12173 
12174 	for_each_vi(pi, v, vi) {
12175 		ifp = vi->ifp;
12176 		if (ifp == NULL || IS_DETACHING(vi))
12177 			continue;
12178 
12179 		if (lc->link_ok) {
12180 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12181 			if_link_state_change(ifp, LINK_STATE_UP);
12182 		} else {
12183 			if_link_state_change(ifp, LINK_STATE_DOWN);
12184 		}
12185 	}
12186 }
12187 
12188 void
12189 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12190 {
12191 	struct adapter *sc;
12192 
12193 	sx_slock(&t4_list_lock);
12194 	SLIST_FOREACH(sc, &t4_list, link) {
12195 		/*
12196 		 * func should not make any assumptions about what state sc is
12197 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12198 		 */
12199 		func(sc, arg);
12200 	}
12201 	sx_sunlock(&t4_list_lock);
12202 }
12203 
12204 static int
12205 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12206     struct thread *td)
12207 {
12208 	int rc;
12209 	struct adapter *sc = dev->si_drv1;
12210 
12211 	rc = priv_check(td, PRIV_DRIVER);
12212 	if (rc != 0)
12213 		return (rc);
12214 
12215 	switch (cmd) {
12216 	case CHELSIO_T4_GETREG: {
12217 		struct t4_reg *edata = (struct t4_reg *)data;
12218 
12219 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12220 			return (EFAULT);
12221 
12222 		mtx_lock(&sc->reg_lock);
12223 		if (hw_off_limits(sc))
12224 			rc = ENXIO;
12225 		else if (edata->size == 4)
12226 			edata->val = t4_read_reg(sc, edata->addr);
12227 		else if (edata->size == 8)
12228 			edata->val = t4_read_reg64(sc, edata->addr);
12229 		else
12230 			rc = EINVAL;
12231 		mtx_unlock(&sc->reg_lock);
12232 
12233 		break;
12234 	}
12235 	case CHELSIO_T4_SETREG: {
12236 		struct t4_reg *edata = (struct t4_reg *)data;
12237 
12238 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12239 			return (EFAULT);
12240 
12241 		mtx_lock(&sc->reg_lock);
12242 		if (hw_off_limits(sc))
12243 			rc = ENXIO;
12244 		else if (edata->size == 4) {
12245 			if (edata->val & 0xffffffff00000000)
12246 				rc = EINVAL;
12247 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12248 		} else if (edata->size == 8)
12249 			t4_write_reg64(sc, edata->addr, edata->val);
12250 		else
12251 			rc = EINVAL;
12252 		mtx_unlock(&sc->reg_lock);
12253 
12254 		break;
12255 	}
12256 	case CHELSIO_T4_REGDUMP: {
12257 		struct t4_regdump *regs = (struct t4_regdump *)data;
12258 		int reglen = t4_get_regs_len(sc);
12259 		uint8_t *buf;
12260 
12261 		if (regs->len < reglen) {
12262 			regs->len = reglen; /* hint to the caller */
12263 			return (ENOBUFS);
12264 		}
12265 
12266 		regs->len = reglen;
12267 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12268 		mtx_lock(&sc->reg_lock);
12269 		if (hw_off_limits(sc))
12270 			rc = ENXIO;
12271 		else
12272 			get_regs(sc, regs, buf);
12273 		mtx_unlock(&sc->reg_lock);
12274 		if (rc == 0)
12275 			rc = copyout(buf, regs->data, reglen);
12276 		free(buf, M_CXGBE);
12277 		break;
12278 	}
12279 	case CHELSIO_T4_GET_FILTER_MODE:
12280 		rc = get_filter_mode(sc, (uint32_t *)data);
12281 		break;
12282 	case CHELSIO_T4_SET_FILTER_MODE:
12283 		rc = set_filter_mode(sc, *(uint32_t *)data);
12284 		break;
12285 	case CHELSIO_T4_SET_FILTER_MASK:
12286 		rc = set_filter_mask(sc, *(uint32_t *)data);
12287 		break;
12288 	case CHELSIO_T4_GET_FILTER:
12289 		rc = get_filter(sc, (struct t4_filter *)data);
12290 		break;
12291 	case CHELSIO_T4_SET_FILTER:
12292 		rc = set_filter(sc, (struct t4_filter *)data);
12293 		break;
12294 	case CHELSIO_T4_DEL_FILTER:
12295 		rc = del_filter(sc, (struct t4_filter *)data);
12296 		break;
12297 	case CHELSIO_T4_GET_SGE_CONTEXT:
12298 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12299 		break;
12300 	case CHELSIO_T4_LOAD_FW:
12301 		rc = load_fw(sc, (struct t4_data *)data);
12302 		break;
12303 	case CHELSIO_T4_GET_MEM:
12304 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12305 		break;
12306 	case CHELSIO_T4_GET_I2C:
12307 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12308 		break;
12309 	case CHELSIO_T4_CLEAR_STATS:
12310 		rc = clear_stats(sc, *(uint32_t *)data);
12311 		break;
12312 	case CHELSIO_T4_SCHED_CLASS:
12313 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12314 		break;
12315 	case CHELSIO_T4_SCHED_QUEUE:
12316 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12317 		break;
12318 	case CHELSIO_T4_GET_TRACER:
12319 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12320 		break;
12321 	case CHELSIO_T4_SET_TRACER:
12322 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12323 		break;
12324 	case CHELSIO_T4_LOAD_CFG:
12325 		rc = load_cfg(sc, (struct t4_data *)data);
12326 		break;
12327 	case CHELSIO_T4_LOAD_BOOT:
12328 		rc = load_boot(sc, (struct t4_bootrom *)data);
12329 		break;
12330 	case CHELSIO_T4_LOAD_BOOTCFG:
12331 		rc = load_bootcfg(sc, (struct t4_data *)data);
12332 		break;
12333 	case CHELSIO_T4_CUDBG_DUMP:
12334 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12335 		break;
12336 	case CHELSIO_T4_SET_OFLD_POLICY:
12337 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12338 		break;
12339 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12340 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12341 		break;
12342 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12343 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12344 		break;
12345 	default:
12346 		rc = ENOTTY;
12347 	}
12348 
12349 	return (rc);
12350 }
12351 
12352 #ifdef TCP_OFFLOAD
12353 static int
12354 toe_capability(struct vi_info *vi, bool enable)
12355 {
12356 	int rc;
12357 	struct port_info *pi = vi->pi;
12358 	struct adapter *sc = pi->adapter;
12359 
12360 	ASSERT_SYNCHRONIZED_OP(sc);
12361 
12362 	if (!is_offload(sc))
12363 		return (ENODEV);
12364 	if (hw_off_limits(sc))
12365 		return (ENXIO);
12366 
12367 	if (enable) {
12368 #ifdef KERN_TLS
12369 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12370 			int i, j, n;
12371 			struct port_info *p;
12372 			struct vi_info *v;
12373 
12374 			/*
12375 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12376 			 * on any ifnet.
12377 			 */
12378 			n = 0;
12379 			for_each_port(sc, i) {
12380 				p = sc->port[i];
12381 				for_each_vi(p, j, v) {
12382 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12383 						CH_WARN(sc,
12384 						    "%s has NIC TLS enabled.\n",
12385 						    device_get_nameunit(v->dev));
12386 						n++;
12387 					}
12388 				}
12389 			}
12390 			if (n > 0) {
12391 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12392 				    "associated with this adapter before "
12393 				    "trying to enable TOE.\n");
12394 				return (EAGAIN);
12395 			}
12396 			rc = t6_config_kern_tls(sc, false);
12397 			if (rc)
12398 				return (rc);
12399 		}
12400 #endif
12401 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12402 			/* TOE is already enabled. */
12403 			return (0);
12404 		}
12405 
12406 		/*
12407 		 * We need the port's queues around so that we're able to send
12408 		 * and receive CPLs to/from the TOE even if the ifnet for this
12409 		 * port has never been UP'd administratively.
12410 		 */
12411 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12412 			return (rc);
12413 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12414 		    ((rc = vi_init(&pi->vi[0])) != 0))
12415 			return (rc);
12416 
12417 		if (isset(&sc->offload_map, pi->port_id)) {
12418 			/* TOE is enabled on another VI of this port. */
12419 			pi->uld_vis++;
12420 			return (0);
12421 		}
12422 
12423 		if (!uld_active(sc, ULD_TOM)) {
12424 			rc = t4_activate_uld(sc, ULD_TOM);
12425 			if (rc == EAGAIN) {
12426 				log(LOG_WARNING,
12427 				    "You must kldload t4_tom.ko before trying "
12428 				    "to enable TOE on a cxgbe interface.\n");
12429 			}
12430 			if (rc != 0)
12431 				return (rc);
12432 			KASSERT(sc->tom_softc != NULL,
12433 			    ("%s: TOM activated but softc NULL", __func__));
12434 			KASSERT(uld_active(sc, ULD_TOM),
12435 			    ("%s: TOM activated but flag not set", __func__));
12436 		}
12437 
12438 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12439 		if (!uld_active(sc, ULD_IWARP))
12440 			(void) t4_activate_uld(sc, ULD_IWARP);
12441 		if (!uld_active(sc, ULD_ISCSI))
12442 			(void) t4_activate_uld(sc, ULD_ISCSI);
12443 
12444 		pi->uld_vis++;
12445 		setbit(&sc->offload_map, pi->port_id);
12446 	} else {
12447 		pi->uld_vis--;
12448 
12449 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12450 			return (0);
12451 
12452 		KASSERT(uld_active(sc, ULD_TOM),
12453 		    ("%s: TOM never initialized?", __func__));
12454 		clrbit(&sc->offload_map, pi->port_id);
12455 	}
12456 
12457 	return (0);
12458 }
12459 
12460 /*
12461  * Add an upper layer driver to the global list.
12462  */
12463 int
12464 t4_register_uld(struct uld_info *ui, int id)
12465 {
12466 	int rc;
12467 
12468 	if (id < 0 || id > ULD_MAX)
12469 		return (EINVAL);
12470 	sx_xlock(&t4_uld_list_lock);
12471 	if (t4_uld_list[id] != NULL)
12472 		rc = EEXIST;
12473 	else {
12474 		t4_uld_list[id] = ui;
12475 		rc = 0;
12476 	}
12477 	sx_xunlock(&t4_uld_list_lock);
12478 	return (rc);
12479 }
12480 
12481 int
12482 t4_unregister_uld(struct uld_info *ui, int id)
12483 {
12484 
12485 	if (id < 0 || id > ULD_MAX)
12486 		return (EINVAL);
12487 	sx_xlock(&t4_uld_list_lock);
12488 	MPASS(t4_uld_list[id] == ui);
12489 	t4_uld_list[id] = NULL;
12490 	sx_xunlock(&t4_uld_list_lock);
12491 	return (0);
12492 }
12493 
12494 int
12495 t4_activate_uld(struct adapter *sc, int id)
12496 {
12497 	int rc;
12498 
12499 	ASSERT_SYNCHRONIZED_OP(sc);
12500 
12501 	if (id < 0 || id > ULD_MAX)
12502 		return (EINVAL);
12503 
12504 	/* Adapter needs to be initialized before any ULD can be activated. */
12505 	if (!(sc->flags & FULL_INIT_DONE)) {
12506 		rc = adapter_init(sc);
12507 		if (rc != 0)
12508 			return (rc);
12509 	}
12510 
12511 	sx_slock(&t4_uld_list_lock);
12512 	if (t4_uld_list[id] == NULL)
12513 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
12514 	else {
12515 		rc = t4_uld_list[id]->uld_activate(sc);
12516 		if (rc == 0)
12517 			setbit(&sc->active_ulds, id);
12518 	}
12519 	sx_sunlock(&t4_uld_list_lock);
12520 
12521 	return (rc);
12522 }
12523 
12524 int
12525 t4_deactivate_uld(struct adapter *sc, int id)
12526 {
12527 	int rc;
12528 
12529 	ASSERT_SYNCHRONIZED_OP(sc);
12530 
12531 	if (id < 0 || id > ULD_MAX)
12532 		return (EINVAL);
12533 
12534 	sx_slock(&t4_uld_list_lock);
12535 	if (t4_uld_list[id] == NULL)
12536 		rc = ENXIO;
12537 	else {
12538 		rc = t4_uld_list[id]->uld_deactivate(sc);
12539 		if (rc == 0)
12540 			clrbit(&sc->active_ulds, id);
12541 	}
12542 	sx_sunlock(&t4_uld_list_lock);
12543 
12544 	return (rc);
12545 }
12546 
12547 static int
12548 deactivate_all_uld(struct adapter *sc)
12549 {
12550 	int i, rc;
12551 
12552 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12553 	if (rc != 0)
12554 		return (ENXIO);
12555 	sx_slock(&t4_uld_list_lock);
12556 	for (i = 0; i <= ULD_MAX; i++) {
12557 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
12558 			continue;
12559 		rc = t4_uld_list[i]->uld_deactivate(sc);
12560 		if (rc != 0)
12561 			break;
12562 		clrbit(&sc->active_ulds, i);
12563 	}
12564 	sx_sunlock(&t4_uld_list_lock);
12565 	end_synchronized_op(sc, 0);
12566 
12567 	return (rc);
12568 }
12569 
12570 static void
12571 stop_all_uld(struct adapter *sc)
12572 {
12573 	int i;
12574 
12575 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
12576 		return;
12577 	sx_slock(&t4_uld_list_lock);
12578 	for (i = 0; i <= ULD_MAX; i++) {
12579 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12580 		    t4_uld_list[i]->uld_stop == NULL)
12581 			continue;
12582 		(void) t4_uld_list[i]->uld_stop(sc);
12583 	}
12584 	sx_sunlock(&t4_uld_list_lock);
12585 	end_synchronized_op(sc, 0);
12586 }
12587 
12588 static void
12589 restart_all_uld(struct adapter *sc)
12590 {
12591 	int i;
12592 
12593 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 0)
12594 		return;
12595 	sx_slock(&t4_uld_list_lock);
12596 	for (i = 0; i <= ULD_MAX; i++) {
12597 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12598 		    t4_uld_list[i]->uld_restart == NULL)
12599 			continue;
12600 		(void) t4_uld_list[i]->uld_restart(sc);
12601 	}
12602 	sx_sunlock(&t4_uld_list_lock);
12603 	end_synchronized_op(sc, 0);
12604 }
12605 
12606 int
12607 uld_active(struct adapter *sc, int id)
12608 {
12609 
12610 	MPASS(id >= 0 && id <= ULD_MAX);
12611 
12612 	return (isset(&sc->active_ulds, id));
12613 }
12614 #endif
12615 
12616 #ifdef KERN_TLS
12617 static int
12618 ktls_capability(struct adapter *sc, bool enable)
12619 {
12620 	ASSERT_SYNCHRONIZED_OP(sc);
12621 
12622 	if (!is_ktls(sc))
12623 		return (ENODEV);
12624 	if (!is_t6(sc))
12625 		return (0);
12626 	if (hw_off_limits(sc))
12627 		return (ENXIO);
12628 
12629 	if (enable) {
12630 		if (sc->flags & KERN_TLS_ON)
12631 			return (0);	/* already on */
12632 		if (sc->offload_map != 0) {
12633 			CH_WARN(sc,
12634 			    "Disable TOE on all interfaces associated with "
12635 			    "this adapter before trying to enable NIC TLS.\n");
12636 			return (EAGAIN);
12637 		}
12638 		return (t6_config_kern_tls(sc, true));
12639 	} else {
12640 		/*
12641 		 * Nothing to do for disable.  If TOE is enabled sometime later
12642 		 * then toe_capability will reconfigure the hardware.
12643 		 */
12644 		return (0);
12645 	}
12646 }
12647 #endif
12648 
12649 /*
12650  * t  = ptr to tunable.
12651  * nc = number of CPUs.
12652  * c  = compiled in default for that tunable.
12653  */
12654 static void
12655 calculate_nqueues(int *t, int nc, const int c)
12656 {
12657 	int nq;
12658 
12659 	if (*t > 0)
12660 		return;
12661 	nq = *t < 0 ? -*t : c;
12662 	*t = min(nc, nq);
12663 }
12664 
12665 /*
12666  * Come up with reasonable defaults for some of the tunables, provided they're
12667  * not set by the user (in which case we'll use the values as is).
12668  */
12669 static void
12670 tweak_tunables(void)
12671 {
12672 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12673 
12674 	if (t4_ntxq < 1) {
12675 #ifdef RSS
12676 		t4_ntxq = rss_getnumbuckets();
12677 #else
12678 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12679 #endif
12680 	}
12681 
12682 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12683 
12684 	if (t4_nrxq < 1) {
12685 #ifdef RSS
12686 		t4_nrxq = rss_getnumbuckets();
12687 #else
12688 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12689 #endif
12690 	}
12691 
12692 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12693 
12694 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12695 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12696 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12697 #endif
12698 #ifdef TCP_OFFLOAD
12699 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12700 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12701 #endif
12702 
12703 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12704 	if (t4_toecaps_allowed == -1)
12705 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12706 #else
12707 	if (t4_toecaps_allowed == -1)
12708 		t4_toecaps_allowed = 0;
12709 #endif
12710 
12711 #ifdef TCP_OFFLOAD
12712 	if (t4_rdmacaps_allowed == -1) {
12713 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12714 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12715 	}
12716 
12717 	if (t4_iscsicaps_allowed == -1) {
12718 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12719 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12720 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12721 	}
12722 
12723 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12724 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12725 
12726 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12727 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12728 #else
12729 	if (t4_rdmacaps_allowed == -1)
12730 		t4_rdmacaps_allowed = 0;
12731 
12732 	if (t4_iscsicaps_allowed == -1)
12733 		t4_iscsicaps_allowed = 0;
12734 #endif
12735 
12736 #ifdef DEV_NETMAP
12737 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12738 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12739 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12740 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12741 #endif
12742 
12743 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12744 		t4_tmr_idx = TMR_IDX;
12745 
12746 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12747 		t4_pktc_idx = PKTC_IDX;
12748 
12749 	if (t4_qsize_txq < 128)
12750 		t4_qsize_txq = 128;
12751 
12752 	if (t4_qsize_rxq < 128)
12753 		t4_qsize_rxq = 128;
12754 	while (t4_qsize_rxq & 7)
12755 		t4_qsize_rxq++;
12756 
12757 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12758 
12759 	/*
12760 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12761 	 * VI for the port.  The rest are additional virtual interfaces on the
12762 	 * same physical port.  Note that the main VI does not have native
12763 	 * netmap support but the extra VIs do.
12764 	 *
12765 	 * Limit the number of VIs per port to the number of available
12766 	 * MAC addresses per port.
12767 	 */
12768 	if (t4_num_vis < 1)
12769 		t4_num_vis = 1;
12770 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12771 		t4_num_vis = nitems(vi_mac_funcs);
12772 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12773 	}
12774 
12775 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12776 		pcie_relaxed_ordering = 1;
12777 #if defined(__i386__) || defined(__amd64__)
12778 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12779 			pcie_relaxed_ordering = 0;
12780 #endif
12781 	}
12782 }
12783 
12784 #ifdef DDB
12785 static void
12786 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
12787 {
12788 	uint32_t base, j, off, pf, reg, save, win_pos;
12789 
12790 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12791 	save = t4_read_reg(sc, reg);
12792 	base = sc->memwin[2].mw_base;
12793 
12794 	if (is_t4(sc)) {
12795 		pf = 0;
12796 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
12797 	} else {
12798 		pf = V_PFNUM(sc->pf);
12799 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
12800 	}
12801 	off = addr - win_pos;
12802 	t4_write_reg(sc, reg, win_pos | pf);
12803 	t4_read_reg(sc, reg);
12804 
12805 	while (len > 0 && !db_pager_quit) {
12806 		uint32_t buf[8];
12807 		for (j = 0; j < 8; j++, off += 4)
12808 			buf[j] = htonl(t4_read_reg(sc, base + off));
12809 
12810 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12811 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12812 		    buf[7]);
12813 		if (len <= sizeof(buf))
12814 			len = 0;
12815 		else
12816 			len -= sizeof(buf);
12817 	}
12818 
12819 	t4_write_reg(sc, reg, save);
12820 	t4_read_reg(sc, reg);
12821 }
12822 
12823 static void
12824 t4_dump_tcb(struct adapter *sc, int tid)
12825 {
12826 	uint32_t tcb_addr;
12827 
12828 	/* Dump TCB for the tid */
12829 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12830 	tcb_addr += tid * TCB_SIZE;
12831 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
12832 }
12833 
12834 static void
12835 t4_dump_devlog(struct adapter *sc)
12836 {
12837 	struct devlog_params *dparams = &sc->params.devlog;
12838 	struct fw_devlog_e e;
12839 	int i, first, j, m, nentries, rc;
12840 	uint64_t ftstamp = UINT64_MAX;
12841 
12842 	if (dparams->start == 0) {
12843 		db_printf("devlog params not valid\n");
12844 		return;
12845 	}
12846 
12847 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12848 	m = fwmtype_to_hwmtype(dparams->memtype);
12849 
12850 	/* Find the first entry. */
12851 	first = -1;
12852 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12853 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12854 		    sizeof(e), (void *)&e);
12855 		if (rc != 0)
12856 			break;
12857 
12858 		if (e.timestamp == 0)
12859 			break;
12860 
12861 		e.timestamp = be64toh(e.timestamp);
12862 		if (e.timestamp < ftstamp) {
12863 			ftstamp = e.timestamp;
12864 			first = i;
12865 		}
12866 	}
12867 
12868 	if (first == -1)
12869 		return;
12870 
12871 	i = first;
12872 	do {
12873 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12874 		    sizeof(e), (void *)&e);
12875 		if (rc != 0)
12876 			return;
12877 
12878 		if (e.timestamp == 0)
12879 			return;
12880 
12881 		e.timestamp = be64toh(e.timestamp);
12882 		e.seqno = be32toh(e.seqno);
12883 		for (j = 0; j < 8; j++)
12884 			e.params[j] = be32toh(e.params[j]);
12885 
12886 		db_printf("%10d  %15ju  %8s  %8s  ",
12887 		    e.seqno, e.timestamp,
12888 		    (e.level < nitems(devlog_level_strings) ?
12889 			devlog_level_strings[e.level] : "UNKNOWN"),
12890 		    (e.facility < nitems(devlog_facility_strings) ?
12891 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12892 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12893 		    e.params[3], e.params[4], e.params[5], e.params[6],
12894 		    e.params[7]);
12895 
12896 		if (++i == nentries)
12897 			i = 0;
12898 	} while (i != first && !db_pager_quit);
12899 }
12900 
12901 static DB_DEFINE_TABLE(show, t4, show_t4);
12902 
12903 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12904 {
12905 	device_t dev;
12906 	int t;
12907 	bool valid;
12908 
12909 	valid = false;
12910 	t = db_read_token();
12911 	if (t == tIDENT) {
12912 		dev = device_lookup_by_name(db_tok_string);
12913 		valid = true;
12914 	}
12915 	db_skip_to_eol();
12916 	if (!valid) {
12917 		db_printf("usage: show t4 devlog <nexus>\n");
12918 		return;
12919 	}
12920 
12921 	if (dev == NULL) {
12922 		db_printf("device not found\n");
12923 		return;
12924 	}
12925 
12926 	t4_dump_devlog(device_get_softc(dev));
12927 }
12928 
12929 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12930 {
12931 	device_t dev;
12932 	int radix, tid, t;
12933 	bool valid;
12934 
12935 	valid = false;
12936 	radix = db_radix;
12937 	db_radix = 10;
12938 	t = db_read_token();
12939 	if (t == tIDENT) {
12940 		dev = device_lookup_by_name(db_tok_string);
12941 		t = db_read_token();
12942 		if (t == tNUMBER) {
12943 			tid = db_tok_number;
12944 			valid = true;
12945 		}
12946 	}
12947 	db_radix = radix;
12948 	db_skip_to_eol();
12949 	if (!valid) {
12950 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12951 		return;
12952 	}
12953 
12954 	if (dev == NULL) {
12955 		db_printf("device not found\n");
12956 		return;
12957 	}
12958 	if (tid < 0) {
12959 		db_printf("invalid tid\n");
12960 		return;
12961 	}
12962 
12963 	t4_dump_tcb(device_get_softc(dev), tid);
12964 }
12965 
12966 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
12967 {
12968 	device_t dev;
12969 	int radix, t;
12970 	bool valid;
12971 
12972 	valid = false;
12973 	radix = db_radix;
12974 	db_radix = 10;
12975 	t = db_read_token();
12976 	if (t == tIDENT) {
12977 		dev = device_lookup_by_name(db_tok_string);
12978 		t = db_read_token();
12979 		if (t == tNUMBER) {
12980 			addr = db_tok_number;
12981 			t = db_read_token();
12982 			if (t == tNUMBER) {
12983 				count = db_tok_number;
12984 				valid = true;
12985 			}
12986 		}
12987 	}
12988 	db_radix = radix;
12989 	db_skip_to_eol();
12990 	if (!valid) {
12991 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
12992 		return;
12993 	}
12994 
12995 	if (dev == NULL) {
12996 		db_printf("device not found\n");
12997 		return;
12998 	}
12999 	if (addr < 0) {
13000 		db_printf("invalid address\n");
13001 		return;
13002 	}
13003 	if (count <= 0) {
13004 		db_printf("invalid length\n");
13005 		return;
13006 	}
13007 
13008 	t4_dump_mem(device_get_softc(dev), addr, count);
13009 }
13010 #endif
13011 
13012 static eventhandler_tag vxlan_start_evtag;
13013 static eventhandler_tag vxlan_stop_evtag;
13014 
13015 struct vxlan_evargs {
13016 	if_t ifp;
13017 	uint16_t port;
13018 };
13019 
13020 static void
13021 enable_vxlan_rx(struct adapter *sc)
13022 {
13023 	int i, rc;
13024 	struct port_info *pi;
13025 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13026 
13027 	ASSERT_SYNCHRONIZED_OP(sc);
13028 
13029 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13030 	    F_VXLAN_EN);
13031 	for_each_port(sc, i) {
13032 		pi = sc->port[i];
13033 		if (pi->vxlan_tcam_entry == true)
13034 			continue;
13035 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13036 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13037 		    true);
13038 		if (rc < 0) {
13039 			rc = -rc;
13040 			CH_ERR(&pi->vi[0],
13041 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13042 		} else {
13043 			MPASS(rc == sc->rawf_base + pi->port_id);
13044 			pi->vxlan_tcam_entry = true;
13045 		}
13046 	}
13047 }
13048 
13049 static void
13050 t4_vxlan_start(struct adapter *sc, void *arg)
13051 {
13052 	struct vxlan_evargs *v = arg;
13053 
13054 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13055 		return;
13056 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13057 		return;
13058 
13059 	if (sc->vxlan_refcount == 0) {
13060 		sc->vxlan_port = v->port;
13061 		sc->vxlan_refcount = 1;
13062 		if (!hw_off_limits(sc))
13063 			enable_vxlan_rx(sc);
13064 	} else if (sc->vxlan_port == v->port) {
13065 		sc->vxlan_refcount++;
13066 	} else {
13067 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13068 		    "ignoring attempt to configure it on port %d\n",
13069 		    sc->vxlan_port, v->port);
13070 	}
13071 	end_synchronized_op(sc, 0);
13072 }
13073 
13074 static void
13075 t4_vxlan_stop(struct adapter *sc, void *arg)
13076 {
13077 	struct vxlan_evargs *v = arg;
13078 
13079 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13080 		return;
13081 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13082 		return;
13083 
13084 	/*
13085 	 * VXLANs may have been configured before the driver was loaded so we
13086 	 * may see more stops than starts.  This is not handled cleanly but at
13087 	 * least we keep the refcount sane.
13088 	 */
13089 	if (sc->vxlan_port != v->port)
13090 		goto done;
13091 	if (sc->vxlan_refcount == 0) {
13092 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13093 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13094 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13095 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13096 done:
13097 	end_synchronized_op(sc, 0);
13098 }
13099 
13100 static void
13101 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13102     sa_family_t family, u_int port)
13103 {
13104 	struct vxlan_evargs v;
13105 
13106 	MPASS(family == AF_INET || family == AF_INET6);
13107 	v.ifp = ifp;
13108 	v.port = port;
13109 
13110 	t4_iterate(t4_vxlan_start, &v);
13111 }
13112 
13113 static void
13114 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13115     u_int port)
13116 {
13117 	struct vxlan_evargs v;
13118 
13119 	MPASS(family == AF_INET || family == AF_INET6);
13120 	v.ifp = ifp;
13121 	v.port = port;
13122 
13123 	t4_iterate(t4_vxlan_stop, &v);
13124 }
13125 
13126 
13127 static struct sx mlu;	/* mod load unload */
13128 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13129 
13130 static int
13131 mod_event(module_t mod, int cmd, void *arg)
13132 {
13133 	int rc = 0;
13134 	static int loaded = 0;
13135 
13136 	switch (cmd) {
13137 	case MOD_LOAD:
13138 		sx_xlock(&mlu);
13139 		if (loaded++ == 0) {
13140 			t4_sge_modload();
13141 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13142 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13143 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13144 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13145 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13146 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13147 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13148 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13149 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13150 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13151 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13152 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13153 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13154 			    do_smt_write_rpl);
13155 			sx_init(&t4_list_lock, "T4/T5 adapters");
13156 			SLIST_INIT(&t4_list);
13157 			callout_init(&fatal_callout, 1);
13158 #ifdef TCP_OFFLOAD
13159 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13160 #endif
13161 #ifdef INET6
13162 			t4_clip_modload();
13163 #endif
13164 #ifdef KERN_TLS
13165 			t6_ktls_modload();
13166 #endif
13167 			t4_tracer_modload();
13168 			tweak_tunables();
13169 			vxlan_start_evtag =
13170 			    EVENTHANDLER_REGISTER(vxlan_start,
13171 				t4_vxlan_start_handler, NULL,
13172 				EVENTHANDLER_PRI_ANY);
13173 			vxlan_stop_evtag =
13174 			    EVENTHANDLER_REGISTER(vxlan_stop,
13175 				t4_vxlan_stop_handler, NULL,
13176 				EVENTHANDLER_PRI_ANY);
13177 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13178 			    taskqueue_thread_enqueue, &reset_tq);
13179 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13180 			    "t4_rst_thr");
13181 		}
13182 		sx_xunlock(&mlu);
13183 		break;
13184 
13185 	case MOD_UNLOAD:
13186 		sx_xlock(&mlu);
13187 		if (--loaded == 0) {
13188 #ifdef TCP_OFFLOAD
13189 			int i;
13190 #endif
13191 			int tries;
13192 
13193 			taskqueue_free(reset_tq);
13194 
13195 			tries = 0;
13196 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13197 				uprintf("%ju clusters with custom free routine "
13198 				    "still is use.\n", t4_sge_extfree_refs());
13199 				pause("t4unload", 2 * hz);
13200 			}
13201 
13202 			sx_slock(&t4_list_lock);
13203 			if (!SLIST_EMPTY(&t4_list)) {
13204 				rc = EBUSY;
13205 				sx_sunlock(&t4_list_lock);
13206 				goto done_unload;
13207 			}
13208 #ifdef TCP_OFFLOAD
13209 			sx_slock(&t4_uld_list_lock);
13210 			for (i = 0; i <= ULD_MAX; i++) {
13211 				if (t4_uld_list[i] != NULL) {
13212 					rc = EBUSY;
13213 					sx_sunlock(&t4_uld_list_lock);
13214 					sx_sunlock(&t4_list_lock);
13215 					goto done_unload;
13216 				}
13217 			}
13218 			sx_sunlock(&t4_uld_list_lock);
13219 #endif
13220 			sx_sunlock(&t4_list_lock);
13221 
13222 			if (t4_sge_extfree_refs() == 0) {
13223 				EVENTHANDLER_DEREGISTER(vxlan_start,
13224 				    vxlan_start_evtag);
13225 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13226 				    vxlan_stop_evtag);
13227 				t4_tracer_modunload();
13228 #ifdef KERN_TLS
13229 				t6_ktls_modunload();
13230 #endif
13231 #ifdef INET6
13232 				t4_clip_modunload();
13233 #endif
13234 #ifdef TCP_OFFLOAD
13235 				sx_destroy(&t4_uld_list_lock);
13236 #endif
13237 				sx_destroy(&t4_list_lock);
13238 				t4_sge_modunload();
13239 				loaded = 0;
13240 			} else {
13241 				rc = EBUSY;
13242 				loaded++;	/* undo earlier decrement */
13243 			}
13244 		}
13245 done_unload:
13246 		sx_xunlock(&mlu);
13247 		break;
13248 	}
13249 
13250 	return (rc);
13251 }
13252 
13253 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13254 MODULE_VERSION(t4nex, 1);
13255 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13256 #ifdef DEV_NETMAP
13257 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13258 #endif /* DEV_NETMAP */
13259 
13260 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13261 MODULE_VERSION(t5nex, 1);
13262 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13263 #ifdef DEV_NETMAP
13264 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13265 #endif /* DEV_NETMAP */
13266 
13267 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13268 MODULE_VERSION(t6nex, 1);
13269 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13270 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13271 #ifdef DEV_NETMAP
13272 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13273 #endif /* DEV_NETMAP */
13274 
13275 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13276 MODULE_VERSION(cxgbe, 1);
13277 
13278 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13279 MODULE_VERSION(cxl, 1);
13280 
13281 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13282 MODULE_VERSION(cc, 1);
13283 
13284 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13285 MODULE_VERSION(vcxgbe, 1);
13286 
13287 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13288 MODULE_VERSION(vcxl, 1);
13289 
13290 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13291 MODULE_VERSION(vcc, 1);
13292