xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision 357378bbdedf24ce2b90e9bd831af4a9db3ec70a)
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 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2064 			}
2065 #endif
2066 			for_each_rxq(vi, k, rxq) {
2067 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2068 			}
2069 #if defined(TCP_OFFLOAD)
2070 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2071 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2072 			}
2073 #endif
2074 
2075 			quiesce_vi(vi);
2076 		}
2077 
2078 		if (sc->flags & FULL_INIT_DONE) {
2079 			/* Control queue */
2080 			wrq = &sc->sge.ctrlq[i];
2081 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2082 			quiesce_wrq(wrq);
2083 		}
2084 	}
2085 	if (sc->flags & FULL_INIT_DONE) {
2086 		/* Firmware event queue */
2087 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2088 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2089 	}
2090 
2091 	/* Stop calibration */
2092 	callout_stop(&sc->cal_callout);
2093 	callout_drain(&sc->cal_callout);
2094 
2095 	if (t4_clock_gate_on_suspend) {
2096 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2097 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2098 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2099 	}
2100 
2101 	end_synchronized_op(sc, 0);
2102 
2103 	stop_atid_allocator(sc);
2104 	t4_stop_l2t(sc);
2105 
2106 	return (rc);
2107 }
2108 
2109 static int
2110 t4_suspend(device_t dev)
2111 {
2112 	struct adapter *sc = device_get_softc(dev);
2113 
2114 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2115 	stop_adapter(sc);
2116 	stop_lld(sc);
2117 #ifdef TCP_OFFLOAD
2118 	stop_all_uld(sc);
2119 #endif
2120 	set_adapter_hwstatus(sc, false);
2121 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2122 
2123 	return (0);
2124 }
2125 
2126 struct adapter_pre_reset_state {
2127 	u_int flags;
2128 	uint16_t nbmcaps;
2129 	uint16_t linkcaps;
2130 	uint16_t switchcaps;
2131 	uint16_t niccaps;
2132 	uint16_t toecaps;
2133 	uint16_t rdmacaps;
2134 	uint16_t cryptocaps;
2135 	uint16_t iscsicaps;
2136 	uint16_t fcoecaps;
2137 
2138 	u_int cfcsum;
2139 	char cfg_file[32];
2140 
2141 	struct adapter_params params;
2142 	struct t4_virt_res vres;
2143 	struct tid_info tids;
2144 	struct sge sge;
2145 
2146 	int rawf_base;
2147 	int nrawf;
2148 
2149 };
2150 
2151 static void
2152 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2153 {
2154 
2155 	ASSERT_SYNCHRONIZED_OP(sc);
2156 
2157 	o->flags = sc->flags;
2158 
2159 	o->nbmcaps =  sc->nbmcaps;
2160 	o->linkcaps = sc->linkcaps;
2161 	o->switchcaps = sc->switchcaps;
2162 	o->niccaps = sc->niccaps;
2163 	o->toecaps = sc->toecaps;
2164 	o->rdmacaps = sc->rdmacaps;
2165 	o->cryptocaps = sc->cryptocaps;
2166 	o->iscsicaps = sc->iscsicaps;
2167 	o->fcoecaps = sc->fcoecaps;
2168 
2169 	o->cfcsum = sc->cfcsum;
2170 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2171 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2172 
2173 	o->params = sc->params;
2174 	o->vres = sc->vres;
2175 	o->tids = sc->tids;
2176 	o->sge = sc->sge;
2177 
2178 	o->rawf_base = sc->rawf_base;
2179 	o->nrawf = sc->nrawf;
2180 }
2181 
2182 static int
2183 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2184 {
2185 	int rc = 0;
2186 
2187 	ASSERT_SYNCHRONIZED_OP(sc);
2188 
2189 	/* Capabilities */
2190 #define COMPARE_CAPS(c) do { \
2191 	if (o->c##caps != sc->c##caps) { \
2192 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2193 		    sc->c##caps); \
2194 		rc = EINVAL; \
2195 	} \
2196 } while (0)
2197 	COMPARE_CAPS(nbm);
2198 	COMPARE_CAPS(link);
2199 	COMPARE_CAPS(switch);
2200 	COMPARE_CAPS(nic);
2201 	COMPARE_CAPS(toe);
2202 	COMPARE_CAPS(rdma);
2203 	COMPARE_CAPS(crypto);
2204 	COMPARE_CAPS(iscsi);
2205 	COMPARE_CAPS(fcoe);
2206 #undef COMPARE_CAPS
2207 
2208 	/* Firmware config file */
2209 	if (o->cfcsum != sc->cfcsum) {
2210 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2211 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2212 		rc = EINVAL;
2213 	}
2214 
2215 #define COMPARE_PARAM(p, name) do { \
2216 	if (o->p != sc->p) { \
2217 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2218 		rc = EINVAL; \
2219 	} \
2220 } while (0)
2221 	COMPARE_PARAM(sge.iq_start, iq_start);
2222 	COMPARE_PARAM(sge.eq_start, eq_start);
2223 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2224 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2225 	COMPARE_PARAM(tids.nftids, nftids);
2226 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2227 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2228 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2229 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2230 	COMPARE_PARAM(tids.tid_base, tid_base);
2231 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2232 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2233 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2234 	COMPARE_PARAM(rawf_base, rawf_base);
2235 	COMPARE_PARAM(nrawf, nrawf);
2236 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2237 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2238 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2239 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2240 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2241 	COMPARE_PARAM(tids.ntids, ntids);
2242 	COMPARE_PARAM(tids.etid_base, etid_base);
2243 	COMPARE_PARAM(tids.etid_end, etid_end);
2244 	COMPARE_PARAM(tids.netids, netids);
2245 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2246 	COMPARE_PARAM(params.ethoffload, ethoffload);
2247 	COMPARE_PARAM(tids.natids, natids);
2248 	COMPARE_PARAM(tids.stid_base, stid_base);
2249 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2250 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2251 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2252 	COMPARE_PARAM(vres.stag.start, stag_start);
2253 	COMPARE_PARAM(vres.stag.size, stag_size);
2254 	COMPARE_PARAM(vres.rq.start, rq_start);
2255 	COMPARE_PARAM(vres.rq.size, rq_size);
2256 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2257 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2258 	COMPARE_PARAM(vres.qp.start, qp_start);
2259 	COMPARE_PARAM(vres.qp.size, qp_size);
2260 	COMPARE_PARAM(vres.cq.start, cq_start);
2261 	COMPARE_PARAM(vres.cq.size, cq_size);
2262 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2263 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2264 	COMPARE_PARAM(vres.srq.start, srq_start);
2265 	COMPARE_PARAM(vres.srq.size, srq_size);
2266 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2267 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2268 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2269 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2270 	COMPARE_PARAM(vres.key.start, key_start);
2271 	COMPARE_PARAM(vres.key.size, key_size);
2272 #undef COMPARE_PARAM
2273 
2274 	return (rc);
2275 }
2276 
2277 static int
2278 restart_lld(struct adapter *sc)
2279 {
2280 	struct adapter_pre_reset_state *old_state = NULL;
2281 	struct port_info *pi;
2282 	struct vi_info *vi;
2283 	if_t ifp;
2284 	struct sge_txq *txq;
2285 	int rc, i, j, k;
2286 
2287 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rlld");
2288 	if (rc != 0)
2289 		return (ENXIO);
2290 
2291 	/* Restore memory window. */
2292 	setup_memwin(sc);
2293 
2294 	/* Go no further if recovery mode has been requested. */
2295 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2296 		CH_ALERT(sc, "%s: recovery mode during restart.\n", __func__);
2297 		rc = 0;
2298 		set_adapter_hwstatus(sc, true);
2299 		goto done;
2300 	}
2301 
2302 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2303 	save_caps_and_params(sc, old_state);
2304 
2305 	/* Reestablish contact with firmware and become the primary PF. */
2306 	rc = contact_firmware(sc);
2307 	if (rc != 0)
2308 		goto done; /* error message displayed already */
2309 	MPASS(sc->flags & FW_OK);
2310 
2311 	if (sc->flags & MASTER_PF) {
2312 		rc = partition_resources(sc);
2313 		if (rc != 0)
2314 			goto done; /* error message displayed already */
2315 	}
2316 
2317 	rc = get_params__post_init(sc);
2318 	if (rc != 0)
2319 		goto done; /* error message displayed already */
2320 
2321 	rc = set_params__post_init(sc);
2322 	if (rc != 0)
2323 		goto done; /* error message displayed already */
2324 
2325 	rc = compare_caps_and_params(sc, old_state);
2326 	if (rc != 0)
2327 		goto done; /* error message displayed already */
2328 
2329 	for_each_port(sc, i) {
2330 		pi = sc->port[i];
2331 		MPASS(pi != NULL);
2332 		MPASS(pi->vi != NULL);
2333 		MPASS(pi->vi[0].dev == pi->dev);
2334 
2335 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2336 		if (rc != 0) {
2337 			CH_ERR(sc,
2338 			    "failed to re-initialize port %d: %d\n", i, rc);
2339 			goto done;
2340 		}
2341 		MPASS(sc->chan_map[pi->tx_chan] == i);
2342 
2343 		PORT_LOCK(pi);
2344 		fixup_link_config(pi);
2345 		build_medialist(pi);
2346 		PORT_UNLOCK(pi);
2347 		for_each_vi(pi, j, vi) {
2348 			if (IS_MAIN_VI(vi))
2349 				continue;
2350 			rc = alloc_extra_vi(sc, pi, vi);
2351 			if (rc != 0) {
2352 				CH_ERR(vi,
2353 				    "failed to re-allocate extra VI: %d\n", rc);
2354 				goto done;
2355 			}
2356 		}
2357 	}
2358 
2359 	/*
2360 	 * Interrupts and queues are about to be enabled and other threads will
2361 	 * want to access the hardware too.  It is safe to do so.  Note that
2362 	 * this thread is still in the middle of a synchronized_op.
2363 	 */
2364 	set_adapter_hwstatus(sc, true);
2365 
2366 	if (sc->flags & FULL_INIT_DONE) {
2367 		rc = adapter_full_init(sc);
2368 		if (rc != 0) {
2369 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2370 			goto done;
2371 		}
2372 
2373 		if (sc->vxlan_refcount > 0)
2374 			enable_vxlan_rx(sc);
2375 
2376 		for_each_port(sc, i) {
2377 			pi = sc->port[i];
2378 			for_each_vi(pi, j, vi) {
2379 				mtx_lock(&vi->tick_mtx);
2380 				vi->flags &= ~VI_SKIP_STATS;
2381 				mtx_unlock(&vi->tick_mtx);
2382 				if (!(vi->flags & VI_INIT_DONE))
2383 					continue;
2384 				rc = vi_full_init(vi);
2385 				if (rc != 0) {
2386 					CH_ERR(vi, "failed to re-initialize "
2387 					    "interface: %d\n", rc);
2388 					goto done;
2389 				}
2390 
2391 				ifp = vi->ifp;
2392 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2393 					continue;
2394 				/*
2395 				 * Note that we do not setup multicast addresses
2396 				 * in the first pass.  This ensures that the
2397 				 * unicast DMACs for all VIs on all ports get an
2398 				 * MPS TCAM entry.
2399 				 */
2400 				rc = update_mac_settings(ifp, XGMAC_ALL &
2401 				    ~XGMAC_MCADDRS);
2402 				if (rc != 0) {
2403 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2404 					goto done;
2405 				}
2406 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2407 				    true);
2408 				if (rc != 0) {
2409 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2410 					goto done;
2411 				}
2412 				for_each_txq(vi, k, txq) {
2413 					TXQ_LOCK(txq);
2414 					txq->eq.flags |= EQ_ENABLED;
2415 					TXQ_UNLOCK(txq);
2416 				}
2417 				mtx_lock(&vi->tick_mtx);
2418 				callout_schedule(&vi->tick, hz);
2419 				mtx_unlock(&vi->tick_mtx);
2420 			}
2421 			PORT_LOCK(pi);
2422 			if (pi->up_vis > 0) {
2423 				t4_update_port_info(pi);
2424 				fixup_link_config(pi);
2425 				build_medialist(pi);
2426 				apply_link_config(pi);
2427 				if (pi->link_cfg.link_ok)
2428 					t4_os_link_changed(pi);
2429 			}
2430 			PORT_UNLOCK(pi);
2431 		}
2432 
2433 		/* Now reprogram the L2 multicast addresses. */
2434 		for_each_port(sc, i) {
2435 			pi = sc->port[i];
2436 			for_each_vi(pi, j, vi) {
2437 				if (!(vi->flags & VI_INIT_DONE))
2438 					continue;
2439 				ifp = vi->ifp;
2440 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2441 					continue;
2442 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2443 				if (rc != 0) {
2444 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2445 					rc = 0;	/* carry on */
2446 				}
2447 			}
2448 		}
2449 	}
2450 
2451 	/* Reset all calibration */
2452 	t4_calibration_start(sc);
2453 done:
2454 	end_synchronized_op(sc, 0);
2455 	free(old_state, M_CXGBE);
2456 
2457 	restart_atid_allocator(sc);
2458 	t4_restart_l2t(sc);
2459 
2460 	return (rc);
2461 }
2462 
2463 static int
2464 t4_resume(device_t dev)
2465 {
2466 	struct adapter *sc = device_get_softc(dev);
2467 
2468 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2469 	restart_adapter(sc);
2470 	restart_lld(sc);
2471 #ifdef TCP_OFFLOAD
2472 	restart_all_uld(sc);
2473 #endif
2474 	CH_ALERT(sc, "%s end (thread %p).\n", __func__, curthread);
2475 
2476 	return (0);
2477 }
2478 
2479 static int
2480 t4_reset_prepare(device_t dev, device_t child)
2481 {
2482 	struct adapter *sc = device_get_softc(dev);
2483 
2484 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2485 	return (0);
2486 }
2487 
2488 static int
2489 t4_reset_post(device_t dev, device_t child)
2490 {
2491 	struct adapter *sc = device_get_softc(dev);
2492 
2493 	CH_ALERT(sc, "%s from thread %p.\n", __func__, curthread);
2494 	return (0);
2495 }
2496 
2497 static int
2498 reset_adapter_with_pci_bus_reset(struct adapter *sc)
2499 {
2500 	int rc;
2501 
2502 	mtx_lock(&Giant);
2503 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2504 	mtx_unlock(&Giant);
2505 	return (rc);
2506 }
2507 
2508 static int
2509 reset_adapter_with_pl_rst(struct adapter *sc)
2510 {
2511 	stop_adapter(sc);
2512 	stop_lld(sc);
2513 #ifdef TCP_OFFLOAD
2514 	stop_all_uld(sc);
2515 #endif
2516 	set_adapter_hwstatus(sc, false);
2517 
2518 	/* This is a t4_write_reg without the hw_off_limits check. */
2519 	MPASS(sc->error_flags & HW_OFF_LIMITS);
2520 	bus_space_write_4(sc->bt, sc->bh, A_PL_RST,
2521 			  F_PIORSTMODE | F_PIORST | F_AUTOPCIEPAUSE);
2522 	pause("pl_rst", 1 * hz);		/* Wait 1s for reset */
2523 
2524 	restart_adapter(sc);
2525 	restart_lld(sc);
2526 #ifdef TCP_OFFLOAD
2527 	restart_all_uld(sc);
2528 #endif
2529 
2530 	return (0);
2531 }
2532 
2533 static void
2534 reset_adapter_task(void *arg, int pending)
2535 {
2536 	struct adapter *sc = arg;
2537 	const int flags = sc->flags;
2538 	const int eflags = sc->error_flags;
2539 	int rc;
2540 
2541 	if (pending > 1)
2542 		CH_ALERT(sc, "%s: pending %d\n", __func__, pending);
2543 	if (vm_guest == 0)
2544 		rc = reset_adapter_with_pci_bus_reset(sc);
2545 	else
2546 		rc = reset_adapter_with_pl_rst(sc);
2547 	if (rc != 0) {
2548 		CH_ERR(sc, "adapter did not reset properly, rc = %d, "
2549 		       "flags 0x%08x -> 0x%08x, err_flags 0x%08x -> 0x%08x.\n",
2550 		       rc, flags, sc->flags, eflags, sc->error_flags);
2551 	}
2552 }
2553 
2554 static int
2555 cxgbe_probe(device_t dev)
2556 {
2557 	struct port_info *pi = device_get_softc(dev);
2558 
2559 	device_set_descf(dev, "port %d", pi->port_id);
2560 
2561 	return (BUS_PROBE_DEFAULT);
2562 }
2563 
2564 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2565     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2566     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2567     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2568 #define T4_CAP_ENABLE (T4_CAP)
2569 
2570 static void
2571 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2572 {
2573 	if_t ifp;
2574 	struct sbuf *sb;
2575 	struct sysctl_ctx_list *ctx = &vi->ctx;
2576 	struct sysctl_oid_list *children;
2577 	struct pfil_head_args pa;
2578 	struct adapter *sc = vi->adapter;
2579 
2580 	sysctl_ctx_init(ctx);
2581 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2582 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2583 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2584 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2585 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2586 #ifdef DEV_NETMAP
2587 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2588 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2589 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2590 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2591 #endif
2592 #ifdef TCP_OFFLOAD
2593 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2594 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2595 #endif
2596 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2597 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2598 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2599 #endif
2600 
2601 	vi->xact_addr_filt = -1;
2602 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2603 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2604 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2605 		vi->flags |= TX_USES_VM_WR;
2606 
2607 	/* Allocate an ifnet and set it up */
2608 	ifp = if_alloc_dev(IFT_ETHER, dev);
2609 	vi->ifp = ifp;
2610 	if_setsoftc(ifp, vi);
2611 
2612 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2613 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2614 
2615 	if_setinitfn(ifp, cxgbe_init);
2616 	if_setioctlfn(ifp, cxgbe_ioctl);
2617 	if_settransmitfn(ifp, cxgbe_transmit);
2618 	if_setqflushfn(ifp, cxgbe_qflush);
2619 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2620 		if_setgetcounterfn(ifp, vi_get_counter);
2621 	else
2622 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2623 #if defined(KERN_TLS) || defined(RATELIMIT)
2624 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2625 #endif
2626 #ifdef RATELIMIT
2627 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2628 #endif
2629 
2630 	if_setcapabilities(ifp, T4_CAP);
2631 	if_setcapenable(ifp, T4_CAP_ENABLE);
2632 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2633 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2634 	if (chip_id(sc) >= CHELSIO_T6) {
2635 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2636 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2637 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2638 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2639 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2640 	}
2641 
2642 #ifdef TCP_OFFLOAD
2643 	if (vi->nofldrxq != 0)
2644 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2645 #endif
2646 #ifdef RATELIMIT
2647 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2648 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2649 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2650 	}
2651 #endif
2652 
2653 	if_sethwtsomax(ifp, IP_MAXPACKET);
2654 	if (vi->flags & TX_USES_VM_WR)
2655 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2656 	else
2657 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2658 #ifdef RATELIMIT
2659 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2660 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2661 #endif
2662 	if_sethwtsomaxsegsize(ifp, 65536);
2663 #ifdef KERN_TLS
2664 	if (is_ktls(sc)) {
2665 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2666 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2667 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2668 	}
2669 #endif
2670 
2671 	ether_ifattach(ifp, vi->hw_addr);
2672 #ifdef DEV_NETMAP
2673 	if (vi->nnmrxq != 0)
2674 		cxgbe_nm_attach(vi);
2675 #endif
2676 	sb = sbuf_new_auto();
2677 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2678 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2679 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2680 	case IFCAP_TOE:
2681 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2682 		break;
2683 	case IFCAP_TOE | IFCAP_TXRTLMT:
2684 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2685 		break;
2686 	case IFCAP_TXRTLMT:
2687 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2688 		break;
2689 	}
2690 #endif
2691 #ifdef TCP_OFFLOAD
2692 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2693 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2694 #endif
2695 #ifdef DEV_NETMAP
2696 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2697 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2698 		    vi->nnmtxq, vi->nnmrxq);
2699 #endif
2700 	sbuf_finish(sb);
2701 	device_printf(dev, "%s\n", sbuf_data(sb));
2702 	sbuf_delete(sb);
2703 
2704 	vi_sysctls(vi);
2705 
2706 	pa.pa_version = PFIL_VERSION;
2707 	pa.pa_flags = PFIL_IN;
2708 	pa.pa_type = PFIL_TYPE_ETHERNET;
2709 	pa.pa_headname = if_name(ifp);
2710 	vi->pfil = pfil_head_register(&pa);
2711 }
2712 
2713 static int
2714 cxgbe_attach(device_t dev)
2715 {
2716 	struct port_info *pi = device_get_softc(dev);
2717 	struct adapter *sc = pi->adapter;
2718 	struct vi_info *vi;
2719 	int i;
2720 
2721 	sysctl_ctx_init(&pi->ctx);
2722 
2723 	cxgbe_vi_attach(dev, &pi->vi[0]);
2724 
2725 	for_each_vi(pi, i, vi) {
2726 		if (i == 0)
2727 			continue;
2728 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, DEVICE_UNIT_ANY);
2729 		if (vi->dev == NULL) {
2730 			device_printf(dev, "failed to add VI %d\n", i);
2731 			continue;
2732 		}
2733 		device_set_softc(vi->dev, vi);
2734 	}
2735 
2736 	cxgbe_sysctls(pi);
2737 
2738 	bus_generic_attach(dev);
2739 
2740 	return (0);
2741 }
2742 
2743 static void
2744 cxgbe_vi_detach(struct vi_info *vi)
2745 {
2746 	if_t ifp = vi->ifp;
2747 
2748 	if (vi->pfil != NULL) {
2749 		pfil_head_unregister(vi->pfil);
2750 		vi->pfil = NULL;
2751 	}
2752 
2753 	ether_ifdetach(ifp);
2754 
2755 	/* Let detach proceed even if these fail. */
2756 #ifdef DEV_NETMAP
2757 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2758 		cxgbe_nm_detach(vi);
2759 #endif
2760 	cxgbe_uninit_synchronized(vi);
2761 	callout_drain(&vi->tick);
2762 	mtx_destroy(&vi->tick_mtx);
2763 	sysctl_ctx_free(&vi->ctx);
2764 	vi_full_uninit(vi);
2765 
2766 	if_free(vi->ifp);
2767 	vi->ifp = NULL;
2768 }
2769 
2770 static int
2771 cxgbe_detach(device_t dev)
2772 {
2773 	struct port_info *pi = device_get_softc(dev);
2774 	struct adapter *sc = pi->adapter;
2775 	int rc;
2776 
2777 	/* Detach the extra VIs first. */
2778 	rc = bus_generic_detach(dev);
2779 	if (rc)
2780 		return (rc);
2781 	device_delete_children(dev);
2782 
2783 	sysctl_ctx_free(&pi->ctx);
2784 	begin_vi_detach(sc, &pi->vi[0]);
2785 	if (pi->flags & HAS_TRACEQ) {
2786 		sc->traceq = -1;	/* cloner should not create ifnet */
2787 		t4_tracer_port_detach(sc);
2788 	}
2789 	cxgbe_vi_detach(&pi->vi[0]);
2790 	ifmedia_removeall(&pi->media);
2791 	end_vi_detach(sc, &pi->vi[0]);
2792 
2793 	return (0);
2794 }
2795 
2796 static void
2797 cxgbe_init(void *arg)
2798 {
2799 	struct vi_info *vi = arg;
2800 	struct adapter *sc = vi->adapter;
2801 
2802 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2803 		return;
2804 	cxgbe_init_synchronized(vi);
2805 	end_synchronized_op(sc, 0);
2806 }
2807 
2808 static int
2809 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2810 {
2811 	int rc = 0, mtu, flags;
2812 	struct vi_info *vi = if_getsoftc(ifp);
2813 	struct port_info *pi = vi->pi;
2814 	struct adapter *sc = pi->adapter;
2815 	struct ifreq *ifr = (struct ifreq *)data;
2816 	uint32_t mask;
2817 
2818 	switch (cmd) {
2819 	case SIOCSIFMTU:
2820 		mtu = ifr->ifr_mtu;
2821 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2822 			return (EINVAL);
2823 
2824 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2825 		if (rc)
2826 			return (rc);
2827 		if_setmtu(ifp, mtu);
2828 		if (vi->flags & VI_INIT_DONE) {
2829 			t4_update_fl_bufsize(ifp);
2830 			if (!hw_off_limits(sc) &&
2831 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2832 				rc = update_mac_settings(ifp, XGMAC_MTU);
2833 		}
2834 		end_synchronized_op(sc, 0);
2835 		break;
2836 
2837 	case SIOCSIFFLAGS:
2838 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2839 		if (rc)
2840 			return (rc);
2841 
2842 		if (hw_off_limits(sc)) {
2843 			rc = ENXIO;
2844 			goto fail;
2845 		}
2846 
2847 		if (if_getflags(ifp) & IFF_UP) {
2848 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2849 				flags = vi->if_flags;
2850 				if ((if_getflags(ifp) ^ flags) &
2851 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2852 					rc = update_mac_settings(ifp,
2853 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2854 				}
2855 			} else {
2856 				rc = cxgbe_init_synchronized(vi);
2857 			}
2858 			vi->if_flags = if_getflags(ifp);
2859 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2860 			rc = cxgbe_uninit_synchronized(vi);
2861 		}
2862 		end_synchronized_op(sc, 0);
2863 		break;
2864 
2865 	case SIOCADDMULTI:
2866 	case SIOCDELMULTI:
2867 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2868 		if (rc)
2869 			return (rc);
2870 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2871 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2872 		end_synchronized_op(sc, 0);
2873 		break;
2874 
2875 	case SIOCSIFCAP:
2876 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2877 		if (rc)
2878 			return (rc);
2879 
2880 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2881 		if (mask & IFCAP_TXCSUM) {
2882 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2883 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2884 
2885 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2886 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2887 				mask &= ~IFCAP_TSO4;
2888 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2889 				if_printf(ifp,
2890 				    "tso4 disabled due to -txcsum.\n");
2891 			}
2892 		}
2893 		if (mask & IFCAP_TXCSUM_IPV6) {
2894 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2895 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2896 
2897 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2898 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2899 				mask &= ~IFCAP_TSO6;
2900 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2901 				if_printf(ifp,
2902 				    "tso6 disabled due to -txcsum6.\n");
2903 			}
2904 		}
2905 		if (mask & IFCAP_RXCSUM)
2906 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2907 		if (mask & IFCAP_RXCSUM_IPV6)
2908 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2909 
2910 		/*
2911 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2912 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2913 		 * sending a TSO request our way, so it's sufficient to toggle
2914 		 * IFCAP_TSOx only.
2915 		 */
2916 		if (mask & IFCAP_TSO4) {
2917 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2918 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2919 				if_printf(ifp, "enable txcsum first.\n");
2920 				rc = EAGAIN;
2921 				goto fail;
2922 			}
2923 			if_togglecapenable(ifp, IFCAP_TSO4);
2924 		}
2925 		if (mask & IFCAP_TSO6) {
2926 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2927 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2928 				if_printf(ifp, "enable txcsum6 first.\n");
2929 				rc = EAGAIN;
2930 				goto fail;
2931 			}
2932 			if_togglecapenable(ifp, IFCAP_TSO6);
2933 		}
2934 		if (mask & IFCAP_LRO) {
2935 #if defined(INET) || defined(INET6)
2936 			int i;
2937 			struct sge_rxq *rxq;
2938 
2939 			if_togglecapenable(ifp, IFCAP_LRO);
2940 			for_each_rxq(vi, i, rxq) {
2941 				if (if_getcapenable(ifp) & IFCAP_LRO)
2942 					rxq->iq.flags |= IQ_LRO_ENABLED;
2943 				else
2944 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2945 			}
2946 #endif
2947 		}
2948 #ifdef TCP_OFFLOAD
2949 		if (mask & IFCAP_TOE) {
2950 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2951 
2952 			rc = toe_capability(vi, enable);
2953 			if (rc != 0)
2954 				goto fail;
2955 
2956 			if_togglecapenable(ifp, mask);
2957 		}
2958 #endif
2959 		if (mask & IFCAP_VLAN_HWTAGGING) {
2960 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2961 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2962 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2963 		}
2964 		if (mask & IFCAP_VLAN_MTU) {
2965 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2966 
2967 			/* Need to find out how to disable auto-mtu-inflation */
2968 		}
2969 		if (mask & IFCAP_VLAN_HWTSO)
2970 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2971 		if (mask & IFCAP_VLAN_HWCSUM)
2972 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2973 #ifdef RATELIMIT
2974 		if (mask & IFCAP_TXRTLMT)
2975 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2976 #endif
2977 		if (mask & IFCAP_HWRXTSTMP) {
2978 			int i;
2979 			struct sge_rxq *rxq;
2980 
2981 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2982 			for_each_rxq(vi, i, rxq) {
2983 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2984 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2985 				else
2986 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2987 			}
2988 		}
2989 		if (mask & IFCAP_MEXTPG)
2990 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2991 
2992 #ifdef KERN_TLS
2993 		if (mask & IFCAP_TXTLS) {
2994 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2995 
2996 			rc = ktls_capability(sc, enable);
2997 			if (rc != 0)
2998 				goto fail;
2999 
3000 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
3001 		}
3002 #endif
3003 		if (mask & IFCAP_VXLAN_HWCSUM) {
3004 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
3005 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
3006 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
3007 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
3008 		}
3009 		if (mask & IFCAP_VXLAN_HWTSO) {
3010 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
3011 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
3012 			    CSUM_INNER_IP_TSO);
3013 		}
3014 
3015 #ifdef VLAN_CAPABILITIES
3016 		VLAN_CAPABILITIES(ifp);
3017 #endif
3018 fail:
3019 		end_synchronized_op(sc, 0);
3020 		break;
3021 
3022 	case SIOCSIFMEDIA:
3023 	case SIOCGIFMEDIA:
3024 	case SIOCGIFXMEDIA:
3025 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3026 		break;
3027 
3028 	case SIOCGI2C: {
3029 		struct ifi2creq i2c;
3030 
3031 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3032 		if (rc != 0)
3033 			break;
3034 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3035 			rc = EPERM;
3036 			break;
3037 		}
3038 		if (i2c.len > sizeof(i2c.data)) {
3039 			rc = EINVAL;
3040 			break;
3041 		}
3042 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3043 		if (rc)
3044 			return (rc);
3045 		if (hw_off_limits(sc))
3046 			rc = ENXIO;
3047 		else
3048 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3049 			    i2c.offset, i2c.len, &i2c.data[0]);
3050 		end_synchronized_op(sc, 0);
3051 		if (rc == 0)
3052 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3053 		break;
3054 	}
3055 
3056 	default:
3057 		rc = ether_ioctl(ifp, cmd, data);
3058 	}
3059 
3060 	return (rc);
3061 }
3062 
3063 static int
3064 cxgbe_transmit(if_t ifp, struct mbuf *m)
3065 {
3066 	struct vi_info *vi = if_getsoftc(ifp);
3067 	struct port_info *pi = vi->pi;
3068 	struct adapter *sc;
3069 	struct sge_txq *txq;
3070 	void *items[1];
3071 	int rc;
3072 
3073 	M_ASSERTPKTHDR(m);
3074 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3075 #if defined(KERN_TLS) || defined(RATELIMIT)
3076 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3077 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3078 #endif
3079 
3080 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3081 		m_freem(m);
3082 		return (ENETDOWN);
3083 	}
3084 
3085 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3086 	if (__predict_false(rc != 0)) {
3087 		if (__predict_true(rc == EINPROGRESS)) {
3088 			/* queued by parse_pkt */
3089 			MPASS(m != NULL);
3090 			return (0);
3091 		}
3092 
3093 		MPASS(m == NULL);			/* was freed already */
3094 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3095 		return (rc);
3096 	}
3097 
3098 	/* Select a txq. */
3099 	sc = vi->adapter;
3100 	txq = &sc->sge.txq[vi->first_txq];
3101 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3102 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3103 		    vi->rsrv_noflowq);
3104 
3105 	items[0] = m;
3106 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3107 	if (__predict_false(rc != 0))
3108 		m_freem(m);
3109 
3110 	return (rc);
3111 }
3112 
3113 static void
3114 cxgbe_qflush(if_t ifp)
3115 {
3116 	struct vi_info *vi = if_getsoftc(ifp);
3117 	struct sge_txq *txq;
3118 	int i;
3119 
3120 	/* queues do not exist if !VI_INIT_DONE. */
3121 	if (vi->flags & VI_INIT_DONE) {
3122 		for_each_txq(vi, i, txq) {
3123 			TXQ_LOCK(txq);
3124 			txq->eq.flags |= EQ_QFLUSH;
3125 			TXQ_UNLOCK(txq);
3126 			while (!mp_ring_is_idle(txq->r)) {
3127 				mp_ring_check_drainage(txq->r, 4096);
3128 				pause("qflush", 1);
3129 			}
3130 			TXQ_LOCK(txq);
3131 			txq->eq.flags &= ~EQ_QFLUSH;
3132 			TXQ_UNLOCK(txq);
3133 		}
3134 	}
3135 	if_qflush(ifp);
3136 }
3137 
3138 static uint64_t
3139 vi_get_counter(if_t ifp, ift_counter c)
3140 {
3141 	struct vi_info *vi = if_getsoftc(ifp);
3142 	struct fw_vi_stats_vf *s = &vi->stats;
3143 
3144 	mtx_lock(&vi->tick_mtx);
3145 	vi_refresh_stats(vi);
3146 	mtx_unlock(&vi->tick_mtx);
3147 
3148 	switch (c) {
3149 	case IFCOUNTER_IPACKETS:
3150 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3151 		    s->rx_ucast_frames);
3152 	case IFCOUNTER_IERRORS:
3153 		return (s->rx_err_frames);
3154 	case IFCOUNTER_OPACKETS:
3155 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3156 		    s->tx_ucast_frames + s->tx_offload_frames);
3157 	case IFCOUNTER_OERRORS:
3158 		return (s->tx_drop_frames);
3159 	case IFCOUNTER_IBYTES:
3160 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3161 		    s->rx_ucast_bytes);
3162 	case IFCOUNTER_OBYTES:
3163 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3164 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3165 	case IFCOUNTER_IMCASTS:
3166 		return (s->rx_mcast_frames);
3167 	case IFCOUNTER_OMCASTS:
3168 		return (s->tx_mcast_frames);
3169 	case IFCOUNTER_OQDROPS: {
3170 		uint64_t drops;
3171 
3172 		drops = 0;
3173 		if (vi->flags & VI_INIT_DONE) {
3174 			int i;
3175 			struct sge_txq *txq;
3176 
3177 			for_each_txq(vi, i, txq)
3178 				drops += counter_u64_fetch(txq->r->dropped);
3179 		}
3180 
3181 		return (drops);
3182 
3183 	}
3184 
3185 	default:
3186 		return (if_get_counter_default(ifp, c));
3187 	}
3188 }
3189 
3190 static uint64_t
3191 cxgbe_get_counter(if_t ifp, ift_counter c)
3192 {
3193 	struct vi_info *vi = if_getsoftc(ifp);
3194 	struct port_info *pi = vi->pi;
3195 	struct port_stats *s = &pi->stats;
3196 
3197 	mtx_lock(&vi->tick_mtx);
3198 	cxgbe_refresh_stats(vi);
3199 	mtx_unlock(&vi->tick_mtx);
3200 
3201 	switch (c) {
3202 	case IFCOUNTER_IPACKETS:
3203 		return (s->rx_frames);
3204 
3205 	case IFCOUNTER_IERRORS:
3206 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3207 		    s->rx_fcs_err + s->rx_len_err);
3208 
3209 	case IFCOUNTER_OPACKETS:
3210 		return (s->tx_frames);
3211 
3212 	case IFCOUNTER_OERRORS:
3213 		return (s->tx_error_frames);
3214 
3215 	case IFCOUNTER_IBYTES:
3216 		return (s->rx_octets);
3217 
3218 	case IFCOUNTER_OBYTES:
3219 		return (s->tx_octets);
3220 
3221 	case IFCOUNTER_IMCASTS:
3222 		return (s->rx_mcast_frames);
3223 
3224 	case IFCOUNTER_OMCASTS:
3225 		return (s->tx_mcast_frames);
3226 
3227 	case IFCOUNTER_IQDROPS:
3228 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3229 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3230 		    s->rx_trunc3 + pi->tnl_cong_drops);
3231 
3232 	case IFCOUNTER_OQDROPS: {
3233 		uint64_t drops;
3234 
3235 		drops = s->tx_drop;
3236 		if (vi->flags & VI_INIT_DONE) {
3237 			int i;
3238 			struct sge_txq *txq;
3239 
3240 			for_each_txq(vi, i, txq)
3241 				drops += counter_u64_fetch(txq->r->dropped);
3242 		}
3243 
3244 		return (drops);
3245 
3246 	}
3247 
3248 	default:
3249 		return (if_get_counter_default(ifp, c));
3250 	}
3251 }
3252 
3253 #if defined(KERN_TLS) || defined(RATELIMIT)
3254 static int
3255 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3256     struct m_snd_tag **pt)
3257 {
3258 	int error;
3259 
3260 	switch (params->hdr.type) {
3261 #ifdef RATELIMIT
3262 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3263 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3264 		break;
3265 #endif
3266 #ifdef KERN_TLS
3267 	case IF_SND_TAG_TYPE_TLS:
3268 	{
3269 		struct vi_info *vi = if_getsoftc(ifp);
3270 
3271 		if (is_t6(vi->pi->adapter))
3272 			error = t6_tls_tag_alloc(ifp, params, pt);
3273 		else
3274 			error = EOPNOTSUPP;
3275 		break;
3276 	}
3277 #endif
3278 	default:
3279 		error = EOPNOTSUPP;
3280 	}
3281 	return (error);
3282 }
3283 #endif
3284 
3285 /*
3286  * The kernel picks a media from the list we had provided but we still validate
3287  * the requeste.
3288  */
3289 int
3290 cxgbe_media_change(if_t ifp)
3291 {
3292 	struct vi_info *vi = if_getsoftc(ifp);
3293 	struct port_info *pi = vi->pi;
3294 	struct ifmedia *ifm = &pi->media;
3295 	struct link_config *lc = &pi->link_cfg;
3296 	struct adapter *sc = pi->adapter;
3297 	int rc;
3298 
3299 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3300 	if (rc != 0)
3301 		return (rc);
3302 	PORT_LOCK(pi);
3303 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3304 		/* ifconfig .. media autoselect */
3305 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3306 			rc = ENOTSUP; /* AN not supported by transceiver */
3307 			goto done;
3308 		}
3309 		lc->requested_aneg = AUTONEG_ENABLE;
3310 		lc->requested_speed = 0;
3311 		lc->requested_fc |= PAUSE_AUTONEG;
3312 	} else {
3313 		lc->requested_aneg = AUTONEG_DISABLE;
3314 		lc->requested_speed =
3315 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3316 		lc->requested_fc = 0;
3317 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3318 			lc->requested_fc |= PAUSE_RX;
3319 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3320 			lc->requested_fc |= PAUSE_TX;
3321 	}
3322 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3323 		fixup_link_config(pi);
3324 		rc = apply_link_config(pi);
3325 	}
3326 done:
3327 	PORT_UNLOCK(pi);
3328 	end_synchronized_op(sc, 0);
3329 	return (rc);
3330 }
3331 
3332 /*
3333  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3334  * given speed.
3335  */
3336 static int
3337 port_mword(struct port_info *pi, uint32_t speed)
3338 {
3339 
3340 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3341 	MPASS(powerof2(speed));
3342 
3343 	switch(pi->port_type) {
3344 	case FW_PORT_TYPE_BT_SGMII:
3345 	case FW_PORT_TYPE_BT_XFI:
3346 	case FW_PORT_TYPE_BT_XAUI:
3347 		/* BaseT */
3348 		switch (speed) {
3349 		case FW_PORT_CAP32_SPEED_100M:
3350 			return (IFM_100_T);
3351 		case FW_PORT_CAP32_SPEED_1G:
3352 			return (IFM_1000_T);
3353 		case FW_PORT_CAP32_SPEED_10G:
3354 			return (IFM_10G_T);
3355 		}
3356 		break;
3357 	case FW_PORT_TYPE_KX4:
3358 		if (speed == FW_PORT_CAP32_SPEED_10G)
3359 			return (IFM_10G_KX4);
3360 		break;
3361 	case FW_PORT_TYPE_CX4:
3362 		if (speed == FW_PORT_CAP32_SPEED_10G)
3363 			return (IFM_10G_CX4);
3364 		break;
3365 	case FW_PORT_TYPE_KX:
3366 		if (speed == FW_PORT_CAP32_SPEED_1G)
3367 			return (IFM_1000_KX);
3368 		break;
3369 	case FW_PORT_TYPE_KR:
3370 	case FW_PORT_TYPE_BP_AP:
3371 	case FW_PORT_TYPE_BP4_AP:
3372 	case FW_PORT_TYPE_BP40_BA:
3373 	case FW_PORT_TYPE_KR4_100G:
3374 	case FW_PORT_TYPE_KR_SFP28:
3375 	case FW_PORT_TYPE_KR_XLAUI:
3376 		switch (speed) {
3377 		case FW_PORT_CAP32_SPEED_1G:
3378 			return (IFM_1000_KX);
3379 		case FW_PORT_CAP32_SPEED_10G:
3380 			return (IFM_10G_KR);
3381 		case FW_PORT_CAP32_SPEED_25G:
3382 			return (IFM_25G_KR);
3383 		case FW_PORT_CAP32_SPEED_40G:
3384 			return (IFM_40G_KR4);
3385 		case FW_PORT_CAP32_SPEED_50G:
3386 			return (IFM_50G_KR2);
3387 		case FW_PORT_CAP32_SPEED_100G:
3388 			return (IFM_100G_KR4);
3389 		}
3390 		break;
3391 	case FW_PORT_TYPE_FIBER_XFI:
3392 	case FW_PORT_TYPE_FIBER_XAUI:
3393 	case FW_PORT_TYPE_SFP:
3394 	case FW_PORT_TYPE_QSFP_10G:
3395 	case FW_PORT_TYPE_QSA:
3396 	case FW_PORT_TYPE_QSFP:
3397 	case FW_PORT_TYPE_CR4_QSFP:
3398 	case FW_PORT_TYPE_CR_QSFP:
3399 	case FW_PORT_TYPE_CR2_QSFP:
3400 	case FW_PORT_TYPE_SFP28:
3401 		/* Pluggable transceiver */
3402 		switch (pi->mod_type) {
3403 		case FW_PORT_MOD_TYPE_LR:
3404 			switch (speed) {
3405 			case FW_PORT_CAP32_SPEED_1G:
3406 				return (IFM_1000_LX);
3407 			case FW_PORT_CAP32_SPEED_10G:
3408 				return (IFM_10G_LR);
3409 			case FW_PORT_CAP32_SPEED_25G:
3410 				return (IFM_25G_LR);
3411 			case FW_PORT_CAP32_SPEED_40G:
3412 				return (IFM_40G_LR4);
3413 			case FW_PORT_CAP32_SPEED_50G:
3414 				return (IFM_50G_LR2);
3415 			case FW_PORT_CAP32_SPEED_100G:
3416 				return (IFM_100G_LR4);
3417 			}
3418 			break;
3419 		case FW_PORT_MOD_TYPE_SR:
3420 			switch (speed) {
3421 			case FW_PORT_CAP32_SPEED_1G:
3422 				return (IFM_1000_SX);
3423 			case FW_PORT_CAP32_SPEED_10G:
3424 				return (IFM_10G_SR);
3425 			case FW_PORT_CAP32_SPEED_25G:
3426 				return (IFM_25G_SR);
3427 			case FW_PORT_CAP32_SPEED_40G:
3428 				return (IFM_40G_SR4);
3429 			case FW_PORT_CAP32_SPEED_50G:
3430 				return (IFM_50G_SR2);
3431 			case FW_PORT_CAP32_SPEED_100G:
3432 				return (IFM_100G_SR4);
3433 			}
3434 			break;
3435 		case FW_PORT_MOD_TYPE_ER:
3436 			if (speed == FW_PORT_CAP32_SPEED_10G)
3437 				return (IFM_10G_ER);
3438 			break;
3439 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3440 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3441 			switch (speed) {
3442 			case FW_PORT_CAP32_SPEED_1G:
3443 				return (IFM_1000_CX);
3444 			case FW_PORT_CAP32_SPEED_10G:
3445 				return (IFM_10G_TWINAX);
3446 			case FW_PORT_CAP32_SPEED_25G:
3447 				return (IFM_25G_CR);
3448 			case FW_PORT_CAP32_SPEED_40G:
3449 				return (IFM_40G_CR4);
3450 			case FW_PORT_CAP32_SPEED_50G:
3451 				return (IFM_50G_CR2);
3452 			case FW_PORT_CAP32_SPEED_100G:
3453 				return (IFM_100G_CR4);
3454 			}
3455 			break;
3456 		case FW_PORT_MOD_TYPE_LRM:
3457 			if (speed == FW_PORT_CAP32_SPEED_10G)
3458 				return (IFM_10G_LRM);
3459 			break;
3460 		case FW_PORT_MOD_TYPE_NA:
3461 			MPASS(0);	/* Not pluggable? */
3462 			/* fall throough */
3463 		case FW_PORT_MOD_TYPE_ERROR:
3464 		case FW_PORT_MOD_TYPE_UNKNOWN:
3465 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3466 			break;
3467 		case FW_PORT_MOD_TYPE_NONE:
3468 			return (IFM_NONE);
3469 		}
3470 		break;
3471 	case FW_PORT_TYPE_NONE:
3472 		return (IFM_NONE);
3473 	}
3474 
3475 	return (IFM_UNKNOWN);
3476 }
3477 
3478 void
3479 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3480 {
3481 	struct vi_info *vi = if_getsoftc(ifp);
3482 	struct port_info *pi = vi->pi;
3483 	struct adapter *sc = pi->adapter;
3484 	struct link_config *lc = &pi->link_cfg;
3485 
3486 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3487 		return;
3488 	PORT_LOCK(pi);
3489 
3490 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3491 		/*
3492 		 * If all the interfaces are administratively down the firmware
3493 		 * does not report transceiver changes.  Refresh port info here
3494 		 * so that ifconfig displays accurate ifmedia at all times.
3495 		 * This is the only reason we have a synchronized op in this
3496 		 * function.  Just PORT_LOCK would have been enough otherwise.
3497 		 */
3498 		t4_update_port_info(pi);
3499 		build_medialist(pi);
3500 	}
3501 
3502 	/* ifm_status */
3503 	ifmr->ifm_status = IFM_AVALID;
3504 	if (lc->link_ok == false)
3505 		goto done;
3506 	ifmr->ifm_status |= IFM_ACTIVE;
3507 
3508 	/* ifm_active */
3509 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3510 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3511 	if (lc->fc & PAUSE_RX)
3512 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3513 	if (lc->fc & PAUSE_TX)
3514 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3515 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3516 done:
3517 	PORT_UNLOCK(pi);
3518 	end_synchronized_op(sc, 0);
3519 }
3520 
3521 static int
3522 vcxgbe_probe(device_t dev)
3523 {
3524 	struct vi_info *vi = device_get_softc(dev);
3525 
3526 	device_set_descf(dev, "port %d vi %td", vi->pi->port_id,
3527 	    vi - vi->pi->vi);
3528 
3529 	return (BUS_PROBE_DEFAULT);
3530 }
3531 
3532 static int
3533 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3534 {
3535 	int func, index, rc;
3536 	uint32_t param, val;
3537 
3538 	ASSERT_SYNCHRONIZED_OP(sc);
3539 
3540 	index = vi - pi->vi;
3541 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3542 	KASSERT(index < nitems(vi_mac_funcs),
3543 	    ("%s: VI %s doesn't have a MAC func", __func__,
3544 	    device_get_nameunit(vi->dev)));
3545 	func = vi_mac_funcs[index];
3546 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3547 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3548 	if (rc < 0) {
3549 		CH_ERR(vi, "failed to allocate virtual interface %d"
3550 		    "for port %d: %d\n", index, pi->port_id, -rc);
3551 		return (-rc);
3552 	}
3553 	vi->viid = rc;
3554 
3555 	if (vi->rss_size == 1) {
3556 		/*
3557 		 * This VI didn't get a slice of the RSS table.  Reduce the
3558 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3559 		 * configuration file (nvi, rssnvi for this PF) if this is a
3560 		 * problem.
3561 		 */
3562 		device_printf(vi->dev, "RSS table not available.\n");
3563 		vi->rss_base = 0xffff;
3564 
3565 		return (0);
3566 	}
3567 
3568 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3569 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3570 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3571 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3572 	if (rc)
3573 		vi->rss_base = 0xffff;
3574 	else {
3575 		MPASS((val >> 16) == vi->rss_size);
3576 		vi->rss_base = val & 0xffff;
3577 	}
3578 
3579 	return (0);
3580 }
3581 
3582 static int
3583 vcxgbe_attach(device_t dev)
3584 {
3585 	struct vi_info *vi;
3586 	struct port_info *pi;
3587 	struct adapter *sc;
3588 	int rc;
3589 
3590 	vi = device_get_softc(dev);
3591 	pi = vi->pi;
3592 	sc = pi->adapter;
3593 
3594 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3595 	if (rc)
3596 		return (rc);
3597 	rc = alloc_extra_vi(sc, pi, vi);
3598 	end_synchronized_op(sc, 0);
3599 	if (rc)
3600 		return (rc);
3601 
3602 	cxgbe_vi_attach(dev, vi);
3603 
3604 	return (0);
3605 }
3606 
3607 static int
3608 vcxgbe_detach(device_t dev)
3609 {
3610 	struct vi_info *vi;
3611 	struct adapter *sc;
3612 
3613 	vi = device_get_softc(dev);
3614 	sc = vi->adapter;
3615 
3616 	begin_vi_detach(sc, vi);
3617 	cxgbe_vi_detach(vi);
3618 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3619 	end_vi_detach(sc, vi);
3620 
3621 	return (0);
3622 }
3623 
3624 static struct callout fatal_callout;
3625 static struct taskqueue *reset_tq;
3626 
3627 static void
3628 delayed_panic(void *arg)
3629 {
3630 	struct adapter *sc = arg;
3631 
3632 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3633 }
3634 
3635 static void
3636 fatal_error_task(void *arg, int pending)
3637 {
3638 	struct adapter *sc = arg;
3639 	int rc;
3640 
3641 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3642 		dump_cim_regs(sc);
3643 		dump_cimla(sc);
3644 		dump_devlog(sc);
3645 	}
3646 
3647 	if (t4_reset_on_fatal_err) {
3648 		CH_ALERT(sc, "resetting adapter after fatal error.\n");
3649 		rc = reset_adapter_with_pci_bus_reset(sc);
3650 		if (rc == 0 && t4_panic_on_fatal_err) {
3651 			CH_ALERT(sc, "reset was successful, "
3652 			    "system will NOT panic.\n");
3653 			return;
3654 		}
3655 	}
3656 
3657 	if (t4_panic_on_fatal_err) {
3658 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3659 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3660 	}
3661 }
3662 
3663 void
3664 t4_fatal_err(struct adapter *sc, bool fw_error)
3665 {
3666 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3667 
3668 	stop_adapter(sc);
3669 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3670 		return;
3671 	if (fw_error) {
3672 		/*
3673 		 * We are here because of a firmware error/timeout and not
3674 		 * because of a hardware interrupt.  It is possible (although
3675 		 * not very likely) that an error interrupt was also raised but
3676 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3677 		 * main INT_CAUSE registers here to make sure we haven't missed
3678 		 * anything interesting.
3679 		 */
3680 		t4_slow_intr_handler(sc, verbose);
3681 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3682 	}
3683 	t4_report_fw_error(sc);
3684 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3685 	    device_get_nameunit(sc->dev), fw_error);
3686 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3687 }
3688 
3689 void
3690 t4_add_adapter(struct adapter *sc)
3691 {
3692 	sx_xlock(&t4_list_lock);
3693 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3694 	sx_xunlock(&t4_list_lock);
3695 }
3696 
3697 int
3698 t4_map_bars_0_and_4(struct adapter *sc)
3699 {
3700 	sc->regs_rid = PCIR_BAR(0);
3701 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3702 	    &sc->regs_rid, RF_ACTIVE);
3703 	if (sc->regs_res == NULL) {
3704 		device_printf(sc->dev, "cannot map registers.\n");
3705 		return (ENXIO);
3706 	}
3707 	sc->bt = rman_get_bustag(sc->regs_res);
3708 	sc->bh = rman_get_bushandle(sc->regs_res);
3709 	sc->mmio_len = rman_get_size(sc->regs_res);
3710 	setbit(&sc->doorbells, DOORBELL_KDB);
3711 
3712 	sc->msix_rid = PCIR_BAR(4);
3713 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3714 	    &sc->msix_rid, RF_ACTIVE);
3715 	if (sc->msix_res == NULL) {
3716 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3717 		return (ENXIO);
3718 	}
3719 
3720 	return (0);
3721 }
3722 
3723 int
3724 t4_map_bar_2(struct adapter *sc)
3725 {
3726 
3727 	/*
3728 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3729 	 * to map it if RDMA is disabled.
3730 	 */
3731 	if (is_t4(sc) && sc->rdmacaps == 0)
3732 		return (0);
3733 
3734 	sc->udbs_rid = PCIR_BAR(2);
3735 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3736 	    &sc->udbs_rid, RF_ACTIVE);
3737 	if (sc->udbs_res == NULL) {
3738 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3739 		return (ENXIO);
3740 	}
3741 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3742 
3743 	if (chip_id(sc) >= CHELSIO_T5) {
3744 		setbit(&sc->doorbells, DOORBELL_UDB);
3745 #if defined(__i386__) || defined(__amd64__)
3746 		if (t5_write_combine) {
3747 			int rc, mode;
3748 
3749 			/*
3750 			 * Enable write combining on BAR2.  This is the
3751 			 * userspace doorbell BAR and is split into 128B
3752 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3753 			 * with an egress queue.  The first 64B has the doorbell
3754 			 * and the second 64B can be used to submit a tx work
3755 			 * request with an implicit doorbell.
3756 			 */
3757 
3758 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3759 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3760 			if (rc == 0) {
3761 				clrbit(&sc->doorbells, DOORBELL_UDB);
3762 				setbit(&sc->doorbells, DOORBELL_WCWR);
3763 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3764 			} else {
3765 				device_printf(sc->dev,
3766 				    "couldn't enable write combining: %d\n",
3767 				    rc);
3768 			}
3769 
3770 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3771 			t4_write_reg(sc, A_SGE_STAT_CFG,
3772 			    V_STATSOURCE_T5(7) | mode);
3773 		}
3774 #endif
3775 	}
3776 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3777 
3778 	return (0);
3779 }
3780 
3781 int
3782 t4_adj_doorbells(struct adapter *sc)
3783 {
3784 	if ((sc->doorbells & t4_doorbells_allowed) != 0) {
3785 		sc->doorbells &= t4_doorbells_allowed;
3786 		return (0);
3787 	}
3788 	CH_ERR(sc, "No usable doorbell (available = 0x%x, allowed = 0x%x).\n",
3789 	       sc->doorbells, t4_doorbells_allowed);
3790 	return (EINVAL);
3791 }
3792 
3793 struct memwin_init {
3794 	uint32_t base;
3795 	uint32_t aperture;
3796 };
3797 
3798 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3799 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3800 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3801 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3802 };
3803 
3804 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3805 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3806 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3807 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3808 };
3809 
3810 static void
3811 setup_memwin(struct adapter *sc)
3812 {
3813 	const struct memwin_init *mw_init;
3814 	struct memwin *mw;
3815 	int i;
3816 	uint32_t bar0;
3817 
3818 	if (is_t4(sc)) {
3819 		/*
3820 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3821 		 * mechanism.  Works from within PCI passthrough environments
3822 		 * too, where rman_get_start() can return a different value.  We
3823 		 * need to program the T4 memory window decoders with the actual
3824 		 * addresses that will be coming across the PCIe link.
3825 		 */
3826 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3827 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3828 
3829 		mw_init = &t4_memwin[0];
3830 	} else {
3831 		/* T5+ use the relative offset inside the PCIe BAR */
3832 		bar0 = 0;
3833 
3834 		mw_init = &t5_memwin[0];
3835 	}
3836 
3837 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3838 		if (!rw_initialized(&mw->mw_lock)) {
3839 			rw_init(&mw->mw_lock, "memory window access");
3840 			mw->mw_base = mw_init->base;
3841 			mw->mw_aperture = mw_init->aperture;
3842 			mw->mw_curpos = 0;
3843 		}
3844 		t4_write_reg(sc,
3845 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3846 		    (mw->mw_base + bar0) | V_BIR(0) |
3847 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3848 		rw_wlock(&mw->mw_lock);
3849 		position_memwin(sc, i, mw->mw_curpos);
3850 		rw_wunlock(&mw->mw_lock);
3851 	}
3852 
3853 	/* flush */
3854 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3855 }
3856 
3857 /*
3858  * Positions the memory window at the given address in the card's address space.
3859  * There are some alignment requirements and the actual position may be at an
3860  * address prior to the requested address.  mw->mw_curpos always has the actual
3861  * position of the window.
3862  */
3863 static void
3864 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3865 {
3866 	struct memwin *mw;
3867 	uint32_t pf;
3868 	uint32_t reg;
3869 
3870 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3871 	mw = &sc->memwin[idx];
3872 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3873 
3874 	if (is_t4(sc)) {
3875 		pf = 0;
3876 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3877 	} else {
3878 		pf = V_PFNUM(sc->pf);
3879 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3880 	}
3881 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3882 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3883 	t4_read_reg(sc, reg);	/* flush */
3884 }
3885 
3886 int
3887 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3888     int len, int rw)
3889 {
3890 	struct memwin *mw;
3891 	uint32_t mw_end, v;
3892 
3893 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3894 
3895 	/* Memory can only be accessed in naturally aligned 4 byte units */
3896 	if (addr & 3 || len & 3 || len <= 0)
3897 		return (EINVAL);
3898 
3899 	mw = &sc->memwin[idx];
3900 	while (len > 0) {
3901 		rw_rlock(&mw->mw_lock);
3902 		mw_end = mw->mw_curpos + mw->mw_aperture;
3903 		if (addr >= mw_end || addr < mw->mw_curpos) {
3904 			/* Will need to reposition the window */
3905 			if (!rw_try_upgrade(&mw->mw_lock)) {
3906 				rw_runlock(&mw->mw_lock);
3907 				rw_wlock(&mw->mw_lock);
3908 			}
3909 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3910 			position_memwin(sc, idx, addr);
3911 			rw_downgrade(&mw->mw_lock);
3912 			mw_end = mw->mw_curpos + mw->mw_aperture;
3913 		}
3914 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3915 		while (addr < mw_end && len > 0) {
3916 			if (rw == 0) {
3917 				v = t4_read_reg(sc, mw->mw_base + addr -
3918 				    mw->mw_curpos);
3919 				*val++ = le32toh(v);
3920 			} else {
3921 				v = *val++;
3922 				t4_write_reg(sc, mw->mw_base + addr -
3923 				    mw->mw_curpos, htole32(v));
3924 			}
3925 			addr += 4;
3926 			len -= 4;
3927 		}
3928 		rw_runlock(&mw->mw_lock);
3929 	}
3930 
3931 	return (0);
3932 }
3933 
3934 CTASSERT(M_TID_COOKIE == M_COOKIE);
3935 CTASSERT(MAX_ATIDS <= (M_TID_TID + 1));
3936 
3937 static void
3938 t4_init_atid_table(struct adapter *sc)
3939 {
3940 	struct tid_info *t;
3941 	int i;
3942 
3943 	t = &sc->tids;
3944 	if (t->natids == 0)
3945 		return;
3946 
3947 	MPASS(t->atid_tab == NULL);
3948 
3949 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3950 	    M_ZERO | M_WAITOK);
3951 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3952 	t->afree = t->atid_tab;
3953 	t->atids_in_use = 0;
3954 	t->atid_alloc_stopped = false;
3955 	for (i = 1; i < t->natids; i++)
3956 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3957 	t->atid_tab[t->natids - 1].next = NULL;
3958 }
3959 
3960 static void
3961 t4_free_atid_table(struct adapter *sc)
3962 {
3963 	struct tid_info *t;
3964 
3965 	t = &sc->tids;
3966 
3967 	KASSERT(t->atids_in_use == 0,
3968 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3969 
3970 	if (mtx_initialized(&t->atid_lock))
3971 		mtx_destroy(&t->atid_lock);
3972 	free(t->atid_tab, M_CXGBE);
3973 	t->atid_tab = NULL;
3974 }
3975 
3976 static void
3977 stop_atid_allocator(struct adapter *sc)
3978 {
3979 	struct tid_info *t = &sc->tids;
3980 
3981 	mtx_lock(&t->atid_lock);
3982 	t->atid_alloc_stopped = true;
3983 	mtx_unlock(&t->atid_lock);
3984 }
3985 
3986 static void
3987 restart_atid_allocator(struct adapter *sc)
3988 {
3989 	struct tid_info *t = &sc->tids;
3990 
3991 	mtx_lock(&t->atid_lock);
3992 	KASSERT(t->atids_in_use == 0,
3993 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3994 	t->atid_alloc_stopped = false;
3995 	mtx_unlock(&t->atid_lock);
3996 }
3997 
3998 int
3999 alloc_atid(struct adapter *sc, void *ctx)
4000 {
4001 	struct tid_info *t = &sc->tids;
4002 	int atid = -1;
4003 
4004 	mtx_lock(&t->atid_lock);
4005 	if (t->afree && !t->atid_alloc_stopped) {
4006 		union aopen_entry *p = t->afree;
4007 
4008 		atid = p - t->atid_tab;
4009 		MPASS(atid <= M_TID_TID);
4010 		t->afree = p->next;
4011 		p->data = ctx;
4012 		t->atids_in_use++;
4013 	}
4014 	mtx_unlock(&t->atid_lock);
4015 	return (atid);
4016 }
4017 
4018 void *
4019 lookup_atid(struct adapter *sc, int atid)
4020 {
4021 	struct tid_info *t = &sc->tids;
4022 
4023 	return (t->atid_tab[atid].data);
4024 }
4025 
4026 void
4027 free_atid(struct adapter *sc, int atid)
4028 {
4029 	struct tid_info *t = &sc->tids;
4030 	union aopen_entry *p = &t->atid_tab[atid];
4031 
4032 	mtx_lock(&t->atid_lock);
4033 	p->next = t->afree;
4034 	t->afree = p;
4035 	t->atids_in_use--;
4036 	mtx_unlock(&t->atid_lock);
4037 }
4038 
4039 static void
4040 queue_tid_release(struct adapter *sc, int tid)
4041 {
4042 
4043 	CXGBE_UNIMPLEMENTED("deferred tid release");
4044 }
4045 
4046 void
4047 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4048 {
4049 	struct wrqe *wr;
4050 	struct cpl_tid_release *req;
4051 
4052 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4053 	if (wr == NULL) {
4054 		queue_tid_release(sc, tid);	/* defer */
4055 		return;
4056 	}
4057 	req = wrtod(wr);
4058 
4059 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4060 
4061 	t4_wrq_tx(sc, wr);
4062 }
4063 
4064 static int
4065 t4_range_cmp(const void *a, const void *b)
4066 {
4067 	return ((const struct t4_range *)a)->start -
4068 	       ((const struct t4_range *)b)->start;
4069 }
4070 
4071 /*
4072  * Verify that the memory range specified by the addr/len pair is valid within
4073  * the card's address space.
4074  */
4075 static int
4076 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4077 {
4078 	struct t4_range mem_ranges[4], *r, *next;
4079 	uint32_t em, addr_len;
4080 	int i, n, remaining;
4081 
4082 	/* Memory can only be accessed in naturally aligned 4 byte units */
4083 	if (addr & 3 || len & 3 || len == 0)
4084 		return (EINVAL);
4085 
4086 	/* Enabled memories */
4087 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4088 
4089 	r = &mem_ranges[0];
4090 	n = 0;
4091 	bzero(r, sizeof(mem_ranges));
4092 	if (em & F_EDRAM0_ENABLE) {
4093 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4094 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4095 		if (r->size > 0) {
4096 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4097 			if (addr >= r->start &&
4098 			    addr + len <= r->start + r->size)
4099 				return (0);
4100 			r++;
4101 			n++;
4102 		}
4103 	}
4104 	if (em & F_EDRAM1_ENABLE) {
4105 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4106 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4107 		if (r->size > 0) {
4108 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4109 			if (addr >= r->start &&
4110 			    addr + len <= r->start + r->size)
4111 				return (0);
4112 			r++;
4113 			n++;
4114 		}
4115 	}
4116 	if (em & F_EXT_MEM_ENABLE) {
4117 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4118 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4119 		if (r->size > 0) {
4120 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4121 			if (addr >= r->start &&
4122 			    addr + len <= r->start + r->size)
4123 				return (0);
4124 			r++;
4125 			n++;
4126 		}
4127 	}
4128 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4129 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4130 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4131 		if (r->size > 0) {
4132 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4133 			if (addr >= r->start &&
4134 			    addr + len <= r->start + r->size)
4135 				return (0);
4136 			r++;
4137 			n++;
4138 		}
4139 	}
4140 	MPASS(n <= nitems(mem_ranges));
4141 
4142 	if (n > 1) {
4143 		/* Sort and merge the ranges. */
4144 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4145 
4146 		/* Start from index 0 and examine the next n - 1 entries. */
4147 		r = &mem_ranges[0];
4148 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4149 
4150 			MPASS(r->size > 0);	/* r is a valid entry. */
4151 			next = r + 1;
4152 			MPASS(next->size > 0);	/* and so is the next one. */
4153 
4154 			while (r->start + r->size >= next->start) {
4155 				/* Merge the next one into the current entry. */
4156 				r->size = max(r->start + r->size,
4157 				    next->start + next->size) - r->start;
4158 				n--;	/* One fewer entry in total. */
4159 				if (--remaining == 0)
4160 					goto done;	/* short circuit */
4161 				next++;
4162 			}
4163 			if (next != r + 1) {
4164 				/*
4165 				 * Some entries were merged into r and next
4166 				 * points to the first valid entry that couldn't
4167 				 * be merged.
4168 				 */
4169 				MPASS(next->size > 0);	/* must be valid */
4170 				memcpy(r + 1, next, remaining * sizeof(*r));
4171 #ifdef INVARIANTS
4172 				/*
4173 				 * This so that the foo->size assertion in the
4174 				 * next iteration of the loop do the right
4175 				 * thing for entries that were pulled up and are
4176 				 * no longer valid.
4177 				 */
4178 				MPASS(n < nitems(mem_ranges));
4179 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4180 				    sizeof(struct t4_range));
4181 #endif
4182 			}
4183 		}
4184 done:
4185 		/* Done merging the ranges. */
4186 		MPASS(n > 0);
4187 		r = &mem_ranges[0];
4188 		for (i = 0; i < n; i++, r++) {
4189 			if (addr >= r->start &&
4190 			    addr + len <= r->start + r->size)
4191 				return (0);
4192 		}
4193 	}
4194 
4195 	return (EFAULT);
4196 }
4197 
4198 static int
4199 fwmtype_to_hwmtype(int mtype)
4200 {
4201 
4202 	switch (mtype) {
4203 	case FW_MEMTYPE_EDC0:
4204 		return (MEM_EDC0);
4205 	case FW_MEMTYPE_EDC1:
4206 		return (MEM_EDC1);
4207 	case FW_MEMTYPE_EXTMEM:
4208 		return (MEM_MC0);
4209 	case FW_MEMTYPE_EXTMEM1:
4210 		return (MEM_MC1);
4211 	default:
4212 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4213 	}
4214 }
4215 
4216 /*
4217  * Verify that the memory range specified by the memtype/offset/len pair is
4218  * valid and lies entirely within the memtype specified.  The global address of
4219  * the start of the range is returned in addr.
4220  */
4221 static int
4222 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4223     uint32_t *addr)
4224 {
4225 	uint32_t em, addr_len, maddr;
4226 
4227 	/* Memory can only be accessed in naturally aligned 4 byte units */
4228 	if (off & 3 || len & 3 || len == 0)
4229 		return (EINVAL);
4230 
4231 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4232 	switch (fwmtype_to_hwmtype(mtype)) {
4233 	case MEM_EDC0:
4234 		if (!(em & F_EDRAM0_ENABLE))
4235 			return (EINVAL);
4236 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4237 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4238 		break;
4239 	case MEM_EDC1:
4240 		if (!(em & F_EDRAM1_ENABLE))
4241 			return (EINVAL);
4242 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4243 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4244 		break;
4245 	case MEM_MC:
4246 		if (!(em & F_EXT_MEM_ENABLE))
4247 			return (EINVAL);
4248 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4249 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4250 		break;
4251 	case MEM_MC1:
4252 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4253 			return (EINVAL);
4254 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4255 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4256 		break;
4257 	default:
4258 		return (EINVAL);
4259 	}
4260 
4261 	*addr = maddr + off;	/* global address */
4262 	return (validate_mem_range(sc, *addr, len));
4263 }
4264 
4265 static int
4266 fixup_devlog_params(struct adapter *sc)
4267 {
4268 	struct devlog_params *dparams = &sc->params.devlog;
4269 	int rc;
4270 
4271 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4272 	    dparams->size, &dparams->addr);
4273 
4274 	return (rc);
4275 }
4276 
4277 static void
4278 update_nirq(struct intrs_and_queues *iaq, int nports)
4279 {
4280 
4281 	iaq->nirq = T4_EXTRA_INTR;
4282 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4283 	iaq->nirq += nports * iaq->nofldrxq;
4284 	iaq->nirq += nports * (iaq->num_vis - 1) *
4285 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4286 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4287 }
4288 
4289 /*
4290  * Adjust requirements to fit the number of interrupts available.
4291  */
4292 static void
4293 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4294     int navail)
4295 {
4296 	int old_nirq;
4297 	const int nports = sc->params.nports;
4298 
4299 	MPASS(nports > 0);
4300 	MPASS(navail > 0);
4301 
4302 	bzero(iaq, sizeof(*iaq));
4303 	iaq->intr_type = itype;
4304 	iaq->num_vis = t4_num_vis;
4305 	iaq->ntxq = t4_ntxq;
4306 	iaq->ntxq_vi = t4_ntxq_vi;
4307 	iaq->nrxq = t4_nrxq;
4308 	iaq->nrxq_vi = t4_nrxq_vi;
4309 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4310 	if (is_offload(sc) || is_ethoffload(sc)) {
4311 		iaq->nofldtxq = t4_nofldtxq;
4312 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4313 	}
4314 #endif
4315 #ifdef TCP_OFFLOAD
4316 	if (is_offload(sc)) {
4317 		iaq->nofldrxq = t4_nofldrxq;
4318 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4319 	}
4320 #endif
4321 #ifdef DEV_NETMAP
4322 	if (t4_native_netmap & NN_MAIN_VI) {
4323 		iaq->nnmtxq = t4_nnmtxq;
4324 		iaq->nnmrxq = t4_nnmrxq;
4325 	}
4326 	if (t4_native_netmap & NN_EXTRA_VI) {
4327 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4328 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4329 	}
4330 #endif
4331 
4332 	update_nirq(iaq, nports);
4333 	if (iaq->nirq <= navail &&
4334 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4335 		/*
4336 		 * This is the normal case -- there are enough interrupts for
4337 		 * everything.
4338 		 */
4339 		goto done;
4340 	}
4341 
4342 	/*
4343 	 * If extra VIs have been configured try reducing their count and see if
4344 	 * that works.
4345 	 */
4346 	while (iaq->num_vis > 1) {
4347 		iaq->num_vis--;
4348 		update_nirq(iaq, nports);
4349 		if (iaq->nirq <= navail &&
4350 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4351 			device_printf(sc->dev, "virtual interfaces per port "
4352 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4353 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4354 			    "itype %d, navail %u, nirq %d.\n",
4355 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4356 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4357 			    itype, navail, iaq->nirq);
4358 			goto done;
4359 		}
4360 	}
4361 
4362 	/*
4363 	 * Extra VIs will not be created.  Log a message if they were requested.
4364 	 */
4365 	MPASS(iaq->num_vis == 1);
4366 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4367 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4368 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4369 	if (iaq->num_vis != t4_num_vis) {
4370 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4371 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4372 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4373 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4374 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4375 	}
4376 
4377 	/*
4378 	 * Keep reducing the number of NIC rx queues to the next lower power of
4379 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4380 	 * if that works.
4381 	 */
4382 	do {
4383 		if (iaq->nrxq > 1) {
4384 			iaq->nrxq = rounddown_pow_of_two(iaq->nrxq - 1);
4385 			if (iaq->nnmrxq > iaq->nrxq)
4386 				iaq->nnmrxq = iaq->nrxq;
4387 		}
4388 		if (iaq->nofldrxq > 1)
4389 			iaq->nofldrxq >>= 1;
4390 
4391 		old_nirq = iaq->nirq;
4392 		update_nirq(iaq, nports);
4393 		if (iaq->nirq <= navail &&
4394 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4395 			device_printf(sc->dev, "running with reduced number of "
4396 			    "rx queues because of shortage of interrupts.  "
4397 			    "nrxq=%u, nofldrxq=%u.  "
4398 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4399 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4400 			goto done;
4401 		}
4402 	} while (old_nirq != iaq->nirq);
4403 
4404 	/* One interrupt for everything.  Ugh. */
4405 	device_printf(sc->dev, "running with minimal number of queues.  "
4406 	    "itype %d, navail %u.\n", itype, navail);
4407 	iaq->nirq = 1;
4408 	iaq->nrxq = 1;
4409 	iaq->ntxq = 1;
4410 	if (iaq->nofldrxq > 0) {
4411 		iaq->nofldrxq = 1;
4412 		iaq->nofldtxq = 1;
4413 	}
4414 	iaq->nnmtxq = 0;
4415 	iaq->nnmrxq = 0;
4416 done:
4417 	MPASS(iaq->num_vis > 0);
4418 	if (iaq->num_vis > 1) {
4419 		MPASS(iaq->nrxq_vi > 0);
4420 		MPASS(iaq->ntxq_vi > 0);
4421 	}
4422 	MPASS(iaq->nirq > 0);
4423 	MPASS(iaq->nrxq > 0);
4424 	MPASS(iaq->ntxq > 0);
4425 	if (itype == INTR_MSI) {
4426 		MPASS(powerof2(iaq->nirq));
4427 	}
4428 }
4429 
4430 static int
4431 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4432 {
4433 	int rc, itype, navail, nalloc;
4434 
4435 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4436 
4437 		if ((itype & t4_intr_types) == 0)
4438 			continue;	/* not allowed */
4439 
4440 		if (itype == INTR_MSIX)
4441 			navail = pci_msix_count(sc->dev);
4442 		else if (itype == INTR_MSI)
4443 			navail = pci_msi_count(sc->dev);
4444 		else
4445 			navail = 1;
4446 restart:
4447 		if (navail == 0)
4448 			continue;
4449 
4450 		calculate_iaq(sc, iaq, itype, navail);
4451 		nalloc = iaq->nirq;
4452 		rc = 0;
4453 		if (itype == INTR_MSIX)
4454 			rc = pci_alloc_msix(sc->dev, &nalloc);
4455 		else if (itype == INTR_MSI)
4456 			rc = pci_alloc_msi(sc->dev, &nalloc);
4457 
4458 		if (rc == 0 && nalloc > 0) {
4459 			if (nalloc == iaq->nirq)
4460 				return (0);
4461 
4462 			/*
4463 			 * Didn't get the number requested.  Use whatever number
4464 			 * the kernel is willing to allocate.
4465 			 */
4466 			device_printf(sc->dev, "fewer vectors than requested, "
4467 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4468 			    itype, iaq->nirq, nalloc);
4469 			pci_release_msi(sc->dev);
4470 			navail = nalloc;
4471 			goto restart;
4472 		}
4473 
4474 		device_printf(sc->dev,
4475 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4476 		    itype, rc, iaq->nirq, nalloc);
4477 	}
4478 
4479 	device_printf(sc->dev,
4480 	    "failed to find a usable interrupt type.  "
4481 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4482 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4483 
4484 	return (ENXIO);
4485 }
4486 
4487 #define FW_VERSION(chip) ( \
4488     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4489     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4490     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4491     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4492 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4493 
4494 /* Just enough of fw_hdr to cover all version info. */
4495 struct fw_h {
4496 	__u8	ver;
4497 	__u8	chip;
4498 	__be16	len512;
4499 	__be32	fw_ver;
4500 	__be32	tp_microcode_ver;
4501 	__u8	intfver_nic;
4502 	__u8	intfver_vnic;
4503 	__u8	intfver_ofld;
4504 	__u8	intfver_ri;
4505 	__u8	intfver_iscsipdu;
4506 	__u8	intfver_iscsi;
4507 	__u8	intfver_fcoepdu;
4508 	__u8	intfver_fcoe;
4509 };
4510 /* Spot check a couple of fields. */
4511 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4512 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4513 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4514 
4515 struct fw_info {
4516 	uint8_t chip;
4517 	char *kld_name;
4518 	char *fw_mod_name;
4519 	struct fw_h fw_h;
4520 } fw_info[] = {
4521 	{
4522 		.chip = CHELSIO_T4,
4523 		.kld_name = "t4fw_cfg",
4524 		.fw_mod_name = "t4fw",
4525 		.fw_h = {
4526 			.chip = FW_HDR_CHIP_T4,
4527 			.fw_ver = htobe32(FW_VERSION(T4)),
4528 			.intfver_nic = FW_INTFVER(T4, NIC),
4529 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4530 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4531 			.intfver_ri = FW_INTFVER(T4, RI),
4532 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4533 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4534 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4535 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4536 		},
4537 	}, {
4538 		.chip = CHELSIO_T5,
4539 		.kld_name = "t5fw_cfg",
4540 		.fw_mod_name = "t5fw",
4541 		.fw_h = {
4542 			.chip = FW_HDR_CHIP_T5,
4543 			.fw_ver = htobe32(FW_VERSION(T5)),
4544 			.intfver_nic = FW_INTFVER(T5, NIC),
4545 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4546 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4547 			.intfver_ri = FW_INTFVER(T5, RI),
4548 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4549 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4550 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4551 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4552 		},
4553 	}, {
4554 		.chip = CHELSIO_T6,
4555 		.kld_name = "t6fw_cfg",
4556 		.fw_mod_name = "t6fw",
4557 		.fw_h = {
4558 			.chip = FW_HDR_CHIP_T6,
4559 			.fw_ver = htobe32(FW_VERSION(T6)),
4560 			.intfver_nic = FW_INTFVER(T6, NIC),
4561 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4562 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4563 			.intfver_ri = FW_INTFVER(T6, RI),
4564 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4565 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4566 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4567 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4568 		},
4569 	}
4570 };
4571 
4572 static struct fw_info *
4573 find_fw_info(int chip)
4574 {
4575 	int i;
4576 
4577 	for (i = 0; i < nitems(fw_info); i++) {
4578 		if (fw_info[i].chip == chip)
4579 			return (&fw_info[i]);
4580 	}
4581 	return (NULL);
4582 }
4583 
4584 /*
4585  * Is the given firmware API compatible with the one the driver was compiled
4586  * with?
4587  */
4588 static int
4589 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4590 {
4591 
4592 	/* short circuit if it's the exact same firmware version */
4593 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4594 		return (1);
4595 
4596 	/*
4597 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4598 	 * features that are supported in the driver.
4599 	 */
4600 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4601 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4602 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4603 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4604 		return (1);
4605 #undef SAME_INTF
4606 
4607 	return (0);
4608 }
4609 
4610 static int
4611 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4612     const struct firmware **fw)
4613 {
4614 	struct fw_info *fw_info;
4615 
4616 	*dcfg = NULL;
4617 	if (fw != NULL)
4618 		*fw = NULL;
4619 
4620 	fw_info = find_fw_info(chip_id(sc));
4621 	if (fw_info == NULL) {
4622 		device_printf(sc->dev,
4623 		    "unable to look up firmware information for chip %d.\n",
4624 		    chip_id(sc));
4625 		return (EINVAL);
4626 	}
4627 
4628 	*dcfg = firmware_get(fw_info->kld_name);
4629 	if (*dcfg != NULL) {
4630 		if (fw != NULL)
4631 			*fw = firmware_get(fw_info->fw_mod_name);
4632 		return (0);
4633 	}
4634 
4635 	return (ENOENT);
4636 }
4637 
4638 static void
4639 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4640     const struct firmware *fw)
4641 {
4642 
4643 	if (fw != NULL)
4644 		firmware_put(fw, FIRMWARE_UNLOAD);
4645 	if (dcfg != NULL)
4646 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4647 }
4648 
4649 /*
4650  * Return values:
4651  * 0 means no firmware install attempted.
4652  * ERESTART means a firmware install was attempted and was successful.
4653  * +ve errno means a firmware install was attempted but failed.
4654  */
4655 static int
4656 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4657     const struct fw_h *drv_fw, const char *reason, int *already)
4658 {
4659 	const struct firmware *cfg, *fw;
4660 	const uint32_t c = be32toh(card_fw->fw_ver);
4661 	uint32_t d, k;
4662 	int rc, fw_install;
4663 	struct fw_h bundled_fw;
4664 	bool load_attempted;
4665 
4666 	cfg = fw = NULL;
4667 	load_attempted = false;
4668 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4669 
4670 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4671 	if (t4_fw_install < 0) {
4672 		rc = load_fw_module(sc, &cfg, &fw);
4673 		if (rc != 0 || fw == NULL) {
4674 			device_printf(sc->dev,
4675 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4676 			    " will use compiled-in firmware version for"
4677 			    "hw.cxgbe.fw_install checks.\n",
4678 			    rc, cfg, fw);
4679 		} else {
4680 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4681 		}
4682 		load_attempted = true;
4683 	}
4684 	d = be32toh(bundled_fw.fw_ver);
4685 
4686 	if (reason != NULL)
4687 		goto install;
4688 
4689 	if ((sc->flags & FW_OK) == 0) {
4690 
4691 		if (c == 0xffffffff) {
4692 			reason = "missing";
4693 			goto install;
4694 		}
4695 
4696 		rc = 0;
4697 		goto done;
4698 	}
4699 
4700 	if (!fw_compatible(card_fw, &bundled_fw)) {
4701 		reason = "incompatible or unusable";
4702 		goto install;
4703 	}
4704 
4705 	if (d > c) {
4706 		reason = "older than the version bundled with this driver";
4707 		goto install;
4708 	}
4709 
4710 	if (fw_install == 2 && d != c) {
4711 		reason = "different than the version bundled with this driver";
4712 		goto install;
4713 	}
4714 
4715 	/* No reason to do anything to the firmware already on the card. */
4716 	rc = 0;
4717 	goto done;
4718 
4719 install:
4720 	rc = 0;
4721 	if ((*already)++)
4722 		goto done;
4723 
4724 	if (fw_install == 0) {
4725 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4726 		    "but the driver is prohibited from installing a firmware "
4727 		    "on the card.\n",
4728 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4729 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4730 
4731 		goto done;
4732 	}
4733 
4734 	/*
4735 	 * We'll attempt to install a firmware.  Load the module first (if it
4736 	 * hasn't been loaded already).
4737 	 */
4738 	if (!load_attempted) {
4739 		rc = load_fw_module(sc, &cfg, &fw);
4740 		if (rc != 0 || fw == NULL) {
4741 			device_printf(sc->dev,
4742 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4743 			    rc, cfg, fw);
4744 			/* carry on */
4745 		}
4746 	}
4747 	if (fw == NULL) {
4748 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4749 		    "but the driver cannot take corrective action because it "
4750 		    "is unable to load the firmware module.\n",
4751 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4752 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4753 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4754 		goto done;
4755 	}
4756 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4757 	if (k != d) {
4758 		MPASS(t4_fw_install > 0);
4759 		device_printf(sc->dev,
4760 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4761 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4762 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4763 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4764 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4765 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4766 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4767 		goto done;
4768 	}
4769 
4770 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4771 	    "installing firmware %u.%u.%u.%u on card.\n",
4772 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4773 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4774 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4775 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4776 
4777 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4778 	if (rc != 0) {
4779 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4780 	} else {
4781 		/* Installed successfully, update the cached header too. */
4782 		rc = ERESTART;
4783 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4784 	}
4785 done:
4786 	unload_fw_module(sc, cfg, fw);
4787 
4788 	return (rc);
4789 }
4790 
4791 /*
4792  * Establish contact with the firmware and attempt to become the master driver.
4793  *
4794  * A firmware will be installed to the card if needed (if the driver is allowed
4795  * to do so).
4796  */
4797 static int
4798 contact_firmware(struct adapter *sc)
4799 {
4800 	int rc, already = 0;
4801 	enum dev_state state;
4802 	struct fw_info *fw_info;
4803 	struct fw_hdr *card_fw;		/* fw on the card */
4804 	const struct fw_h *drv_fw;
4805 
4806 	fw_info = find_fw_info(chip_id(sc));
4807 	if (fw_info == NULL) {
4808 		device_printf(sc->dev,
4809 		    "unable to look up firmware information for chip %d.\n",
4810 		    chip_id(sc));
4811 		return (EINVAL);
4812 	}
4813 	drv_fw = &fw_info->fw_h;
4814 
4815 	/* Read the header of the firmware on the card */
4816 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4817 restart:
4818 	rc = -t4_get_fw_hdr(sc, card_fw);
4819 	if (rc != 0) {
4820 		device_printf(sc->dev,
4821 		    "unable to read firmware header from card's flash: %d\n",
4822 		    rc);
4823 		goto done;
4824 	}
4825 
4826 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4827 	    &already);
4828 	if (rc == ERESTART)
4829 		goto restart;
4830 	if (rc != 0)
4831 		goto done;
4832 
4833 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4834 	if (rc < 0 || state == DEV_STATE_ERR) {
4835 		rc = -rc;
4836 		device_printf(sc->dev,
4837 		    "failed to connect to the firmware: %d, %d.  "
4838 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4839 #if 0
4840 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4841 		    "not responding properly to HELLO", &already) == ERESTART)
4842 			goto restart;
4843 #endif
4844 		goto done;
4845 	}
4846 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4847 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4848 
4849 	if (rc == sc->pf) {
4850 		sc->flags |= MASTER_PF;
4851 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4852 		    NULL, &already);
4853 		if (rc == ERESTART)
4854 			rc = 0;
4855 		else if (rc != 0)
4856 			goto done;
4857 	} else if (state == DEV_STATE_UNINIT) {
4858 		/*
4859 		 * We didn't get to be the master so we definitely won't be
4860 		 * configuring the chip.  It's a bug if someone else hasn't
4861 		 * configured it already.
4862 		 */
4863 		device_printf(sc->dev, "couldn't be master(%d), "
4864 		    "device not already initialized either(%d).  "
4865 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4866 		rc = EPROTO;
4867 		goto done;
4868 	} else {
4869 		/*
4870 		 * Some other PF is the master and has configured the chip.
4871 		 * This is allowed but untested.
4872 		 */
4873 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4874 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4875 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4876 		sc->cfcsum = 0;
4877 		rc = 0;
4878 	}
4879 done:
4880 	if (rc != 0 && sc->flags & FW_OK) {
4881 		t4_fw_bye(sc, sc->mbox);
4882 		sc->flags &= ~FW_OK;
4883 	}
4884 	free(card_fw, M_CXGBE);
4885 	return (rc);
4886 }
4887 
4888 static int
4889 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4890     uint32_t mtype, uint32_t moff)
4891 {
4892 	struct fw_info *fw_info;
4893 	const struct firmware *dcfg, *rcfg = NULL;
4894 	const uint32_t *cfdata;
4895 	uint32_t cflen, addr;
4896 	int rc;
4897 
4898 	load_fw_module(sc, &dcfg, NULL);
4899 
4900 	/* Card specific interpretation of "default". */
4901 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4902 		if (pci_get_device(sc->dev) == 0x440a)
4903 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4904 		if (is_fpga(sc))
4905 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4906 	}
4907 
4908 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4909 		if (dcfg == NULL) {
4910 			device_printf(sc->dev,
4911 			    "KLD with default config is not available.\n");
4912 			rc = ENOENT;
4913 			goto done;
4914 		}
4915 		cfdata = dcfg->data;
4916 		cflen = dcfg->datasize & ~3;
4917 	} else {
4918 		char s[32];
4919 
4920 		fw_info = find_fw_info(chip_id(sc));
4921 		if (fw_info == NULL) {
4922 			device_printf(sc->dev,
4923 			    "unable to look up firmware information for chip %d.\n",
4924 			    chip_id(sc));
4925 			rc = EINVAL;
4926 			goto done;
4927 		}
4928 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4929 
4930 		rcfg = firmware_get(s);
4931 		if (rcfg == NULL) {
4932 			device_printf(sc->dev,
4933 			    "unable to load module \"%s\" for configuration "
4934 			    "profile \"%s\".\n", s, cfg_file);
4935 			rc = ENOENT;
4936 			goto done;
4937 		}
4938 		cfdata = rcfg->data;
4939 		cflen = rcfg->datasize & ~3;
4940 	}
4941 
4942 	if (cflen > FLASH_CFG_MAX_SIZE) {
4943 		device_printf(sc->dev,
4944 		    "config file too long (%d, max allowed is %d).\n",
4945 		    cflen, FLASH_CFG_MAX_SIZE);
4946 		rc = EINVAL;
4947 		goto done;
4948 	}
4949 
4950 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4951 	if (rc != 0) {
4952 		device_printf(sc->dev,
4953 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4954 		    __func__, mtype, moff, cflen, rc);
4955 		rc = EINVAL;
4956 		goto done;
4957 	}
4958 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4959 done:
4960 	if (rcfg != NULL)
4961 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4962 	unload_fw_module(sc, dcfg, NULL);
4963 	return (rc);
4964 }
4965 
4966 struct caps_allowed {
4967 	uint16_t nbmcaps;
4968 	uint16_t linkcaps;
4969 	uint16_t switchcaps;
4970 	uint16_t niccaps;
4971 	uint16_t toecaps;
4972 	uint16_t rdmacaps;
4973 	uint16_t cryptocaps;
4974 	uint16_t iscsicaps;
4975 	uint16_t fcoecaps;
4976 };
4977 
4978 #define FW_PARAM_DEV(param) \
4979 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4980 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4981 #define FW_PARAM_PFVF(param) \
4982 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4983 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4984 
4985 /*
4986  * Provide a configuration profile to the firmware and have it initialize the
4987  * chip accordingly.  This may involve uploading a configuration file to the
4988  * card.
4989  */
4990 static int
4991 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4992     const struct caps_allowed *caps_allowed)
4993 {
4994 	int rc;
4995 	struct fw_caps_config_cmd caps;
4996 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4997 
4998 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4999 	if (rc != 0) {
5000 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
5001 		return (rc);
5002 	}
5003 
5004 	bzero(&caps, sizeof(caps));
5005 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5006 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5007 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
5008 		mtype = 0;
5009 		moff = 0;
5010 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5011 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
5012 		mtype = FW_MEMTYPE_FLASH;
5013 		moff = t4_flash_cfg_addr(sc);
5014 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5015 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5016 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5017 		    FW_LEN16(caps));
5018 	} else {
5019 		/*
5020 		 * Ask the firmware where it wants us to upload the config file.
5021 		 */
5022 		param = FW_PARAM_DEV(CF);
5023 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5024 		if (rc != 0) {
5025 			/* No support for config file?  Shouldn't happen. */
5026 			device_printf(sc->dev,
5027 			    "failed to query config file location: %d.\n", rc);
5028 			goto done;
5029 		}
5030 		mtype = G_FW_PARAMS_PARAM_Y(val);
5031 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
5032 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
5033 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
5034 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
5035 		    FW_LEN16(caps));
5036 
5037 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
5038 		if (rc != 0) {
5039 			device_printf(sc->dev,
5040 			    "failed to upload config file to card: %d.\n", rc);
5041 			goto done;
5042 		}
5043 	}
5044 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5045 	if (rc != 0) {
5046 		device_printf(sc->dev, "failed to pre-process config file: %d "
5047 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5048 		goto done;
5049 	}
5050 
5051 	finicsum = be32toh(caps.finicsum);
5052 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5053 	if (finicsum != cfcsum) {
5054 		device_printf(sc->dev,
5055 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5056 		    finicsum, cfcsum);
5057 	}
5058 	sc->cfcsum = cfcsum;
5059 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5060 
5061 	/*
5062 	 * Let the firmware know what features will (not) be used so it can tune
5063 	 * things accordingly.
5064 	 */
5065 #define LIMIT_CAPS(x) do { \
5066 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5067 } while (0)
5068 	LIMIT_CAPS(nbm);
5069 	LIMIT_CAPS(link);
5070 	LIMIT_CAPS(switch);
5071 	LIMIT_CAPS(nic);
5072 	LIMIT_CAPS(toe);
5073 	LIMIT_CAPS(rdma);
5074 	LIMIT_CAPS(crypto);
5075 	LIMIT_CAPS(iscsi);
5076 	LIMIT_CAPS(fcoe);
5077 #undef LIMIT_CAPS
5078 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5079 		/*
5080 		 * TOE and hashfilters are mutually exclusive.  It is a config
5081 		 * file or firmware bug if both are reported as available.  Try
5082 		 * to cope with the situation in non-debug builds by disabling
5083 		 * TOE.
5084 		 */
5085 		MPASS(caps.toecaps == 0);
5086 
5087 		caps.toecaps = 0;
5088 		caps.rdmacaps = 0;
5089 		caps.iscsicaps = 0;
5090 	}
5091 
5092 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5093 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5094 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5095 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5096 	if (rc != 0) {
5097 		device_printf(sc->dev,
5098 		    "failed to process config file: %d.\n", rc);
5099 		goto done;
5100 	}
5101 
5102 	t4_tweak_chip_settings(sc);
5103 	set_params__pre_init(sc);
5104 
5105 	/* get basic stuff going */
5106 	rc = -t4_fw_initialize(sc, sc->mbox);
5107 	if (rc != 0) {
5108 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5109 		goto done;
5110 	}
5111 done:
5112 	return (rc);
5113 }
5114 
5115 /*
5116  * Partition chip resources for use between various PFs, VFs, etc.
5117  */
5118 static int
5119 partition_resources(struct adapter *sc)
5120 {
5121 	char cfg_file[sizeof(t4_cfg_file)];
5122 	struct caps_allowed caps_allowed;
5123 	int rc;
5124 	bool fallback;
5125 
5126 	/* Only the master driver gets to configure the chip resources. */
5127 	MPASS(sc->flags & MASTER_PF);
5128 
5129 #define COPY_CAPS(x) do { \
5130 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5131 } while (0)
5132 	bzero(&caps_allowed, sizeof(caps_allowed));
5133 	COPY_CAPS(nbm);
5134 	COPY_CAPS(link);
5135 	COPY_CAPS(switch);
5136 	COPY_CAPS(nic);
5137 	COPY_CAPS(toe);
5138 	COPY_CAPS(rdma);
5139 	COPY_CAPS(crypto);
5140 	COPY_CAPS(iscsi);
5141 	COPY_CAPS(fcoe);
5142 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5143 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5144 retry:
5145 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5146 	if (rc != 0 && fallback) {
5147 		dump_devlog(sc);
5148 		device_printf(sc->dev,
5149 		    "failed (%d) to configure card with \"%s\" profile, "
5150 		    "will fall back to a basic configuration and retry.\n",
5151 		    rc, cfg_file);
5152 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5153 		bzero(&caps_allowed, sizeof(caps_allowed));
5154 		COPY_CAPS(switch);
5155 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5156 		fallback = false;
5157 		goto retry;
5158 	}
5159 #undef COPY_CAPS
5160 	return (rc);
5161 }
5162 
5163 /*
5164  * Retrieve parameters that are needed (or nice to have) very early.
5165  */
5166 static int
5167 get_params__pre_init(struct adapter *sc)
5168 {
5169 	int rc;
5170 	uint32_t param[2], val[2];
5171 
5172 	t4_get_version_info(sc);
5173 
5174 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5175 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5176 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5177 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5178 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5179 
5180 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5181 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5182 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5183 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5184 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5185 
5186 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5187 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5188 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5189 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5190 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5191 
5192 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5193 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5194 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5195 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5196 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5197 
5198 	param[0] = FW_PARAM_DEV(PORTVEC);
5199 	param[1] = FW_PARAM_DEV(CCLK);
5200 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5201 	if (rc != 0) {
5202 		device_printf(sc->dev,
5203 		    "failed to query parameters (pre_init): %d.\n", rc);
5204 		return (rc);
5205 	}
5206 
5207 	sc->params.portvec = val[0];
5208 	sc->params.nports = bitcount32(val[0]);
5209 	sc->params.vpd.cclk = val[1];
5210 
5211 	/* Read device log parameters. */
5212 	rc = -t4_init_devlog_params(sc, 1);
5213 	if (rc == 0)
5214 		fixup_devlog_params(sc);
5215 	else {
5216 		device_printf(sc->dev,
5217 		    "failed to get devlog parameters: %d.\n", rc);
5218 		rc = 0;	/* devlog isn't critical for device operation */
5219 	}
5220 
5221 	return (rc);
5222 }
5223 
5224 /*
5225  * Any params that need to be set before FW_INITIALIZE.
5226  */
5227 static int
5228 set_params__pre_init(struct adapter *sc)
5229 {
5230 	int rc = 0;
5231 	uint32_t param, val;
5232 
5233 	if (chip_id(sc) >= CHELSIO_T6) {
5234 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5235 		val = 1;
5236 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5237 		/* firmwares < 1.20.1.0 do not have this param. */
5238 		if (rc == FW_EINVAL &&
5239 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5240 			rc = 0;
5241 		}
5242 		if (rc != 0) {
5243 			device_printf(sc->dev,
5244 			    "failed to enable high priority filters :%d.\n",
5245 			    rc);
5246 		}
5247 
5248 		param = FW_PARAM_DEV(PPOD_EDRAM);
5249 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5250 		if (rc == 0 && val == 1) {
5251 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5252 			    &val);
5253 			if (rc != 0) {
5254 				device_printf(sc->dev,
5255 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5256 			}
5257 		}
5258 	}
5259 
5260 	/* Enable opaque VIIDs with firmwares that support it. */
5261 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5262 	val = 1;
5263 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5264 	if (rc == 0 && val == 1)
5265 		sc->params.viid_smt_extn_support = true;
5266 	else
5267 		sc->params.viid_smt_extn_support = false;
5268 
5269 	return (rc);
5270 }
5271 
5272 /*
5273  * Retrieve various parameters that are of interest to the driver.  The device
5274  * has been initialized by the firmware at this point.
5275  */
5276 static int
5277 get_params__post_init(struct adapter *sc)
5278 {
5279 	int rc;
5280 	uint32_t param[7], val[7];
5281 	struct fw_caps_config_cmd caps;
5282 
5283 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5284 	param[1] = FW_PARAM_PFVF(EQ_START);
5285 	param[2] = FW_PARAM_PFVF(FILTER_START);
5286 	param[3] = FW_PARAM_PFVF(FILTER_END);
5287 	param[4] = FW_PARAM_PFVF(L2T_START);
5288 	param[5] = FW_PARAM_PFVF(L2T_END);
5289 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5290 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5291 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5292 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5293 	if (rc != 0) {
5294 		device_printf(sc->dev,
5295 		    "failed to query parameters (post_init): %d.\n", rc);
5296 		return (rc);
5297 	}
5298 
5299 	sc->sge.iq_start = val[0];
5300 	sc->sge.eq_start = val[1];
5301 	if ((int)val[3] > (int)val[2]) {
5302 		sc->tids.ftid_base = val[2];
5303 		sc->tids.ftid_end = val[3];
5304 		sc->tids.nftids = val[3] - val[2] + 1;
5305 	}
5306 	sc->vres.l2t.start = val[4];
5307 	sc->vres.l2t.size = val[5] - val[4] + 1;
5308 	/* val[5] is the last hwidx and it must not collide with F_SYNC_WR */
5309 	if (sc->vres.l2t.size > 0)
5310 		MPASS(fls(val[5]) <= S_SYNC_WR);
5311 	sc->params.core_vdd = val[6];
5312 
5313 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5314 	param[1] = FW_PARAM_PFVF(EQ_END);
5315 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5316 	if (rc != 0) {
5317 		device_printf(sc->dev,
5318 		    "failed to query parameters (post_init2): %d.\n", rc);
5319 		return (rc);
5320 	}
5321 	MPASS((int)val[0] >= sc->sge.iq_start);
5322 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5323 	MPASS((int)val[1] >= sc->sge.eq_start);
5324 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5325 
5326 	if (chip_id(sc) >= CHELSIO_T6) {
5327 
5328 		sc->tids.tid_base = t4_read_reg(sc,
5329 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5330 
5331 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5332 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5333 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5334 		if (rc != 0) {
5335 			device_printf(sc->dev,
5336 			   "failed to query hpfilter parameters: %d.\n", rc);
5337 			return (rc);
5338 		}
5339 		if ((int)val[1] > (int)val[0]) {
5340 			sc->tids.hpftid_base = val[0];
5341 			sc->tids.hpftid_end = val[1];
5342 			sc->tids.nhpftids = val[1] - val[0] + 1;
5343 
5344 			/*
5345 			 * These should go off if the layout changes and the
5346 			 * driver needs to catch up.
5347 			 */
5348 			MPASS(sc->tids.hpftid_base == 0);
5349 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5350 		}
5351 
5352 		param[0] = FW_PARAM_PFVF(RAWF_START);
5353 		param[1] = FW_PARAM_PFVF(RAWF_END);
5354 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5355 		if (rc != 0) {
5356 			device_printf(sc->dev,
5357 			   "failed to query rawf parameters: %d.\n", rc);
5358 			return (rc);
5359 		}
5360 		if ((int)val[1] > (int)val[0]) {
5361 			sc->rawf_base = val[0];
5362 			sc->nrawf = val[1] - val[0] + 1;
5363 		}
5364 	}
5365 
5366 	/*
5367 	 * The parameters that follow may not be available on all firmwares.  We
5368 	 * query them individually rather than in a compound query because old
5369 	 * firmwares fail the entire query if an unknown parameter is queried.
5370 	 */
5371 
5372 	/*
5373 	 * MPS buffer group configuration.
5374 	 */
5375 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5376 	val[0] = 0;
5377 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5378 	if (rc == 0)
5379 		sc->params.mps_bg_map = val[0];
5380 	else
5381 		sc->params.mps_bg_map = UINT32_MAX;	/* Not a legal value. */
5382 
5383 	param[0] = FW_PARAM_DEV(TPCHMAP);
5384 	val[0] = 0;
5385 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5386 	if (rc == 0)
5387 		sc->params.tp_ch_map = val[0];
5388 	else
5389 		sc->params.tp_ch_map = UINT32_MAX;	/* Not a legal value. */
5390 
5391 	/*
5392 	 * Determine whether the firmware supports the filter2 work request.
5393 	 */
5394 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5395 	val[0] = 0;
5396 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5397 	if (rc == 0)
5398 		sc->params.filter2_wr_support = val[0] != 0;
5399 	else
5400 		sc->params.filter2_wr_support = 0;
5401 
5402 	/*
5403 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5404 	 */
5405 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5406 	val[0] = 0;
5407 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5408 	if (rc == 0)
5409 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5410 	else
5411 		sc->params.ulptx_memwrite_dsgl = false;
5412 
5413 	/* FW_RI_FR_NSMR_TPTE_WR support */
5414 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5415 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5416 	if (rc == 0)
5417 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5418 	else
5419 		sc->params.fr_nsmr_tpte_wr_support = false;
5420 
5421 	/* Support for 512 SGL entries per FR MR. */
5422 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5423 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5424 	if (rc == 0)
5425 		sc->params.dev_512sgl_mr = val[0] != 0;
5426 	else
5427 		sc->params.dev_512sgl_mr = false;
5428 
5429 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5430 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5431 	if (rc == 0)
5432 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5433 	else
5434 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5435 
5436 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5437 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5438 	if (rc == 0) {
5439 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5440 		sc->params.nsched_cls = val[0];
5441 	} else
5442 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5443 
5444 	/* get capabilites */
5445 	bzero(&caps, sizeof(caps));
5446 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5447 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5448 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5449 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5450 	if (rc != 0) {
5451 		device_printf(sc->dev,
5452 		    "failed to get card capabilities: %d.\n", rc);
5453 		return (rc);
5454 	}
5455 
5456 #define READ_CAPS(x) do { \
5457 	sc->x = htobe16(caps.x); \
5458 } while (0)
5459 	READ_CAPS(nbmcaps);
5460 	READ_CAPS(linkcaps);
5461 	READ_CAPS(switchcaps);
5462 	READ_CAPS(niccaps);
5463 	READ_CAPS(toecaps);
5464 	READ_CAPS(rdmacaps);
5465 	READ_CAPS(cryptocaps);
5466 	READ_CAPS(iscsicaps);
5467 	READ_CAPS(fcoecaps);
5468 
5469 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5470 		MPASS(chip_id(sc) > CHELSIO_T4);
5471 		MPASS(sc->toecaps == 0);
5472 		sc->toecaps = 0;
5473 
5474 		param[0] = FW_PARAM_DEV(NTID);
5475 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5476 		if (rc != 0) {
5477 			device_printf(sc->dev,
5478 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5479 			return (rc);
5480 		}
5481 		sc->tids.ntids = val[0];
5482 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5483 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5484 			sc->tids.ntids -= sc->tids.nhpftids;
5485 		}
5486 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5487 		sc->params.hash_filter = 1;
5488 	}
5489 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5490 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5491 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5492 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5493 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5494 		if (rc != 0) {
5495 			device_printf(sc->dev,
5496 			    "failed to query NIC parameters: %d.\n", rc);
5497 			return (rc);
5498 		}
5499 		if ((int)val[1] > (int)val[0]) {
5500 			sc->tids.etid_base = val[0];
5501 			sc->tids.etid_end = val[1];
5502 			sc->tids.netids = val[1] - val[0] + 1;
5503 			sc->params.eo_wr_cred = val[2];
5504 			sc->params.ethoffload = 1;
5505 		}
5506 	}
5507 	if (sc->toecaps) {
5508 		/* query offload-related parameters */
5509 		param[0] = FW_PARAM_DEV(NTID);
5510 		param[1] = FW_PARAM_PFVF(SERVER_START);
5511 		param[2] = FW_PARAM_PFVF(SERVER_END);
5512 		param[3] = FW_PARAM_PFVF(TDDP_START);
5513 		param[4] = FW_PARAM_PFVF(TDDP_END);
5514 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5515 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5516 		if (rc != 0) {
5517 			device_printf(sc->dev,
5518 			    "failed to query TOE parameters: %d.\n", rc);
5519 			return (rc);
5520 		}
5521 		sc->tids.ntids = val[0];
5522 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5523 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5524 			sc->tids.ntids -= sc->tids.nhpftids;
5525 		}
5526 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5527 		if ((int)val[2] > (int)val[1]) {
5528 			sc->tids.stid_base = val[1];
5529 			sc->tids.nstids = val[2] - val[1] + 1;
5530 		}
5531 		sc->vres.ddp.start = val[3];
5532 		sc->vres.ddp.size = val[4] - val[3] + 1;
5533 		sc->params.ofldq_wr_cred = val[5];
5534 		sc->params.offload = 1;
5535 	} else {
5536 		/*
5537 		 * The firmware attempts memfree TOE configuration for -SO cards
5538 		 * and will report toecaps=0 if it runs out of resources (this
5539 		 * depends on the config file).  It may not report 0 for other
5540 		 * capabilities dependent on the TOE in this case.  Set them to
5541 		 * 0 here so that the driver doesn't bother tracking resources
5542 		 * that will never be used.
5543 		 */
5544 		sc->iscsicaps = 0;
5545 		sc->rdmacaps = 0;
5546 	}
5547 	if (sc->rdmacaps) {
5548 		param[0] = FW_PARAM_PFVF(STAG_START);
5549 		param[1] = FW_PARAM_PFVF(STAG_END);
5550 		param[2] = FW_PARAM_PFVF(RQ_START);
5551 		param[3] = FW_PARAM_PFVF(RQ_END);
5552 		param[4] = FW_PARAM_PFVF(PBL_START);
5553 		param[5] = FW_PARAM_PFVF(PBL_END);
5554 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5555 		if (rc != 0) {
5556 			device_printf(sc->dev,
5557 			    "failed to query RDMA parameters(1): %d.\n", rc);
5558 			return (rc);
5559 		}
5560 		sc->vres.stag.start = val[0];
5561 		sc->vres.stag.size = val[1] - val[0] + 1;
5562 		sc->vres.rq.start = val[2];
5563 		sc->vres.rq.size = val[3] - val[2] + 1;
5564 		sc->vres.pbl.start = val[4];
5565 		sc->vres.pbl.size = val[5] - val[4] + 1;
5566 
5567 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5568 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5569 		param[2] = FW_PARAM_PFVF(CQ_START);
5570 		param[3] = FW_PARAM_PFVF(CQ_END);
5571 		param[4] = FW_PARAM_PFVF(OCQ_START);
5572 		param[5] = FW_PARAM_PFVF(OCQ_END);
5573 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5574 		if (rc != 0) {
5575 			device_printf(sc->dev,
5576 			    "failed to query RDMA parameters(2): %d.\n", rc);
5577 			return (rc);
5578 		}
5579 		sc->vres.qp.start = val[0];
5580 		sc->vres.qp.size = val[1] - val[0] + 1;
5581 		sc->vres.cq.start = val[2];
5582 		sc->vres.cq.size = val[3] - val[2] + 1;
5583 		sc->vres.ocq.start = val[4];
5584 		sc->vres.ocq.size = val[5] - val[4] + 1;
5585 
5586 		param[0] = FW_PARAM_PFVF(SRQ_START);
5587 		param[1] = FW_PARAM_PFVF(SRQ_END);
5588 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5589 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5590 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5591 		if (rc != 0) {
5592 			device_printf(sc->dev,
5593 			    "failed to query RDMA parameters(3): %d.\n", rc);
5594 			return (rc);
5595 		}
5596 		sc->vres.srq.start = val[0];
5597 		sc->vres.srq.size = val[1] - val[0] + 1;
5598 		sc->params.max_ordird_qp = val[2];
5599 		sc->params.max_ird_adapter = val[3];
5600 	}
5601 	if (sc->iscsicaps) {
5602 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5603 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5604 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5605 		if (rc != 0) {
5606 			device_printf(sc->dev,
5607 			    "failed to query iSCSI parameters: %d.\n", rc);
5608 			return (rc);
5609 		}
5610 		sc->vres.iscsi.start = val[0];
5611 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5612 	}
5613 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5614 		param[0] = FW_PARAM_PFVF(TLS_START);
5615 		param[1] = FW_PARAM_PFVF(TLS_END);
5616 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5617 		if (rc != 0) {
5618 			device_printf(sc->dev,
5619 			    "failed to query TLS parameters: %d.\n", rc);
5620 			return (rc);
5621 		}
5622 		sc->vres.key.start = val[0];
5623 		sc->vres.key.size = val[1] - val[0] + 1;
5624 	}
5625 
5626 	/*
5627 	 * We've got the params we wanted to query directly from the firmware.
5628 	 * Grab some others via other means.
5629 	 */
5630 	t4_init_sge_params(sc);
5631 	t4_init_tp_params(sc);
5632 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5633 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5634 
5635 	rc = t4_verify_chip_settings(sc);
5636 	if (rc != 0)
5637 		return (rc);
5638 	t4_init_rx_buf_info(sc);
5639 
5640 	return (rc);
5641 }
5642 
5643 #ifdef KERN_TLS
5644 static void
5645 ktls_tick(void *arg)
5646 {
5647 	struct adapter *sc;
5648 	uint32_t tstamp;
5649 
5650 	sc = arg;
5651 	tstamp = tcp_ts_getticks();
5652 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5653 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5654 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5655 }
5656 
5657 static int
5658 t6_config_kern_tls(struct adapter *sc, bool enable)
5659 {
5660 	int rc;
5661 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5662 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5663 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5664 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5665 
5666 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5667 	if (rc != 0) {
5668 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5669 		    enable ?  "enable" : "disable", rc);
5670 		return (rc);
5671 	}
5672 
5673 	if (enable) {
5674 		sc->flags |= KERN_TLS_ON;
5675 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5676 		    C_HARDCLOCK);
5677 	} else {
5678 		sc->flags &= ~KERN_TLS_ON;
5679 		callout_stop(&sc->ktls_tick);
5680 	}
5681 
5682 	return (rc);
5683 }
5684 #endif
5685 
5686 static int
5687 set_params__post_init(struct adapter *sc)
5688 {
5689 	uint32_t mask, param, val;
5690 #ifdef TCP_OFFLOAD
5691 	int i, v, shift;
5692 #endif
5693 
5694 	/* ask for encapsulated CPLs */
5695 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5696 	val = 1;
5697 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5698 
5699 	/* Enable 32b port caps if the firmware supports it. */
5700 	param = FW_PARAM_PFVF(PORT_CAPS32);
5701 	val = 1;
5702 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5703 		sc->params.port_caps32 = 1;
5704 
5705 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5706 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5707 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5708 	    V_MASKFILTER(val - 1));
5709 
5710 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5711 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5712 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5713 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5714 	val = 0;
5715 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5716 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5717 		    F_ATTACKFILTERENABLE);
5718 		val |= F_DROPERRORATTACK;
5719 	}
5720 	if (t4_drop_ip_fragments != 0) {
5721 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5722 		    F_FRAGMENTDROP);
5723 		val |= F_DROPERRORFRAG;
5724 	}
5725 	if (t4_drop_pkts_with_l2_errors != 0)
5726 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5727 	if (t4_drop_pkts_with_l3_errors != 0) {
5728 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5729 		    F_DROPERRORCSUMIP;
5730 	}
5731 	if (t4_drop_pkts_with_l4_errors != 0) {
5732 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5733 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5734 	}
5735 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5736 
5737 #ifdef TCP_OFFLOAD
5738 	/*
5739 	 * Override the TOE timers with user provided tunables.  This is not the
5740 	 * recommended way to change the timers (the firmware config file is) so
5741 	 * these tunables are not documented.
5742 	 *
5743 	 * All the timer tunables are in microseconds.
5744 	 */
5745 	if (t4_toe_keepalive_idle != 0) {
5746 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5747 		v &= M_KEEPALIVEIDLE;
5748 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5749 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5750 	}
5751 	if (t4_toe_keepalive_interval != 0) {
5752 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5753 		v &= M_KEEPALIVEINTVL;
5754 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5755 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5756 	}
5757 	if (t4_toe_keepalive_count != 0) {
5758 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5759 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5760 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5761 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5762 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5763 	}
5764 	if (t4_toe_rexmt_min != 0) {
5765 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5766 		v &= M_RXTMIN;
5767 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5768 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5769 	}
5770 	if (t4_toe_rexmt_max != 0) {
5771 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5772 		v &= M_RXTMAX;
5773 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5774 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5775 	}
5776 	if (t4_toe_rexmt_count != 0) {
5777 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5778 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5779 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5780 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5781 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5782 	}
5783 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5784 		if (t4_toe_rexmt_backoff[i] != -1) {
5785 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5786 			shift = (i & 3) << 3;
5787 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5788 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5789 		}
5790 	}
5791 #endif
5792 
5793 	/*
5794 	 * Limit TOE connections to 2 reassembly "islands".  This is
5795 	 * required to permit migrating TOE connections to either
5796 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5797 	 */
5798 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5799 	    V_PASSMODE(2));
5800 
5801 #ifdef KERN_TLS
5802 	if (is_ktls(sc)) {
5803 		sc->tlst.inline_keys = t4_tls_inline_keys;
5804 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5805 		if (t4_kern_tls != 0 && is_t6(sc))
5806 			t6_config_kern_tls(sc, true);
5807 	}
5808 #endif
5809 	return (0);
5810 }
5811 
5812 #undef FW_PARAM_PFVF
5813 #undef FW_PARAM_DEV
5814 
5815 static void
5816 t4_set_desc(struct adapter *sc)
5817 {
5818 	struct adapter_params *p = &sc->params;
5819 
5820 	device_set_descf(sc->dev, "Chelsio %s", p->vpd.id);
5821 }
5822 
5823 static inline void
5824 ifmedia_add4(struct ifmedia *ifm, int m)
5825 {
5826 
5827 	ifmedia_add(ifm, m, 0, NULL);
5828 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5829 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5830 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5831 }
5832 
5833 /*
5834  * This is the selected media, which is not quite the same as the active media.
5835  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5836  * and active are not the same, and "media: Ethernet selected" otherwise.
5837  */
5838 static void
5839 set_current_media(struct port_info *pi)
5840 {
5841 	struct link_config *lc;
5842 	struct ifmedia *ifm;
5843 	int mword;
5844 	u_int speed;
5845 
5846 	PORT_LOCK_ASSERT_OWNED(pi);
5847 
5848 	/* Leave current media alone if it's already set to IFM_NONE. */
5849 	ifm = &pi->media;
5850 	if (ifm->ifm_cur != NULL &&
5851 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5852 		return;
5853 
5854 	lc = &pi->link_cfg;
5855 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5856 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5857 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5858 		return;
5859 	}
5860 	mword = IFM_ETHER | IFM_FDX;
5861 	if (lc->requested_fc & PAUSE_TX)
5862 		mword |= IFM_ETH_TXPAUSE;
5863 	if (lc->requested_fc & PAUSE_RX)
5864 		mword |= IFM_ETH_RXPAUSE;
5865 	if (lc->requested_speed == 0)
5866 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5867 	else
5868 		speed = lc->requested_speed;
5869 	mword |= port_mword(pi, speed_to_fwcap(speed));
5870 	ifmedia_set(ifm, mword);
5871 }
5872 
5873 /*
5874  * Returns true if the ifmedia list for the port cannot change.
5875  */
5876 static bool
5877 fixed_ifmedia(struct port_info *pi)
5878 {
5879 
5880 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5881 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5882 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5883 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5884 	    pi->port_type == FW_PORT_TYPE_KX ||
5885 	    pi->port_type == FW_PORT_TYPE_KR ||
5886 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5887 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5888 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5889 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5890 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5891 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5892 }
5893 
5894 static void
5895 build_medialist(struct port_info *pi)
5896 {
5897 	uint32_t ss, speed;
5898 	int unknown, mword, bit;
5899 	struct link_config *lc;
5900 	struct ifmedia *ifm;
5901 
5902 	PORT_LOCK_ASSERT_OWNED(pi);
5903 
5904 	if (pi->flags & FIXED_IFMEDIA)
5905 		return;
5906 
5907 	/*
5908 	 * Rebuild the ifmedia list.
5909 	 */
5910 	ifm = &pi->media;
5911 	ifmedia_removeall(ifm);
5912 	lc = &pi->link_cfg;
5913 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5914 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5915 		MPASS(ss != 0);
5916 no_media:
5917 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5918 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5919 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5920 		return;
5921 	}
5922 
5923 	unknown = 0;
5924 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5925 		speed = 1 << bit;
5926 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5927 		if (ss & speed) {
5928 			mword = port_mword(pi, speed);
5929 			if (mword == IFM_NONE) {
5930 				goto no_media;
5931 			} else if (mword == IFM_UNKNOWN)
5932 				unknown++;
5933 			else
5934 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5935 		}
5936 	}
5937 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5938 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5939 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5940 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5941 
5942 	set_current_media(pi);
5943 }
5944 
5945 /*
5946  * Initialize the requested fields in the link config based on driver tunables.
5947  */
5948 static void
5949 init_link_config(struct port_info *pi)
5950 {
5951 	struct link_config *lc = &pi->link_cfg;
5952 
5953 	PORT_LOCK_ASSERT_OWNED(pi);
5954 
5955 	lc->requested_caps = 0;
5956 	lc->requested_speed = 0;
5957 
5958 	if (t4_autoneg == 0)
5959 		lc->requested_aneg = AUTONEG_DISABLE;
5960 	else if (t4_autoneg == 1)
5961 		lc->requested_aneg = AUTONEG_ENABLE;
5962 	else
5963 		lc->requested_aneg = AUTONEG_AUTO;
5964 
5965 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5966 	    PAUSE_AUTONEG);
5967 
5968 	if (t4_fec & FEC_AUTO)
5969 		lc->requested_fec = FEC_AUTO;
5970 	else if (t4_fec == 0)
5971 		lc->requested_fec = FEC_NONE;
5972 	else {
5973 		/* -1 is handled by the FEC_AUTO block above and not here. */
5974 		lc->requested_fec = t4_fec &
5975 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5976 		if (lc->requested_fec == 0)
5977 			lc->requested_fec = FEC_AUTO;
5978 	}
5979 	if (t4_force_fec < 0)
5980 		lc->force_fec = -1;
5981 	else if (t4_force_fec > 0)
5982 		lc->force_fec = 1;
5983 	else
5984 		lc->force_fec = 0;
5985 }
5986 
5987 /*
5988  * Makes sure that all requested settings comply with what's supported by the
5989  * port.  Returns the number of settings that were invalid and had to be fixed.
5990  */
5991 static int
5992 fixup_link_config(struct port_info *pi)
5993 {
5994 	int n = 0;
5995 	struct link_config *lc = &pi->link_cfg;
5996 	uint32_t fwspeed;
5997 
5998 	PORT_LOCK_ASSERT_OWNED(pi);
5999 
6000 	/* Speed (when not autonegotiating) */
6001 	if (lc->requested_speed != 0) {
6002 		fwspeed = speed_to_fwcap(lc->requested_speed);
6003 		if ((fwspeed & lc->pcaps) == 0) {
6004 			n++;
6005 			lc->requested_speed = 0;
6006 		}
6007 	}
6008 
6009 	/* Link autonegotiation */
6010 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
6011 	    lc->requested_aneg == AUTONEG_DISABLE ||
6012 	    lc->requested_aneg == AUTONEG_AUTO);
6013 	if (lc->requested_aneg == AUTONEG_ENABLE &&
6014 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
6015 		n++;
6016 		lc->requested_aneg = AUTONEG_AUTO;
6017 	}
6018 
6019 	/* Flow control */
6020 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
6021 	if (lc->requested_fc & PAUSE_TX &&
6022 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
6023 		n++;
6024 		lc->requested_fc &= ~PAUSE_TX;
6025 	}
6026 	if (lc->requested_fc & PAUSE_RX &&
6027 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
6028 		n++;
6029 		lc->requested_fc &= ~PAUSE_RX;
6030 	}
6031 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
6032 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
6033 		n++;
6034 		lc->requested_fc |= PAUSE_AUTONEG;
6035 	}
6036 
6037 	/* FEC */
6038 	if ((lc->requested_fec & FEC_RS &&
6039 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
6040 	    (lc->requested_fec & FEC_BASER_RS &&
6041 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
6042 		n++;
6043 		lc->requested_fec = FEC_AUTO;
6044 	}
6045 
6046 	return (n);
6047 }
6048 
6049 /*
6050  * Apply the requested L1 settings, which are expected to be valid, to the
6051  * hardware.
6052  */
6053 static int
6054 apply_link_config(struct port_info *pi)
6055 {
6056 	struct adapter *sc = pi->adapter;
6057 	struct link_config *lc = &pi->link_cfg;
6058 	int rc;
6059 
6060 #ifdef INVARIANTS
6061 	ASSERT_SYNCHRONIZED_OP(sc);
6062 	PORT_LOCK_ASSERT_OWNED(pi);
6063 
6064 	if (lc->requested_aneg == AUTONEG_ENABLE)
6065 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6066 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6067 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6068 	if (lc->requested_fc & PAUSE_TX)
6069 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6070 	if (lc->requested_fc & PAUSE_RX)
6071 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6072 	if (lc->requested_fec & FEC_RS)
6073 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6074 	if (lc->requested_fec & FEC_BASER_RS)
6075 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6076 #endif
6077 	if (!(sc->flags & IS_VF)) {
6078 		rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6079 		if (rc != 0) {
6080 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6081 			return (rc);
6082 		}
6083 	}
6084 
6085 	/*
6086 	 * An L1_CFG will almost always result in a link-change event if the
6087 	 * link is up, and the driver will refresh the actual fec/fc/etc. when
6088 	 * the notification is processed.  If the link is down then the actual
6089 	 * settings are meaningless.
6090 	 *
6091 	 * This takes care of the case where a change in the L1 settings may not
6092 	 * result in a notification.
6093 	 */
6094 	if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6095 		lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6096 
6097 	return (0);
6098 }
6099 
6100 #define FW_MAC_EXACT_CHUNK	7
6101 struct mcaddr_ctx {
6102 	if_t ifp;
6103 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6104 	uint64_t hash;
6105 	int i;
6106 	int del;
6107 	int rc;
6108 };
6109 
6110 static u_int
6111 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6112 {
6113 	struct mcaddr_ctx *ctx = arg;
6114 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6115 	struct port_info *pi = vi->pi;
6116 	struct adapter *sc = pi->adapter;
6117 
6118 	if (ctx->rc < 0)
6119 		return (0);
6120 
6121 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6122 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6123 	ctx->i++;
6124 
6125 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6126 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6127 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6128 		if (ctx->rc < 0) {
6129 			int j;
6130 
6131 			for (j = 0; j < ctx->i; j++) {
6132 				if_printf(ctx->ifp,
6133 				    "failed to add mc address"
6134 				    " %02x:%02x:%02x:"
6135 				    "%02x:%02x:%02x rc=%d\n",
6136 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6137 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6138 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6139 				    -ctx->rc);
6140 			}
6141 			return (0);
6142 		}
6143 		ctx->del = 0;
6144 		ctx->i = 0;
6145 	}
6146 
6147 	return (1);
6148 }
6149 
6150 /*
6151  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6152  * indicates which parameters should be programmed (the rest are left alone).
6153  */
6154 int
6155 update_mac_settings(if_t ifp, int flags)
6156 {
6157 	int rc = 0;
6158 	struct vi_info *vi = if_getsoftc(ifp);
6159 	struct port_info *pi = vi->pi;
6160 	struct adapter *sc = pi->adapter;
6161 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6162 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6163 
6164 	ASSERT_SYNCHRONIZED_OP(sc);
6165 	KASSERT(flags, ("%s: not told what to update.", __func__));
6166 
6167 	if (flags & XGMAC_MTU)
6168 		mtu = if_getmtu(ifp);
6169 
6170 	if (flags & XGMAC_PROMISC)
6171 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6172 
6173 	if (flags & XGMAC_ALLMULTI)
6174 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6175 
6176 	if (flags & XGMAC_VLANEX)
6177 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6178 
6179 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6180 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6181 		    allmulti, 1, vlanex, false);
6182 		if (rc) {
6183 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6184 			    rc);
6185 			return (rc);
6186 		}
6187 	}
6188 
6189 	if (flags & XGMAC_UCADDR) {
6190 		uint8_t ucaddr[ETHER_ADDR_LEN];
6191 
6192 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6193 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6194 		    ucaddr, true, &vi->smt_idx);
6195 		if (rc < 0) {
6196 			rc = -rc;
6197 			if_printf(ifp, "change_mac failed: %d\n", rc);
6198 			return (rc);
6199 		} else {
6200 			vi->xact_addr_filt = rc;
6201 			rc = 0;
6202 		}
6203 	}
6204 
6205 	if (flags & XGMAC_MCADDRS) {
6206 		struct epoch_tracker et;
6207 		struct mcaddr_ctx ctx;
6208 		int j;
6209 
6210 		ctx.ifp = ifp;
6211 		ctx.hash = 0;
6212 		ctx.i = 0;
6213 		ctx.del = 1;
6214 		ctx.rc = 0;
6215 		/*
6216 		 * Unlike other drivers, we accumulate list of pointers into
6217 		 * interface address lists and we need to keep it safe even
6218 		 * after if_foreach_llmaddr() returns, thus we must enter the
6219 		 * network epoch.
6220 		 */
6221 		NET_EPOCH_ENTER(et);
6222 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6223 		if (ctx.rc < 0) {
6224 			NET_EPOCH_EXIT(et);
6225 			rc = -ctx.rc;
6226 			return (rc);
6227 		}
6228 		if (ctx.i > 0) {
6229 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6230 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6231 			NET_EPOCH_EXIT(et);
6232 			if (rc < 0) {
6233 				rc = -rc;
6234 				for (j = 0; j < ctx.i; j++) {
6235 					if_printf(ifp,
6236 					    "failed to add mcast address"
6237 					    " %02x:%02x:%02x:"
6238 					    "%02x:%02x:%02x rc=%d\n",
6239 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6240 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6241 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6242 					    rc);
6243 				}
6244 				return (rc);
6245 			}
6246 			ctx.del = 0;
6247 		} else
6248 			NET_EPOCH_EXIT(et);
6249 
6250 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6251 		if (rc != 0)
6252 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6253 			    rc);
6254 		if (ctx.del == 0) {
6255 			/* We clobbered the VXLAN entry if there was one. */
6256 			pi->vxlan_tcam_entry = false;
6257 		}
6258 	}
6259 
6260 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6261 	    pi->vxlan_tcam_entry == false) {
6262 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6263 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6264 		    true);
6265 		if (rc < 0) {
6266 			rc = -rc;
6267 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6268 			    rc);
6269 		} else {
6270 			MPASS(rc == sc->rawf_base + pi->port_id);
6271 			rc = 0;
6272 			pi->vxlan_tcam_entry = true;
6273 		}
6274 	}
6275 
6276 	return (rc);
6277 }
6278 
6279 /*
6280  * {begin|end}_synchronized_op must be called from the same thread.
6281  */
6282 int
6283 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6284     char *wmesg)
6285 {
6286 	int rc, pri;
6287 
6288 #ifdef WITNESS
6289 	/* the caller thinks it's ok to sleep, but is it really? */
6290 	if (flags & SLEEP_OK)
6291 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6292 		    "begin_synchronized_op");
6293 #endif
6294 
6295 	if (INTR_OK)
6296 		pri = PCATCH;
6297 	else
6298 		pri = 0;
6299 
6300 	ADAPTER_LOCK(sc);
6301 	for (;;) {
6302 
6303 		if (vi && IS_DETACHING(vi)) {
6304 			rc = ENXIO;
6305 			goto done;
6306 		}
6307 
6308 		if (!IS_BUSY(sc)) {
6309 			rc = 0;
6310 			break;
6311 		}
6312 
6313 		if (!(flags & SLEEP_OK)) {
6314 			rc = EBUSY;
6315 			goto done;
6316 		}
6317 
6318 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6319 			rc = EINTR;
6320 			goto done;
6321 		}
6322 	}
6323 
6324 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6325 	SET_BUSY(sc);
6326 #ifdef INVARIANTS
6327 	sc->last_op = wmesg;
6328 	sc->last_op_thr = curthread;
6329 	sc->last_op_flags = flags;
6330 #endif
6331 
6332 done:
6333 	if (!(flags & HOLD_LOCK) || rc)
6334 		ADAPTER_UNLOCK(sc);
6335 
6336 	return (rc);
6337 }
6338 
6339 /*
6340  * Tell if_ioctl and if_init that the VI is going away.  This is
6341  * special variant of begin_synchronized_op and must be paired with a
6342  * call to end_vi_detach.
6343  */
6344 void
6345 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6346 {
6347 	ADAPTER_LOCK(sc);
6348 	SET_DETACHING(vi);
6349 	wakeup(&sc->flags);
6350 	while (IS_BUSY(sc))
6351 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6352 	SET_BUSY(sc);
6353 #ifdef INVARIANTS
6354 	sc->last_op = "t4detach";
6355 	sc->last_op_thr = curthread;
6356 	sc->last_op_flags = 0;
6357 #endif
6358 	ADAPTER_UNLOCK(sc);
6359 }
6360 
6361 void
6362 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6363 {
6364 	ADAPTER_LOCK(sc);
6365 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6366 	CLR_BUSY(sc);
6367 	CLR_DETACHING(vi);
6368 	wakeup(&sc->flags);
6369 	ADAPTER_UNLOCK(sc);
6370 }
6371 
6372 /*
6373  * {begin|end}_synchronized_op must be called from the same thread.
6374  */
6375 void
6376 end_synchronized_op(struct adapter *sc, int flags)
6377 {
6378 
6379 	if (flags & LOCK_HELD)
6380 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6381 	else
6382 		ADAPTER_LOCK(sc);
6383 
6384 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6385 	CLR_BUSY(sc);
6386 	wakeup(&sc->flags);
6387 	ADAPTER_UNLOCK(sc);
6388 }
6389 
6390 static int
6391 cxgbe_init_synchronized(struct vi_info *vi)
6392 {
6393 	struct port_info *pi = vi->pi;
6394 	struct adapter *sc = pi->adapter;
6395 	if_t ifp = vi->ifp;
6396 	int rc = 0, i;
6397 	struct sge_txq *txq;
6398 
6399 	ASSERT_SYNCHRONIZED_OP(sc);
6400 
6401 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6402 		return (0);	/* already running */
6403 
6404 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6405 		return (rc);	/* error message displayed already */
6406 
6407 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6408 		return (rc); /* error message displayed already */
6409 
6410 	rc = update_mac_settings(ifp, XGMAC_ALL);
6411 	if (rc)
6412 		goto done;	/* error message displayed already */
6413 
6414 	PORT_LOCK(pi);
6415 	if (pi->up_vis == 0) {
6416 		t4_update_port_info(pi);
6417 		fixup_link_config(pi);
6418 		build_medialist(pi);
6419 		apply_link_config(pi);
6420 	}
6421 
6422 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6423 	if (rc != 0) {
6424 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6425 		PORT_UNLOCK(pi);
6426 		goto done;
6427 	}
6428 
6429 	/*
6430 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6431 	 * if this changes.
6432 	 */
6433 
6434 	for_each_txq(vi, i, txq) {
6435 		TXQ_LOCK(txq);
6436 		txq->eq.flags |= EQ_ENABLED;
6437 		TXQ_UNLOCK(txq);
6438 	}
6439 
6440 	/*
6441 	 * The first iq of the first port to come up is used for tracing.
6442 	 */
6443 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6444 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6445 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6446 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6447 		    V_QUEUENUMBER(sc->traceq));
6448 		pi->flags |= HAS_TRACEQ;
6449 	}
6450 
6451 	/* all ok */
6452 	pi->up_vis++;
6453 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6454 	if (pi->link_cfg.link_ok)
6455 		t4_os_link_changed(pi);
6456 	PORT_UNLOCK(pi);
6457 
6458 	mtx_lock(&vi->tick_mtx);
6459 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6460 		callout_reset(&vi->tick, hz, vi_tick, vi);
6461 	else
6462 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6463 	mtx_unlock(&vi->tick_mtx);
6464 done:
6465 	if (rc != 0)
6466 		cxgbe_uninit_synchronized(vi);
6467 
6468 	return (rc);
6469 }
6470 
6471 /*
6472  * Idempotent.
6473  */
6474 static int
6475 cxgbe_uninit_synchronized(struct vi_info *vi)
6476 {
6477 	struct port_info *pi = vi->pi;
6478 	struct adapter *sc = pi->adapter;
6479 	if_t ifp = vi->ifp;
6480 	int rc, i;
6481 	struct sge_txq *txq;
6482 
6483 	ASSERT_SYNCHRONIZED_OP(sc);
6484 
6485 	if (!(vi->flags & VI_INIT_DONE)) {
6486 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6487 			KASSERT(0, ("uninited VI is running"));
6488 			if_printf(ifp, "uninited VI with running ifnet.  "
6489 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6490 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6491 			    if_getdrvflags(ifp));
6492 		}
6493 		return (0);
6494 	}
6495 
6496 	/*
6497 	 * Disable the VI so that all its data in either direction is discarded
6498 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6499 	 * tick) intact as the TP can deliver negative advice or data that it's
6500 	 * holding in its RAM (for an offloaded connection) even after the VI is
6501 	 * disabled.
6502 	 */
6503 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6504 	if (rc) {
6505 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6506 		return (rc);
6507 	}
6508 
6509 	for_each_txq(vi, i, txq) {
6510 		TXQ_LOCK(txq);
6511 		txq->eq.flags &= ~EQ_ENABLED;
6512 		TXQ_UNLOCK(txq);
6513 	}
6514 
6515 	mtx_lock(&vi->tick_mtx);
6516 	callout_stop(&vi->tick);
6517 	mtx_unlock(&vi->tick_mtx);
6518 
6519 	PORT_LOCK(pi);
6520 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6521 		PORT_UNLOCK(pi);
6522 		return (0);
6523 	}
6524 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6525 	pi->up_vis--;
6526 	if (pi->up_vis > 0) {
6527 		PORT_UNLOCK(pi);
6528 		return (0);
6529 	}
6530 
6531 	pi->link_cfg.link_ok = false;
6532 	pi->link_cfg.speed = 0;
6533 	pi->link_cfg.link_down_rc = 255;
6534 	t4_os_link_changed(pi);
6535 	PORT_UNLOCK(pi);
6536 
6537 	return (0);
6538 }
6539 
6540 /*
6541  * It is ok for this function to fail midway and return right away.  t4_detach
6542  * will walk the entire sc->irq list and clean up whatever is valid.
6543  */
6544 int
6545 t4_setup_intr_handlers(struct adapter *sc)
6546 {
6547 	int rc, rid, p, q, v;
6548 	char s[8];
6549 	struct irq *irq;
6550 	struct port_info *pi;
6551 	struct vi_info *vi;
6552 	struct sge *sge = &sc->sge;
6553 	struct sge_rxq *rxq;
6554 #ifdef TCP_OFFLOAD
6555 	struct sge_ofld_rxq *ofld_rxq;
6556 #endif
6557 #ifdef DEV_NETMAP
6558 	struct sge_nm_rxq *nm_rxq;
6559 #endif
6560 #ifdef RSS
6561 	int nbuckets = rss_getnumbuckets();
6562 #endif
6563 
6564 	/*
6565 	 * Setup interrupts.
6566 	 */
6567 	irq = &sc->irq[0];
6568 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6569 	if (forwarding_intr_to_fwq(sc))
6570 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6571 
6572 	/* Multiple interrupts. */
6573 	if (sc->flags & IS_VF)
6574 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6575 		    ("%s: too few intr.", __func__));
6576 	else
6577 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6578 		    ("%s: too few intr.", __func__));
6579 
6580 	/* The first one is always error intr on PFs */
6581 	if (!(sc->flags & IS_VF)) {
6582 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6583 		if (rc != 0)
6584 			return (rc);
6585 		irq++;
6586 		rid++;
6587 	}
6588 
6589 	/* The second one is always the firmware event queue (first on VFs) */
6590 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6591 	if (rc != 0)
6592 		return (rc);
6593 	irq++;
6594 	rid++;
6595 
6596 	for_each_port(sc, p) {
6597 		pi = sc->port[p];
6598 		for_each_vi(pi, v, vi) {
6599 			vi->first_intr = rid - 1;
6600 
6601 			if (vi->nnmrxq > 0) {
6602 				int n = max(vi->nrxq, vi->nnmrxq);
6603 
6604 				rxq = &sge->rxq[vi->first_rxq];
6605 #ifdef DEV_NETMAP
6606 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6607 #endif
6608 				for (q = 0; q < n; q++) {
6609 					snprintf(s, sizeof(s), "%x%c%x", p,
6610 					    'a' + v, q);
6611 					if (q < vi->nrxq)
6612 						irq->rxq = rxq++;
6613 #ifdef DEV_NETMAP
6614 					if (q < vi->nnmrxq)
6615 						irq->nm_rxq = nm_rxq++;
6616 
6617 					if (irq->nm_rxq != NULL &&
6618 					    irq->rxq == NULL) {
6619 						/* Netmap rx only */
6620 						rc = t4_alloc_irq(sc, irq, rid,
6621 						    t4_nm_intr, irq->nm_rxq, s);
6622 					}
6623 					if (irq->nm_rxq != NULL &&
6624 					    irq->rxq != NULL) {
6625 						/* NIC and Netmap rx */
6626 						rc = t4_alloc_irq(sc, irq, rid,
6627 						    t4_vi_intr, irq, s);
6628 					}
6629 #endif
6630 					if (irq->rxq != NULL &&
6631 					    irq->nm_rxq == NULL) {
6632 						/* NIC rx only */
6633 						rc = t4_alloc_irq(sc, irq, rid,
6634 						    t4_intr, irq->rxq, s);
6635 					}
6636 					if (rc != 0)
6637 						return (rc);
6638 #ifdef RSS
6639 					if (q < vi->nrxq) {
6640 						bus_bind_intr(sc->dev, irq->res,
6641 						    rss_getcpu(q % nbuckets));
6642 					}
6643 #endif
6644 					irq++;
6645 					rid++;
6646 					vi->nintr++;
6647 				}
6648 			} else {
6649 				for_each_rxq(vi, q, rxq) {
6650 					snprintf(s, sizeof(s), "%x%c%x", p,
6651 					    'a' + v, q);
6652 					rc = t4_alloc_irq(sc, irq, rid,
6653 					    t4_intr, rxq, s);
6654 					if (rc != 0)
6655 						return (rc);
6656 #ifdef RSS
6657 					bus_bind_intr(sc->dev, irq->res,
6658 					    rss_getcpu(q % nbuckets));
6659 #endif
6660 					irq++;
6661 					rid++;
6662 					vi->nintr++;
6663 				}
6664 			}
6665 #ifdef TCP_OFFLOAD
6666 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6667 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6668 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6669 				    ofld_rxq, s);
6670 				if (rc != 0)
6671 					return (rc);
6672 				irq++;
6673 				rid++;
6674 				vi->nintr++;
6675 			}
6676 #endif
6677 		}
6678 	}
6679 	MPASS(irq == &sc->irq[sc->intr_count]);
6680 
6681 	return (0);
6682 }
6683 
6684 static void
6685 write_global_rss_key(struct adapter *sc)
6686 {
6687 #ifdef RSS
6688 	int i;
6689 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6690 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6691 
6692 	CTASSERT(RSS_KEYSIZE == 40);
6693 
6694 	rss_getkey((void *)&raw_rss_key[0]);
6695 	for (i = 0; i < nitems(rss_key); i++) {
6696 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6697 	}
6698 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6699 #endif
6700 }
6701 
6702 /*
6703  * Idempotent.
6704  */
6705 static int
6706 adapter_full_init(struct adapter *sc)
6707 {
6708 	int rc, i;
6709 
6710 	ASSERT_SYNCHRONIZED_OP(sc);
6711 
6712 	/*
6713 	 * queues that belong to the adapter (not any particular port).
6714 	 */
6715 	rc = t4_setup_adapter_queues(sc);
6716 	if (rc != 0)
6717 		return (rc);
6718 
6719 	MPASS(sc->params.nports <= nitems(sc->tq));
6720 	for (i = 0; i < sc->params.nports; i++) {
6721 		if (sc->tq[i] != NULL)
6722 			continue;
6723 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6724 		    taskqueue_thread_enqueue, &sc->tq[i]);
6725 		if (sc->tq[i] == NULL) {
6726 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6727 			return (ENOMEM);
6728 		}
6729 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6730 		    device_get_nameunit(sc->dev), i);
6731 	}
6732 
6733 	if (!(sc->flags & IS_VF)) {
6734 		write_global_rss_key(sc);
6735 		t4_intr_enable(sc);
6736 	}
6737 	return (0);
6738 }
6739 
6740 int
6741 adapter_init(struct adapter *sc)
6742 {
6743 	int rc;
6744 
6745 	ASSERT_SYNCHRONIZED_OP(sc);
6746 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6747 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6748 	    ("%s: FULL_INIT_DONE already", __func__));
6749 
6750 	rc = adapter_full_init(sc);
6751 	if (rc != 0)
6752 		adapter_full_uninit(sc);
6753 	else
6754 		sc->flags |= FULL_INIT_DONE;
6755 
6756 	return (rc);
6757 }
6758 
6759 /*
6760  * Idempotent.
6761  */
6762 static void
6763 adapter_full_uninit(struct adapter *sc)
6764 {
6765 	int i;
6766 
6767 	t4_teardown_adapter_queues(sc);
6768 
6769 	for (i = 0; i < nitems(sc->tq); i++) {
6770 		if (sc->tq[i] == NULL)
6771 			continue;
6772 		taskqueue_free(sc->tq[i]);
6773 		sc->tq[i] = NULL;
6774 	}
6775 
6776 	sc->flags &= ~FULL_INIT_DONE;
6777 }
6778 
6779 #ifdef RSS
6780 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6781     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6782     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6783     RSS_HASHTYPE_RSS_UDP_IPV6)
6784 
6785 /* Translates kernel hash types to hardware. */
6786 static int
6787 hashconfig_to_hashen(int hashconfig)
6788 {
6789 	int hashen = 0;
6790 
6791 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6792 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6793 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6794 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6795 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6796 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6797 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6798 	}
6799 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6800 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6801 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6802 	}
6803 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6804 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6805 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6806 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6807 
6808 	return (hashen);
6809 }
6810 
6811 /* Translates hardware hash types to kernel. */
6812 static int
6813 hashen_to_hashconfig(int hashen)
6814 {
6815 	int hashconfig = 0;
6816 
6817 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6818 		/*
6819 		 * If UDP hashing was enabled it must have been enabled for
6820 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6821 		 * enabling any 4-tuple hash is nonsense configuration.
6822 		 */
6823 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6824 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6825 
6826 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6827 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6828 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6829 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6830 	}
6831 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6832 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6833 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6834 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6835 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6836 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6837 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6838 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6839 
6840 	return (hashconfig);
6841 }
6842 #endif
6843 
6844 /*
6845  * Idempotent.
6846  */
6847 static int
6848 vi_full_init(struct vi_info *vi)
6849 {
6850 	struct adapter *sc = vi->adapter;
6851 	struct sge_rxq *rxq;
6852 	int rc, i, j;
6853 #ifdef RSS
6854 	int nbuckets = rss_getnumbuckets();
6855 	int hashconfig = rss_gethashconfig();
6856 	int extra;
6857 #endif
6858 
6859 	ASSERT_SYNCHRONIZED_OP(sc);
6860 
6861 	/*
6862 	 * Allocate tx/rx/fl queues for this VI.
6863 	 */
6864 	rc = t4_setup_vi_queues(vi);
6865 	if (rc != 0)
6866 		return (rc);
6867 
6868 	/*
6869 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6870 	 */
6871 	if (vi->nrxq > vi->rss_size) {
6872 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6873 		    "some queues will never receive traffic.\n", vi->nrxq,
6874 		    vi->rss_size);
6875 	} else if (vi->rss_size % vi->nrxq) {
6876 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6877 		    "expect uneven traffic distribution.\n", vi->nrxq,
6878 		    vi->rss_size);
6879 	}
6880 #ifdef RSS
6881 	if (vi->nrxq != nbuckets) {
6882 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6883 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6884 	}
6885 #endif
6886 	if (vi->rss == NULL)
6887 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6888 		    M_ZERO | M_WAITOK);
6889 	for (i = 0; i < vi->rss_size;) {
6890 #ifdef RSS
6891 		j = rss_get_indirection_to_bucket(i);
6892 		j %= vi->nrxq;
6893 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6894 		vi->rss[i++] = rxq->iq.abs_id;
6895 #else
6896 		for_each_rxq(vi, j, rxq) {
6897 			vi->rss[i++] = rxq->iq.abs_id;
6898 			if (i == vi->rss_size)
6899 				break;
6900 		}
6901 #endif
6902 	}
6903 
6904 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6905 	    vi->rss, vi->rss_size);
6906 	if (rc != 0) {
6907 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6908 		return (rc);
6909 	}
6910 
6911 #ifdef RSS
6912 	vi->hashen = hashconfig_to_hashen(hashconfig);
6913 
6914 	/*
6915 	 * We may have had to enable some hashes even though the global config
6916 	 * wants them disabled.  This is a potential problem that must be
6917 	 * reported to the user.
6918 	 */
6919 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6920 
6921 	/*
6922 	 * If we consider only the supported hash types, then the enabled hashes
6923 	 * are a superset of the requested hashes.  In other words, there cannot
6924 	 * be any supported hash that was requested but not enabled, but there
6925 	 * can be hashes that were not requested but had to be enabled.
6926 	 */
6927 	extra &= SUPPORTED_RSS_HASHTYPES;
6928 	MPASS((extra & hashconfig) == 0);
6929 
6930 	if (extra) {
6931 		CH_ALERT(vi,
6932 		    "global RSS config (0x%x) cannot be accommodated.\n",
6933 		    hashconfig);
6934 	}
6935 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6936 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6937 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6938 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6939 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6940 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6941 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6942 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6943 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6944 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6945 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6946 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6947 #else
6948 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6949 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6950 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6951 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6952 #endif
6953 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6954 	    0, 0);
6955 	if (rc != 0) {
6956 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6957 		return (rc);
6958 	}
6959 
6960 	return (0);
6961 }
6962 
6963 int
6964 vi_init(struct vi_info *vi)
6965 {
6966 	int rc;
6967 
6968 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6969 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6970 	    ("%s: VI_INIT_DONE already", __func__));
6971 
6972 	rc = vi_full_init(vi);
6973 	if (rc != 0)
6974 		vi_full_uninit(vi);
6975 	else
6976 		vi->flags |= VI_INIT_DONE;
6977 
6978 	return (rc);
6979 }
6980 
6981 /*
6982  * Idempotent.
6983  */
6984 static void
6985 vi_full_uninit(struct vi_info *vi)
6986 {
6987 
6988 	if (vi->flags & VI_INIT_DONE) {
6989 		quiesce_vi(vi);
6990 		free(vi->rss, M_CXGBE);
6991 		free(vi->nm_rss, M_CXGBE);
6992 	}
6993 
6994 	t4_teardown_vi_queues(vi);
6995 	vi->flags &= ~VI_INIT_DONE;
6996 }
6997 
6998 static void
6999 quiesce_txq(struct sge_txq *txq)
7000 {
7001 	struct sge_eq *eq = &txq->eq;
7002 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
7003 
7004 	MPASS(eq->flags & EQ_SW_ALLOCATED);
7005 	MPASS(!(eq->flags & EQ_ENABLED));
7006 
7007 	/* Wait for the mp_ring to empty. */
7008 	while (!mp_ring_is_idle(txq->r)) {
7009 		mp_ring_check_drainage(txq->r, 4096);
7010 		pause("rquiesce", 1);
7011 	}
7012 	MPASS(txq->txp.npkt == 0);
7013 
7014 	if (eq->flags & EQ_HW_ALLOCATED) {
7015 		/*
7016 		 * Hardware is alive and working normally.  Wait for it to
7017 		 * finish and then wait for the driver to catch up and reclaim
7018 		 * all descriptors.
7019 		 */
7020 		while (spg->cidx != htobe16(eq->pidx))
7021 			pause("equiesce", 1);
7022 		while (eq->cidx != eq->pidx)
7023 			pause("dquiesce", 1);
7024 	} else {
7025 		/*
7026 		 * Hardware is unavailable.  Discard all pending tx and reclaim
7027 		 * descriptors directly.
7028 		 */
7029 		TXQ_LOCK(txq);
7030 		while (eq->cidx != eq->pidx) {
7031 			struct mbuf *m, *nextpkt;
7032 			struct tx_sdesc *txsd;
7033 
7034 			txsd = &txq->sdesc[eq->cidx];
7035 			for (m = txsd->m; m != NULL; m = nextpkt) {
7036 				nextpkt = m->m_nextpkt;
7037 				m->m_nextpkt = NULL;
7038 				m_freem(m);
7039 			}
7040 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
7041 		}
7042 		spg->pidx = spg->cidx = htobe16(eq->cidx);
7043 		TXQ_UNLOCK(txq);
7044 	}
7045 }
7046 
7047 static void
7048 quiesce_wrq(struct sge_wrq *wrq)
7049 {
7050 
7051 	/* XXXTX */
7052 }
7053 
7054 static void
7055 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
7056 {
7057 	/* Synchronize with the interrupt handler */
7058 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7059 		pause("iqfree", 1);
7060 
7061 	if (fl != NULL) {
7062 		MPASS(iq->flags & IQ_HAS_FL);
7063 
7064 		mtx_lock(&sc->sfl_lock);
7065 		FL_LOCK(fl);
7066 		fl->flags |= FL_DOOMED;
7067 		FL_UNLOCK(fl);
7068 		callout_stop(&sc->sfl_callout);
7069 		mtx_unlock(&sc->sfl_lock);
7070 
7071 		KASSERT((fl->flags & FL_STARVING) == 0,
7072 		    ("%s: still starving", __func__));
7073 
7074 		/* Release all buffers if hardware is no longer available. */
7075 		if (!(iq->flags & IQ_HW_ALLOCATED))
7076 			free_fl_buffers(sc, fl);
7077 	}
7078 }
7079 
7080 /*
7081  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7082  * that no new work is being enqueued by the hardware or the driver.  That part
7083  * should be arranged before calling this function.
7084  */
7085 static void
7086 quiesce_vi(struct vi_info *vi)
7087 {
7088 	int i;
7089 	struct adapter *sc = vi->adapter;
7090 	struct sge_rxq *rxq;
7091 	struct sge_txq *txq;
7092 #ifdef TCP_OFFLOAD
7093 	struct sge_ofld_rxq *ofld_rxq;
7094 #endif
7095 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7096 	struct sge_ofld_txq *ofld_txq;
7097 #endif
7098 
7099 	if (!(vi->flags & VI_INIT_DONE))
7100 		return;
7101 
7102 	for_each_txq(vi, i, txq) {
7103 		quiesce_txq(txq);
7104 	}
7105 
7106 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7107 	for_each_ofld_txq(vi, i, ofld_txq) {
7108 		quiesce_wrq(&ofld_txq->wrq);
7109 	}
7110 #endif
7111 
7112 	for_each_rxq(vi, i, rxq) {
7113 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7114 	}
7115 
7116 #ifdef TCP_OFFLOAD
7117 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7118 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7119 	}
7120 #endif
7121 }
7122 
7123 static int
7124 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7125     driver_intr_t *handler, void *arg, char *name)
7126 {
7127 	int rc;
7128 
7129 	irq->rid = rid;
7130 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7131 	    RF_SHAREABLE | RF_ACTIVE);
7132 	if (irq->res == NULL) {
7133 		device_printf(sc->dev,
7134 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7135 		return (ENOMEM);
7136 	}
7137 
7138 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7139 	    NULL, handler, arg, &irq->tag);
7140 	if (rc != 0) {
7141 		device_printf(sc->dev,
7142 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7143 		    rid, name, rc);
7144 	} else if (name)
7145 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7146 
7147 	return (rc);
7148 }
7149 
7150 static int
7151 t4_free_irq(struct adapter *sc, struct irq *irq)
7152 {
7153 	if (irq->tag)
7154 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7155 	if (irq->res)
7156 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7157 
7158 	bzero(irq, sizeof(*irq));
7159 
7160 	return (0);
7161 }
7162 
7163 static void
7164 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7165 {
7166 
7167 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7168 	t4_get_regs(sc, buf, regs->len);
7169 }
7170 
7171 #define	A_PL_INDIR_CMD	0x1f8
7172 
7173 #define	S_PL_AUTOINC	31
7174 #define	M_PL_AUTOINC	0x1U
7175 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7176 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7177 
7178 #define	S_PL_VFID	20
7179 #define	M_PL_VFID	0xffU
7180 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7181 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7182 
7183 #define	S_PL_ADDR	0
7184 #define	M_PL_ADDR	0xfffffU
7185 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7186 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7187 
7188 #define	A_PL_INDIR_DATA	0x1fc
7189 
7190 static uint64_t
7191 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7192 {
7193 	u32 stats[2];
7194 
7195 	if (sc->flags & IS_VF) {
7196 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7197 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7198 	} else {
7199 		mtx_assert(&sc->reg_lock, MA_OWNED);
7200 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7201 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7202 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7203 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7204 	}
7205 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7206 }
7207 
7208 static void
7209 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7210 {
7211 
7212 #define GET_STAT(name) \
7213 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7214 
7215 	if (!(sc->flags & IS_VF))
7216 		mtx_lock(&sc->reg_lock);
7217 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7218 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7219 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7220 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7221 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7222 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7223 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7224 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7225 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7226 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7227 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7228 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7229 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7230 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7231 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7232 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7233 	if (!(sc->flags & IS_VF))
7234 		mtx_unlock(&sc->reg_lock);
7235 
7236 #undef GET_STAT
7237 }
7238 
7239 static void
7240 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7241 {
7242 	int reg;
7243 
7244 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7245 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7246 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7247 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7248 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7249 }
7250 
7251 static void
7252 vi_refresh_stats(struct vi_info *vi)
7253 {
7254 	struct timeval tv;
7255 	const struct timeval interval = {0, 250000};	/* 250ms */
7256 
7257 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7258 
7259 	if (vi->flags & VI_SKIP_STATS)
7260 		return;
7261 
7262 	getmicrotime(&tv);
7263 	timevalsub(&tv, &interval);
7264 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7265 		return;
7266 
7267 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7268 	getmicrotime(&vi->last_refreshed);
7269 }
7270 
7271 static void
7272 cxgbe_refresh_stats(struct vi_info *vi)
7273 {
7274 	u_int i, v, tnl_cong_drops, chan_map;
7275 	struct timeval tv;
7276 	const struct timeval interval = {0, 250000};	/* 250ms */
7277 	struct port_info *pi;
7278 	struct adapter *sc;
7279 
7280 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7281 
7282 	if (vi->flags & VI_SKIP_STATS)
7283 		return;
7284 
7285 	getmicrotime(&tv);
7286 	timevalsub(&tv, &interval);
7287 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7288 		return;
7289 
7290 	pi = vi->pi;
7291 	sc = vi->adapter;
7292 	tnl_cong_drops = 0;
7293 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7294 	chan_map = pi->rx_e_chan_map;
7295 	while (chan_map) {
7296 		i = ffs(chan_map) - 1;
7297 		mtx_lock(&sc->reg_lock);
7298 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7299 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7300 		mtx_unlock(&sc->reg_lock);
7301 		tnl_cong_drops += v;
7302 		chan_map &= ~(1 << i);
7303 	}
7304 	pi->tnl_cong_drops = tnl_cong_drops;
7305 	getmicrotime(&vi->last_refreshed);
7306 }
7307 
7308 static void
7309 cxgbe_tick(void *arg)
7310 {
7311 	struct vi_info *vi = arg;
7312 
7313 	MPASS(IS_MAIN_VI(vi));
7314 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7315 
7316 	cxgbe_refresh_stats(vi);
7317 	callout_schedule(&vi->tick, hz);
7318 }
7319 
7320 static void
7321 vi_tick(void *arg)
7322 {
7323 	struct vi_info *vi = arg;
7324 
7325 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7326 
7327 	vi_refresh_stats(vi);
7328 	callout_schedule(&vi->tick, hz);
7329 }
7330 
7331 /*
7332  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7333  */
7334 static char *caps_decoder[] = {
7335 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7336 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7337 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7338 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7339 	    "\006HASHFILTER\007ETHOFLD",
7340 	"\20\001TOE",					/* 4: TOE */
7341 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7342 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7343 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7344 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7345 	    "\007T10DIF"
7346 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7347 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7348 	    "\004TLS_HW",
7349 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7350 		    "\004PO_INITIATOR\005PO_TARGET",
7351 };
7352 
7353 void
7354 t4_sysctls(struct adapter *sc)
7355 {
7356 	struct sysctl_ctx_list *ctx = &sc->ctx;
7357 	struct sysctl_oid *oid;
7358 	struct sysctl_oid_list *children, *c0;
7359 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7360 
7361 	/*
7362 	 * dev.t4nex.X.
7363 	 */
7364 	oid = device_get_sysctl_tree(sc->dev);
7365 	c0 = children = SYSCTL_CHILDREN(oid);
7366 
7367 	sc->sc_do_rxcopy = 1;
7368 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7369 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7370 
7371 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7372 	    sc->params.nports, "# of ports");
7373 
7374 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7375 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7376 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7377 	    "available doorbells");
7378 
7379 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7380 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7381 
7382 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7383 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7384 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7385 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7386 
7387 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7388 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7389 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7390 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7391 
7392 	t4_sge_sysctls(sc, ctx, children);
7393 
7394 	sc->lro_timeout = 100;
7395 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7396 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7397 
7398 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7399 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7400 
7401 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7402 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7403 
7404 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7405 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7406 
7407 	if (sc->flags & IS_VF)
7408 		return;
7409 
7410 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7411 	    NULL, chip_rev(sc), "chip hardware revision");
7412 
7413 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7414 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7415 
7416 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7417 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7418 
7419 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7420 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7421 
7422 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7423 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7424 
7425 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7426 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7427 
7428 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7429 	    sc->er_version, 0, "expansion ROM version");
7430 
7431 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7432 	    sc->bs_version, 0, "bootstrap firmware version");
7433 
7434 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7435 	    NULL, sc->params.scfg_vers, "serial config version");
7436 
7437 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7438 	    NULL, sc->params.vpd_vers, "VPD version");
7439 
7440 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7441 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7442 
7443 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7444 	    sc->cfcsum, "config file checksum");
7445 
7446 #define SYSCTL_CAP(name, n, text) \
7447 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7448 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7449 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7450 	    "available " text " capabilities")
7451 
7452 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7453 	SYSCTL_CAP(linkcaps, 1, "link");
7454 	SYSCTL_CAP(switchcaps, 2, "switch");
7455 	SYSCTL_CAP(niccaps, 3, "NIC");
7456 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7457 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7458 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7459 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7460 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7461 #undef SYSCTL_CAP
7462 
7463 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7464 	    NULL, sc->tids.nftids, "number of filters");
7465 
7466 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7467 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7468 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7469 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7470 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7471 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7472 
7473 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7474 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7475 	    sysctl_loadavg, "A",
7476 	    "microprocessor load averages (debug firmwares only)");
7477 
7478 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7479 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7480 	    "I", "core Vdd (in mV)");
7481 
7482 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7483 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7484 	    sysctl_cpus, "A", "local CPUs");
7485 
7486 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7487 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7488 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7489 
7490 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7491 	    &sc->swintr, 0, "software triggered interrupts");
7492 
7493 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7494 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7495 	    "1 = reset adapter, 0 = zero reset counter");
7496 
7497 	/*
7498 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7499 	 */
7500 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7501 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7502 	    "logs and miscellaneous information");
7503 	children = SYSCTL_CHILDREN(oid);
7504 
7505 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7506 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7507 	    sysctl_cctrl, "A", "congestion control");
7508 
7509 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7510 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7511 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7512 
7513 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7514 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7515 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7516 
7517 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7518 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7519 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7520 
7521 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7522 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7523 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7524 
7525 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7526 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7527 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7528 
7529 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7530 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7531 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7532 
7533 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7534 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7535 	    sysctl_cim_la, "A", "CIM logic analyzer");
7536 
7537 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7538 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7539 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7540 
7541 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7542 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7543 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7544 
7545 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7546 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7547 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7548 
7549 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7550 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7551 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7552 
7553 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7554 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7555 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7556 
7557 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7558 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7559 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7560 
7561 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7562 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7563 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7564 
7565 	if (chip_id(sc) > CHELSIO_T4) {
7566 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7567 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7568 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7569 		    "CIM OBQ 6 (SGE0-RX)");
7570 
7571 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7572 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7573 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7574 		    "CIM OBQ 7 (SGE1-RX)");
7575 	}
7576 
7577 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7578 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7579 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7580 
7581 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7582 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7583 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7584 
7585 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7586 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7587 	    sysctl_cpl_stats, "A", "CPL statistics");
7588 
7589 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7590 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7591 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7592 
7593 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7594 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7595 	    sysctl_tid_stats, "A", "tid stats");
7596 
7597 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7598 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7599 	    sysctl_devlog, "A", "firmware's device log");
7600 
7601 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7602 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7603 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7604 
7605 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7606 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7607 	    sysctl_hw_sched, "A", "hardware scheduler ");
7608 
7609 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7610 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7611 	    sysctl_l2t, "A", "hardware L2 table");
7612 
7613 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7614 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7615 	    sysctl_smt, "A", "hardware source MAC table");
7616 
7617 #ifdef INET6
7618 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7619 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7620 	    sysctl_clip, "A", "active CLIP table entries");
7621 #endif
7622 
7623 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7624 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7625 	    sysctl_lb_stats, "A", "loopback statistics");
7626 
7627 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7628 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7629 	    sysctl_meminfo, "A", "memory regions");
7630 
7631 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7632 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7633 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7634 	    "A", "MPS TCAM entries");
7635 
7636 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7637 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7638 	    sysctl_path_mtus, "A", "path MTUs");
7639 
7640 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7641 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7642 	    sysctl_pm_stats, "A", "PM statistics");
7643 
7644 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7645 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7646 	    sysctl_rdma_stats, "A", "RDMA statistics");
7647 
7648 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7649 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7650 	    sysctl_tcp_stats, "A", "TCP statistics");
7651 
7652 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7653 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7654 	    sysctl_tids, "A", "TID information");
7655 
7656 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7657 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7658 	    sysctl_tp_err_stats, "A", "TP error statistics");
7659 
7660 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7661 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7662 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7663 
7664 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7665 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7666 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7667 
7668 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7669 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7670 	    sysctl_tp_la, "A", "TP logic analyzer");
7671 
7672 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7673 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7674 	    sysctl_tx_rate, "A", "Tx rate");
7675 
7676 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7677 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7678 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7679 
7680 	if (chip_id(sc) >= CHELSIO_T5) {
7681 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7682 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7683 		    sysctl_wcwr_stats, "A", "write combined work requests");
7684 	}
7685 
7686 #ifdef KERN_TLS
7687 	if (is_ktls(sc)) {
7688 		/*
7689 		 * dev.t4nex.0.tls.
7690 		 */
7691 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7692 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7693 		children = SYSCTL_CHILDREN(oid);
7694 
7695 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7696 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7697 		    "keys in work requests (1) or attempt to store TLS keys "
7698 		    "in card memory.");
7699 
7700 		if (is_t6(sc))
7701 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7702 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7703 			    "combine TCB field updates with TLS record work "
7704 			    "requests.");
7705 	}
7706 #endif
7707 
7708 #ifdef TCP_OFFLOAD
7709 	if (is_offload(sc)) {
7710 		int i;
7711 		char s[4];
7712 
7713 		/*
7714 		 * dev.t4nex.X.toe.
7715 		 */
7716 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7717 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7718 		children = SYSCTL_CHILDREN(oid);
7719 
7720 		sc->tt.cong_algorithm = -1;
7721 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7722 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7723 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7724 		    "3 = highspeed)");
7725 
7726 		sc->tt.sndbuf = -1;
7727 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7728 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7729 
7730 		sc->tt.ddp = 0;
7731 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7732 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7733 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7734 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7735 
7736 		sc->tt.rx_coalesce = -1;
7737 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7738 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7739 
7740 		sc->tt.tls = 0;
7741 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7742 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7743 		    "Inline TLS allowed");
7744 
7745 		sc->tt.tx_align = -1;
7746 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7747 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7748 
7749 		sc->tt.tx_zcopy = 0;
7750 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7751 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7752 		    "Enable zero-copy aio_write(2)");
7753 
7754 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7755 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7756 		    "cop_managed_offloading", CTLFLAG_RW,
7757 		    &sc->tt.cop_managed_offloading, 0,
7758 		    "COP (Connection Offload Policy) controls all TOE offload");
7759 
7760 		sc->tt.autorcvbuf_inc = 16 * 1024;
7761 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7762 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7763 		    "autorcvbuf increment");
7764 
7765 		sc->tt.update_hc_on_pmtu_change = 1;
7766 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7767 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7768 		    &sc->tt.update_hc_on_pmtu_change, 0,
7769 		    "Update hostcache entry if the PMTU changes");
7770 
7771 		sc->tt.iso = 1;
7772 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7773 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7774 
7775 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7776 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7777 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7778 
7779 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7780 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7781 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7782 
7783 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7784 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7785 		    sysctl_tp_tick, "A", "DACK tick (us)");
7786 
7787 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7788 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7789 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7790 
7791 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7792 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7793 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7794 		    "Minimum retransmit interval (us)");
7795 
7796 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7797 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7798 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7799 		    "Maximum retransmit interval (us)");
7800 
7801 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7802 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7803 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7804 		    "Persist timer min (us)");
7805 
7806 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7807 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7808 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7809 		    "Persist timer max (us)");
7810 
7811 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7812 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7813 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7814 		    "Keepalive idle timer (us)");
7815 
7816 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7817 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7818 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7819 		    "Keepalive interval timer (us)");
7820 
7821 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7822 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7823 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7824 
7825 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7826 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7827 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7828 		    "FINWAIT2 timer (us)");
7829 
7830 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7831 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7832 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7833 		    "Number of SYN retransmissions before abort");
7834 
7835 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7836 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7837 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7838 		    "Number of retransmissions before abort");
7839 
7840 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7841 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7842 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7843 		    "Number of keepalive probes before abort");
7844 
7845 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7846 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7847 		    "TOE retransmit backoffs");
7848 		children = SYSCTL_CHILDREN(oid);
7849 		for (i = 0; i < 16; i++) {
7850 			snprintf(s, sizeof(s), "%u", i);
7851 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7852 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7853 			    i, sysctl_tp_backoff, "IU",
7854 			    "TOE retransmit backoff");
7855 		}
7856 	}
7857 #endif
7858 }
7859 
7860 void
7861 vi_sysctls(struct vi_info *vi)
7862 {
7863 	struct sysctl_ctx_list *ctx = &vi->ctx;
7864 	struct sysctl_oid *oid;
7865 	struct sysctl_oid_list *children;
7866 
7867 	/*
7868 	 * dev.v?(cxgbe|cxl).X.
7869 	 */
7870 	oid = device_get_sysctl_tree(vi->dev);
7871 	children = SYSCTL_CHILDREN(oid);
7872 
7873 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7874 	    vi->viid, "VI identifer");
7875 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7876 	    &vi->nrxq, 0, "# of rx queues");
7877 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7878 	    &vi->ntxq, 0, "# of tx queues");
7879 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7880 	    &vi->first_rxq, 0, "index of first rx queue");
7881 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7882 	    &vi->first_txq, 0, "index of first tx queue");
7883 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7884 	    vi->rss_base, "start of RSS indirection table");
7885 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7886 	    vi->rss_size, "size of RSS indirection table");
7887 
7888 	if (IS_MAIN_VI(vi)) {
7889 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7890 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7891 		    sysctl_noflowq, "IU",
7892 		    "Reserve queue 0 for non-flowid packets");
7893 	}
7894 
7895 	if (vi->adapter->flags & IS_VF) {
7896 		MPASS(vi->flags & TX_USES_VM_WR);
7897 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7898 		    NULL, 1, "use VM work requests for transmit");
7899 	} else {
7900 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7901 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7902 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7903 	}
7904 
7905 #ifdef TCP_OFFLOAD
7906 	if (vi->nofldrxq != 0) {
7907 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7908 		    &vi->nofldrxq, 0,
7909 		    "# of rx queues for offloaded TCP connections");
7910 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7911 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7912 		    "index of first TOE rx queue");
7913 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7914 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7915 		    sysctl_holdoff_tmr_idx_ofld, "I",
7916 		    "holdoff timer index for TOE queues");
7917 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7918 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7919 		    sysctl_holdoff_pktc_idx_ofld, "I",
7920 		    "holdoff packet counter index for TOE queues");
7921 	}
7922 #endif
7923 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7924 	if (vi->nofldtxq != 0) {
7925 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7926 		    &vi->nofldtxq, 0,
7927 		    "# of tx queues for TOE/ETHOFLD");
7928 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7929 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7930 		    "index of first TOE/ETHOFLD tx queue");
7931 	}
7932 #endif
7933 #ifdef DEV_NETMAP
7934 	if (vi->nnmrxq != 0) {
7935 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7936 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7937 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7938 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7939 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7940 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7941 		    "index of first netmap rx queue");
7942 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7943 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7944 		    "index of first netmap tx queue");
7945 	}
7946 #endif
7947 
7948 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7949 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7950 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7951 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7952 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7953 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7954 
7955 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7956 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7957 	    sysctl_qsize_rxq, "I", "rx queue size");
7958 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7959 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7960 	    sysctl_qsize_txq, "I", "tx queue size");
7961 }
7962 
7963 static void
7964 cxgbe_sysctls(struct port_info *pi)
7965 {
7966 	struct sysctl_ctx_list *ctx = &pi->ctx;
7967 	struct sysctl_oid *oid;
7968 	struct sysctl_oid_list *children, *children2;
7969 	struct adapter *sc = pi->adapter;
7970 	int i;
7971 	char name[16];
7972 	static char *tc_flags = {"\20\1USER"};
7973 
7974 	/*
7975 	 * dev.cxgbe.X.
7976 	 */
7977 	oid = device_get_sysctl_tree(pi->dev);
7978 	children = SYSCTL_CHILDREN(oid);
7979 
7980 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7981 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7982 	    sysctl_linkdnrc, "A", "reason why link is down");
7983 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7984 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7985 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7986 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7987 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7988 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7989 		    sysctl_btphy, "I", "PHY firmware version");
7990 	}
7991 
7992 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7993 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7994 	    sysctl_pause_settings, "A",
7995 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7996 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7997 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7998 	    "FEC in use on the link");
7999 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
8000 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8001 	    sysctl_requested_fec, "A",
8002 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
8003 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
8004 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
8005 	    "FEC recommended by the cable/transceiver");
8006 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
8007 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8008 	    sysctl_autoneg, "I",
8009 	    "autonegotiation (-1 = not supported)");
8010 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
8011 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
8012 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
8013 
8014 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
8015 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
8016 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
8017 	    &pi->link_cfg.pcaps, 0, "port capabilities");
8018 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
8019 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
8020 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
8021 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
8022 
8023 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
8024 	    port_top_speed(pi), "max speed (in Gbps)");
8025 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
8026 	    pi->mps_bg_map, "MPS buffer group map");
8027 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
8028 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
8029 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_chan", CTLFLAG_RD, NULL,
8030 	    pi->tx_chan, "TP tx c-channel");
8031 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_chan", CTLFLAG_RD, NULL,
8032 	    pi->rx_chan, "TP rx c-channel");
8033 
8034 	if (sc->flags & IS_VF)
8035 		return;
8036 
8037 	/*
8038 	 * dev.(cxgbe|cxl).X.tc.
8039 	 */
8040 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
8041 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
8042 	    "Tx scheduler traffic classes (cl_rl)");
8043 	children2 = SYSCTL_CHILDREN(oid);
8044 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
8045 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
8046 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
8047 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
8048 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
8049 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
8050 	for (i = 0; i < sc->params.nsched_cls; i++) {
8051 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
8052 
8053 		snprintf(name, sizeof(name), "%d", i);
8054 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
8055 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
8056 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
8057 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
8058 		    CTLFLAG_RD, &tc->state, 0, "current state");
8059 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8060 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8061 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8062 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8063 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8064 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8065 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8066 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8067 		    "traffic class parameters");
8068 	}
8069 
8070 	/*
8071 	 * dev.cxgbe.X.stats.
8072 	 */
8073 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8074 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8075 	children = SYSCTL_CHILDREN(oid);
8076 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8077 	    &pi->tx_parse_error, 0,
8078 	    "# of tx packets with invalid length or # of segments");
8079 
8080 #define T4_REGSTAT(name, stat, desc) \
8081     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8082 	CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8083 	t4_port_reg(sc, pi->tx_chan, A_MPS_PORT_STAT_##stat##_L), \
8084         sysctl_handle_t4_reg64, "QU", desc)
8085 
8086 /* We get these from port_stats and they may be stale by up to 1s */
8087 #define T4_PORTSTAT(name, desc) \
8088 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8089 	    &pi->stats.name, desc)
8090 
8091 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8092 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8093 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8094 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8095 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8096 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8097 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8098 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8099 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8100 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8101 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8102 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8103 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8104 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8105 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8106 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8107 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8108 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8109 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8110 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8111 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8112 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8113 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8114 
8115 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8116 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8117 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8118 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8119 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8120 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8121 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8122 	if (is_t6(sc)) {
8123 		T4_PORTSTAT(rx_fcs_err,
8124 		    "# of frames received with bad FCS since last link up");
8125 	} else {
8126 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8127 		    "# of frames received with bad FCS");
8128 	}
8129 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8130 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8131 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8132 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8133 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8134 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8135 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8136 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8137 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8138 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8139 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8140 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8141 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8142 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8143 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8144 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8145 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8146 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8147 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8148 
8149 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8150 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8151 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8152 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8153 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8154 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8155 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8156 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8157 
8158 #undef T4_REGSTAT
8159 #undef T4_PORTSTAT
8160 }
8161 
8162 static int
8163 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8164 {
8165 	int rc, *i, space = 0;
8166 	struct sbuf sb;
8167 
8168 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8169 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8170 		if (space)
8171 			sbuf_printf(&sb, " ");
8172 		sbuf_printf(&sb, "%d", *i);
8173 		space = 1;
8174 	}
8175 	rc = sbuf_finish(&sb);
8176 	sbuf_delete(&sb);
8177 	return (rc);
8178 }
8179 
8180 static int
8181 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8182 {
8183 	int rc;
8184 	struct sbuf *sb;
8185 
8186 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8187 	if (sb == NULL)
8188 		return (ENOMEM);
8189 
8190 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8191 	rc = sbuf_finish(sb);
8192 	sbuf_delete(sb);
8193 
8194 	return (rc);
8195 }
8196 
8197 static int
8198 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8199 {
8200 	int rc;
8201 	struct sbuf *sb;
8202 
8203 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8204 	if (sb == NULL)
8205 		return (ENOMEM);
8206 
8207 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8208 	rc = sbuf_finish(sb);
8209 	sbuf_delete(sb);
8210 
8211 	return (rc);
8212 }
8213 
8214 static int
8215 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8216 {
8217 	struct port_info *pi = arg1;
8218 	int op = arg2;
8219 	struct adapter *sc = pi->adapter;
8220 	u_int v;
8221 	int rc;
8222 
8223 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8224 	if (rc)
8225 		return (rc);
8226 	if (hw_off_limits(sc))
8227 		rc = ENXIO;
8228 	else {
8229 		/* XXX: magic numbers */
8230 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8231 		    op ? 0x20 : 0xc820, &v);
8232 	}
8233 	end_synchronized_op(sc, 0);
8234 	if (rc)
8235 		return (rc);
8236 	if (op == 0)
8237 		v /= 256;
8238 
8239 	rc = sysctl_handle_int(oidp, &v, 0, req);
8240 	return (rc);
8241 }
8242 
8243 static int
8244 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8245 {
8246 	struct vi_info *vi = arg1;
8247 	int rc, val;
8248 
8249 	val = vi->rsrv_noflowq;
8250 	rc = sysctl_handle_int(oidp, &val, 0, req);
8251 	if (rc != 0 || req->newptr == NULL)
8252 		return (rc);
8253 
8254 	if ((val >= 1) && (vi->ntxq > 1))
8255 		vi->rsrv_noflowq = 1;
8256 	else
8257 		vi->rsrv_noflowq = 0;
8258 
8259 	return (rc);
8260 }
8261 
8262 static int
8263 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8264 {
8265 	struct vi_info *vi = arg1;
8266 	struct adapter *sc = vi->adapter;
8267 	int rc, val, i;
8268 
8269 	MPASS(!(sc->flags & IS_VF));
8270 
8271 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8272 	rc = sysctl_handle_int(oidp, &val, 0, req);
8273 	if (rc != 0 || req->newptr == NULL)
8274 		return (rc);
8275 
8276 	if (val != 0 && val != 1)
8277 		return (EINVAL);
8278 
8279 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8280 	    "t4txvm");
8281 	if (rc)
8282 		return (rc);
8283 	if (hw_off_limits(sc))
8284 		rc = ENXIO;
8285 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8286 		/*
8287 		 * We don't want parse_pkt to run with one setting (VF or PF)
8288 		 * and then eth_tx to see a different setting but still use
8289 		 * stale information calculated by parse_pkt.
8290 		 */
8291 		rc = EBUSY;
8292 	} else {
8293 		struct port_info *pi = vi->pi;
8294 		struct sge_txq *txq;
8295 		uint32_t ctrl0;
8296 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8297 
8298 		if (val) {
8299 			vi->flags |= TX_USES_VM_WR;
8300 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8301 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8302 			    V_TXPKT_INTF(pi->tx_chan));
8303 			if (!(sc->flags & IS_VF))
8304 				npkt--;
8305 		} else {
8306 			vi->flags &= ~TX_USES_VM_WR;
8307 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8308 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8309 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8310 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8311 		}
8312 		for_each_txq(vi, i, txq) {
8313 			txq->cpl_ctrl0 = ctrl0;
8314 			txq->txp.max_npkt = npkt;
8315 		}
8316 	}
8317 	end_synchronized_op(sc, LOCK_HELD);
8318 	return (rc);
8319 }
8320 
8321 static int
8322 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8323 {
8324 	struct vi_info *vi = arg1;
8325 	struct adapter *sc = vi->adapter;
8326 	int idx, rc, i;
8327 	struct sge_rxq *rxq;
8328 	uint8_t v;
8329 
8330 	idx = vi->tmr_idx;
8331 
8332 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8333 	if (rc != 0 || req->newptr == NULL)
8334 		return (rc);
8335 
8336 	if (idx < 0 || idx >= SGE_NTIMERS)
8337 		return (EINVAL);
8338 
8339 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8340 	    "t4tmr");
8341 	if (rc)
8342 		return (rc);
8343 
8344 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8345 	for_each_rxq(vi, i, rxq) {
8346 #ifdef atomic_store_rel_8
8347 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8348 #else
8349 		rxq->iq.intr_params = v;
8350 #endif
8351 	}
8352 	vi->tmr_idx = idx;
8353 
8354 	end_synchronized_op(sc, LOCK_HELD);
8355 	return (0);
8356 }
8357 
8358 static int
8359 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8360 {
8361 	struct vi_info *vi = arg1;
8362 	struct adapter *sc = vi->adapter;
8363 	int idx, rc;
8364 
8365 	idx = vi->pktc_idx;
8366 
8367 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8368 	if (rc != 0 || req->newptr == NULL)
8369 		return (rc);
8370 
8371 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8372 		return (EINVAL);
8373 
8374 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8375 	    "t4pktc");
8376 	if (rc)
8377 		return (rc);
8378 
8379 	if (vi->flags & VI_INIT_DONE)
8380 		rc = EBUSY; /* cannot be changed once the queues are created */
8381 	else
8382 		vi->pktc_idx = idx;
8383 
8384 	end_synchronized_op(sc, LOCK_HELD);
8385 	return (rc);
8386 }
8387 
8388 static int
8389 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8390 {
8391 	struct vi_info *vi = arg1;
8392 	struct adapter *sc = vi->adapter;
8393 	int qsize, rc;
8394 
8395 	qsize = vi->qsize_rxq;
8396 
8397 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8398 	if (rc != 0 || req->newptr == NULL)
8399 		return (rc);
8400 
8401 	if (qsize < 128 || (qsize & 7))
8402 		return (EINVAL);
8403 
8404 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8405 	    "t4rxqs");
8406 	if (rc)
8407 		return (rc);
8408 
8409 	if (vi->flags & VI_INIT_DONE)
8410 		rc = EBUSY; /* cannot be changed once the queues are created */
8411 	else
8412 		vi->qsize_rxq = qsize;
8413 
8414 	end_synchronized_op(sc, LOCK_HELD);
8415 	return (rc);
8416 }
8417 
8418 static int
8419 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8420 {
8421 	struct vi_info *vi = arg1;
8422 	struct adapter *sc = vi->adapter;
8423 	int qsize, rc;
8424 
8425 	qsize = vi->qsize_txq;
8426 
8427 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8428 	if (rc != 0 || req->newptr == NULL)
8429 		return (rc);
8430 
8431 	if (qsize < 128 || qsize > 65536)
8432 		return (EINVAL);
8433 
8434 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8435 	    "t4txqs");
8436 	if (rc)
8437 		return (rc);
8438 
8439 	if (vi->flags & VI_INIT_DONE)
8440 		rc = EBUSY; /* cannot be changed once the queues are created */
8441 	else
8442 		vi->qsize_txq = qsize;
8443 
8444 	end_synchronized_op(sc, LOCK_HELD);
8445 	return (rc);
8446 }
8447 
8448 static int
8449 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8450 {
8451 	struct port_info *pi = arg1;
8452 	struct adapter *sc = pi->adapter;
8453 	struct link_config *lc = &pi->link_cfg;
8454 	int rc;
8455 
8456 	if (req->newptr == NULL) {
8457 		struct sbuf *sb;
8458 		static char *bits = "\20\1RX\2TX\3AUTO";
8459 
8460 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8461 		if (sb == NULL)
8462 			return (ENOMEM);
8463 
8464 		if (lc->link_ok) {
8465 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8466 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8467 		} else {
8468 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8469 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8470 		}
8471 		rc = sbuf_finish(sb);
8472 		sbuf_delete(sb);
8473 	} else {
8474 		char s[2];
8475 		int n;
8476 
8477 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8478 		    PAUSE_AUTONEG));
8479 		s[1] = 0;
8480 
8481 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8482 		if (rc != 0)
8483 			return(rc);
8484 
8485 		if (s[1] != 0)
8486 			return (EINVAL);
8487 		if (s[0] < '0' || s[0] > '9')
8488 			return (EINVAL);	/* not a number */
8489 		n = s[0] - '0';
8490 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8491 			return (EINVAL);	/* some other bit is set too */
8492 
8493 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8494 		    "t4PAUSE");
8495 		if (rc)
8496 			return (rc);
8497 		if (!hw_off_limits(sc)) {
8498 			PORT_LOCK(pi);
8499 			lc->requested_fc = n;
8500 			fixup_link_config(pi);
8501 			if (pi->up_vis > 0)
8502 				rc = apply_link_config(pi);
8503 			set_current_media(pi);
8504 			PORT_UNLOCK(pi);
8505 		}
8506 		end_synchronized_op(sc, 0);
8507 	}
8508 
8509 	return (rc);
8510 }
8511 
8512 static int
8513 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8514 {
8515 	struct port_info *pi = arg1;
8516 	struct link_config *lc = &pi->link_cfg;
8517 	int rc;
8518 	struct sbuf *sb;
8519 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8520 
8521 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8522 	if (sb == NULL)
8523 		return (ENOMEM);
8524 	if (lc->link_ok)
8525 		sbuf_printf(sb, "%b", lc->fec, bits);
8526 	else
8527 		sbuf_printf(sb, "no link");
8528 	rc = sbuf_finish(sb);
8529 	sbuf_delete(sb);
8530 
8531 	return (rc);
8532 }
8533 
8534 static int
8535 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8536 {
8537 	struct port_info *pi = arg1;
8538 	struct adapter *sc = pi->adapter;
8539 	struct link_config *lc = &pi->link_cfg;
8540 	int rc;
8541 	int8_t old;
8542 
8543 	if (req->newptr == NULL) {
8544 		struct sbuf *sb;
8545 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8546 		    "\5RSVD3\6auto\7module";
8547 
8548 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8549 		if (sb == NULL)
8550 			return (ENOMEM);
8551 
8552 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8553 		rc = sbuf_finish(sb);
8554 		sbuf_delete(sb);
8555 	} else {
8556 		char s[8];
8557 		int n;
8558 
8559 		snprintf(s, sizeof(s), "%d",
8560 		    lc->requested_fec == FEC_AUTO ? -1 :
8561 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8562 
8563 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8564 		if (rc != 0)
8565 			return(rc);
8566 
8567 		n = strtol(&s[0], NULL, 0);
8568 		if (n < 0 || n & FEC_AUTO)
8569 			n = FEC_AUTO;
8570 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8571 			return (EINVAL);/* some other bit is set too */
8572 
8573 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8574 		    "t4reqf");
8575 		if (rc)
8576 			return (rc);
8577 		PORT_LOCK(pi);
8578 		old = lc->requested_fec;
8579 		if (n == FEC_AUTO)
8580 			lc->requested_fec = FEC_AUTO;
8581 		else if (n == 0 || n == FEC_NONE)
8582 			lc->requested_fec = FEC_NONE;
8583 		else {
8584 			if ((lc->pcaps |
8585 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8586 			    lc->pcaps) {
8587 				rc = ENOTSUP;
8588 				goto done;
8589 			}
8590 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8591 			    FEC_MODULE);
8592 		}
8593 		if (!hw_off_limits(sc)) {
8594 			fixup_link_config(pi);
8595 			if (pi->up_vis > 0) {
8596 				rc = apply_link_config(pi);
8597 				if (rc != 0) {
8598 					lc->requested_fec = old;
8599 					if (rc == FW_EPROTO)
8600 						rc = ENOTSUP;
8601 				}
8602 			}
8603 		}
8604 done:
8605 		PORT_UNLOCK(pi);
8606 		end_synchronized_op(sc, 0);
8607 	}
8608 
8609 	return (rc);
8610 }
8611 
8612 static int
8613 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8614 {
8615 	struct port_info *pi = arg1;
8616 	struct adapter *sc = pi->adapter;
8617 	struct link_config *lc = &pi->link_cfg;
8618 	int rc;
8619 	int8_t fec;
8620 	struct sbuf *sb;
8621 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8622 
8623 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8624 	if (sb == NULL)
8625 		return (ENOMEM);
8626 
8627 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8628 		rc = EBUSY;
8629 		goto done;
8630 	}
8631 	if (hw_off_limits(sc)) {
8632 		rc = ENXIO;
8633 		goto done;
8634 	}
8635 	PORT_LOCK(pi);
8636 	if (pi->up_vis == 0) {
8637 		/*
8638 		 * If all the interfaces are administratively down the firmware
8639 		 * does not report transceiver changes.  Refresh port info here.
8640 		 * This is the only reason we have a synchronized op in this
8641 		 * function.  Just PORT_LOCK would have been enough otherwise.
8642 		 */
8643 		t4_update_port_info(pi);
8644 	}
8645 
8646 	fec = lc->fec_hint;
8647 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8648 	    !fec_supported(lc->pcaps)) {
8649 		PORT_UNLOCK(pi);
8650 		sbuf_printf(sb, "n/a");
8651 	} else {
8652 		if (fec == 0)
8653 			fec = FEC_NONE;
8654 		PORT_UNLOCK(pi);
8655 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8656 	}
8657 	rc = sbuf_finish(sb);
8658 done:
8659 	sbuf_delete(sb);
8660 	end_synchronized_op(sc, 0);
8661 
8662 	return (rc);
8663 }
8664 
8665 static int
8666 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8667 {
8668 	struct port_info *pi = arg1;
8669 	struct adapter *sc = pi->adapter;
8670 	struct link_config *lc = &pi->link_cfg;
8671 	int rc, val;
8672 
8673 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8674 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8675 	else
8676 		val = -1;
8677 	rc = sysctl_handle_int(oidp, &val, 0, req);
8678 	if (rc != 0 || req->newptr == NULL)
8679 		return (rc);
8680 	if (val == 0)
8681 		val = AUTONEG_DISABLE;
8682 	else if (val == 1)
8683 		val = AUTONEG_ENABLE;
8684 	else
8685 		val = AUTONEG_AUTO;
8686 
8687 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8688 	    "t4aneg");
8689 	if (rc)
8690 		return (rc);
8691 	PORT_LOCK(pi);
8692 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8693 		rc = ENOTSUP;
8694 		goto done;
8695 	}
8696 	lc->requested_aneg = val;
8697 	if (!hw_off_limits(sc)) {
8698 		fixup_link_config(pi);
8699 		if (pi->up_vis > 0)
8700 			rc = apply_link_config(pi);
8701 		set_current_media(pi);
8702 	}
8703 done:
8704 	PORT_UNLOCK(pi);
8705 	end_synchronized_op(sc, 0);
8706 	return (rc);
8707 }
8708 
8709 static int
8710 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8711 {
8712 	struct port_info *pi = arg1;
8713 	struct adapter *sc = pi->adapter;
8714 	struct link_config *lc = &pi->link_cfg;
8715 	int rc, val;
8716 
8717 	val = lc->force_fec;
8718 	MPASS(val >= -1 && val <= 1);
8719 	rc = sysctl_handle_int(oidp, &val, 0, req);
8720 	if (rc != 0 || req->newptr == NULL)
8721 		return (rc);
8722 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8723 		return (ENOTSUP);
8724 	if (val < -1 || val > 1)
8725 		return (EINVAL);
8726 
8727 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8728 	if (rc)
8729 		return (rc);
8730 	PORT_LOCK(pi);
8731 	lc->force_fec = val;
8732 	if (!hw_off_limits(sc)) {
8733 		fixup_link_config(pi);
8734 		if (pi->up_vis > 0)
8735 			rc = apply_link_config(pi);
8736 	}
8737 	PORT_UNLOCK(pi);
8738 	end_synchronized_op(sc, 0);
8739 	return (rc);
8740 }
8741 
8742 static int
8743 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8744 {
8745 	struct adapter *sc = arg1;
8746 	int rc, reg = arg2;
8747 	uint64_t val;
8748 
8749 	mtx_lock(&sc->reg_lock);
8750 	if (hw_off_limits(sc))
8751 		rc = ENXIO;
8752 	else {
8753 		rc = 0;
8754 		val = t4_read_reg64(sc, reg);
8755 	}
8756 	mtx_unlock(&sc->reg_lock);
8757 	if (rc == 0)
8758 		rc = sysctl_handle_64(oidp, &val, 0, req);
8759 	return (rc);
8760 }
8761 
8762 static int
8763 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8764 {
8765 	struct adapter *sc = arg1;
8766 	int rc, t;
8767 	uint32_t param, val;
8768 
8769 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8770 	if (rc)
8771 		return (rc);
8772 	if (hw_off_limits(sc))
8773 		rc = ENXIO;
8774 	else {
8775 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8776 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8777 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8778 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8779 	}
8780 	end_synchronized_op(sc, 0);
8781 	if (rc)
8782 		return (rc);
8783 
8784 	/* unknown is returned as 0 but we display -1 in that case */
8785 	t = val == 0 ? -1 : val;
8786 
8787 	rc = sysctl_handle_int(oidp, &t, 0, req);
8788 	return (rc);
8789 }
8790 
8791 static int
8792 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8793 {
8794 	struct adapter *sc = arg1;
8795 	int rc;
8796 	uint32_t param, val;
8797 
8798 	if (sc->params.core_vdd == 0) {
8799 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8800 		    "t4vdd");
8801 		if (rc)
8802 			return (rc);
8803 		if (hw_off_limits(sc))
8804 			rc = ENXIO;
8805 		else {
8806 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8807 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8808 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8809 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8810 			    &param, &val);
8811 		}
8812 		end_synchronized_op(sc, 0);
8813 		if (rc)
8814 			return (rc);
8815 		sc->params.core_vdd = val;
8816 	}
8817 
8818 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8819 }
8820 
8821 static int
8822 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8823 {
8824 	struct adapter *sc = arg1;
8825 	int rc, v;
8826 	uint32_t param, val;
8827 
8828 	v = sc->sensor_resets;
8829 	rc = sysctl_handle_int(oidp, &v, 0, req);
8830 	if (rc != 0 || req->newptr == NULL || v <= 0)
8831 		return (rc);
8832 
8833 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8834 	    chip_id(sc) < CHELSIO_T5)
8835 		return (ENOTSUP);
8836 
8837 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8838 	if (rc)
8839 		return (rc);
8840 	if (hw_off_limits(sc))
8841 		rc = ENXIO;
8842 	else {
8843 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8844 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8845 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8846 		val = 1;
8847 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8848 	}
8849 	end_synchronized_op(sc, 0);
8850 	if (rc == 0)
8851 		sc->sensor_resets++;
8852 	return (rc);
8853 }
8854 
8855 static int
8856 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8857 {
8858 	struct adapter *sc = arg1;
8859 	struct sbuf *sb;
8860 	int rc;
8861 	uint32_t param, val;
8862 
8863 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8864 	if (rc)
8865 		return (rc);
8866 	if (hw_off_limits(sc))
8867 		rc = ENXIO;
8868 	else {
8869 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8870 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8871 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8872 	}
8873 	end_synchronized_op(sc, 0);
8874 	if (rc)
8875 		return (rc);
8876 
8877 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8878 	if (sb == NULL)
8879 		return (ENOMEM);
8880 
8881 	if (val == 0xffffffff) {
8882 		/* Only debug and custom firmwares report load averages. */
8883 		sbuf_printf(sb, "not available");
8884 	} else {
8885 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8886 		    (val >> 16) & 0xff);
8887 	}
8888 	rc = sbuf_finish(sb);
8889 	sbuf_delete(sb);
8890 
8891 	return (rc);
8892 }
8893 
8894 static int
8895 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8896 {
8897 	struct adapter *sc = arg1;
8898 	struct sbuf *sb;
8899 	int rc, i;
8900 	uint16_t incr[NMTUS][NCCTRL_WIN];
8901 	static const char *dec_fac[] = {
8902 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8903 		"0.9375"
8904 	};
8905 
8906 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8907 	if (sb == NULL)
8908 		return (ENOMEM);
8909 
8910 	rc = 0;
8911 	mtx_lock(&sc->reg_lock);
8912 	if (hw_off_limits(sc))
8913 		rc = ENXIO;
8914 	else
8915 		t4_read_cong_tbl(sc, incr);
8916 	mtx_unlock(&sc->reg_lock);
8917 	if (rc)
8918 		goto done;
8919 
8920 	for (i = 0; i < NCCTRL_WIN; ++i) {
8921 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8922 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8923 		    incr[5][i], incr[6][i], incr[7][i]);
8924 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8925 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8926 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8927 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8928 	}
8929 
8930 	rc = sbuf_finish(sb);
8931 done:
8932 	sbuf_delete(sb);
8933 	return (rc);
8934 }
8935 
8936 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8937 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8938 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8939 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8940 };
8941 
8942 static int
8943 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8944 {
8945 	struct adapter *sc = arg1;
8946 	struct sbuf *sb;
8947 	int rc, i, n, qid = arg2;
8948 	uint32_t *buf, *p;
8949 	char *qtype;
8950 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8951 
8952 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8953 	    ("%s: bad qid %d\n", __func__, qid));
8954 
8955 	if (qid < CIM_NUM_IBQ) {
8956 		/* inbound queue */
8957 		qtype = "IBQ";
8958 		n = 4 * CIM_IBQ_SIZE;
8959 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8960 		mtx_lock(&sc->reg_lock);
8961 		if (hw_off_limits(sc))
8962 			rc = -ENXIO;
8963 		else
8964 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8965 		mtx_unlock(&sc->reg_lock);
8966 	} else {
8967 		/* outbound queue */
8968 		qtype = "OBQ";
8969 		qid -= CIM_NUM_IBQ;
8970 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8971 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8972 		mtx_lock(&sc->reg_lock);
8973 		if (hw_off_limits(sc))
8974 			rc = -ENXIO;
8975 		else
8976 			rc = t4_read_cim_obq(sc, qid, buf, n);
8977 		mtx_unlock(&sc->reg_lock);
8978 	}
8979 
8980 	if (rc < 0) {
8981 		rc = -rc;
8982 		goto done;
8983 	}
8984 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8985 
8986 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8987 	if (sb == NULL) {
8988 		rc = ENOMEM;
8989 		goto done;
8990 	}
8991 
8992 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8993 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8994 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8995 		    p[2], p[3]);
8996 
8997 	rc = sbuf_finish(sb);
8998 	sbuf_delete(sb);
8999 done:
9000 	free(buf, M_CXGBE);
9001 	return (rc);
9002 }
9003 
9004 static void
9005 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9006 {
9007 	uint32_t *p;
9008 
9009 	sbuf_printf(sb, "Status   Data      PC%s",
9010 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9011 	    "     LS0Stat  LS0Addr             LS0Data");
9012 
9013 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
9014 		if (cfg & F_UPDBGLACAPTPCONLY) {
9015 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
9016 			    p[6], p[7]);
9017 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
9018 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
9019 			    p[4] & 0xff, p[5] >> 8);
9020 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
9021 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9022 			    p[1] & 0xf, p[2] >> 4);
9023 		} else {
9024 			sbuf_printf(sb,
9025 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9026 			    "%08x%08x%08x%08x",
9027 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9028 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9029 			    p[6], p[7]);
9030 		}
9031 	}
9032 }
9033 
9034 static void
9035 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9036 {
9037 	uint32_t *p;
9038 
9039 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9040 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9041 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9042 
9043 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9044 		if (cfg & F_UPDBGLACAPTPCONLY) {
9045 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9046 			    p[3] & 0xff, p[2], p[1], p[0]);
9047 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9048 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9049 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9050 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9051 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9052 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9053 			    p[6] >> 16);
9054 		} else {
9055 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9056 			    "%08x %08x %08x %08x %08x %08x",
9057 			    (p[9] >> 16) & 0xff,
9058 			    p[9] & 0xffff, p[8] >> 16,
9059 			    p[8] & 0xffff, p[7] >> 16,
9060 			    p[7] & 0xffff, p[6] >> 16,
9061 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9062 		}
9063 	}
9064 }
9065 
9066 static int
9067 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9068 {
9069 	uint32_t cfg, *buf;
9070 	int rc;
9071 
9072 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9073 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9074 	    M_ZERO | flags);
9075 	if (buf == NULL)
9076 		return (ENOMEM);
9077 
9078 	mtx_lock(&sc->reg_lock);
9079 	if (hw_off_limits(sc))
9080 		rc = ENXIO;
9081 	else {
9082 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9083 		if (rc == 0)
9084 			rc = -t4_cim_read_la(sc, buf, NULL);
9085 	}
9086 	mtx_unlock(&sc->reg_lock);
9087 	if (rc == 0) {
9088 		if (chip_id(sc) < CHELSIO_T6)
9089 			sbuf_cim_la4(sc, sb, buf, cfg);
9090 		else
9091 			sbuf_cim_la6(sc, sb, buf, cfg);
9092 	}
9093 	free(buf, M_CXGBE);
9094 	return (rc);
9095 }
9096 
9097 static int
9098 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9099 {
9100 	struct adapter *sc = arg1;
9101 	struct sbuf *sb;
9102 	int rc;
9103 
9104 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9105 	if (sb == NULL)
9106 		return (ENOMEM);
9107 
9108 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9109 	if (rc == 0)
9110 		rc = sbuf_finish(sb);
9111 	sbuf_delete(sb);
9112 	return (rc);
9113 }
9114 
9115 static void
9116 dump_cim_regs(struct adapter *sc)
9117 {
9118 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9119 	    device_get_nameunit(sc->dev),
9120 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9121 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9122 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9123 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9124 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9125 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9126 	    device_get_nameunit(sc->dev),
9127 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9128 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9129 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9130 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9131 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9132 }
9133 
9134 static void
9135 dump_cimla(struct adapter *sc)
9136 {
9137 	struct sbuf sb;
9138 	int rc;
9139 
9140 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9141 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9142 		    device_get_nameunit(sc->dev));
9143 		return;
9144 	}
9145 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9146 	if (rc == 0) {
9147 		rc = sbuf_finish(&sb);
9148 		if (rc == 0) {
9149 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9150 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9151 		}
9152 	}
9153 	sbuf_delete(&sb);
9154 }
9155 
9156 void
9157 t4_os_cim_err(struct adapter *sc)
9158 {
9159 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9160 }
9161 
9162 static int
9163 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9164 {
9165 	struct adapter *sc = arg1;
9166 	u_int i;
9167 	struct sbuf *sb;
9168 	uint32_t *buf, *p;
9169 	int rc;
9170 
9171 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9172 	if (sb == NULL)
9173 		return (ENOMEM);
9174 
9175 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9176 	    M_ZERO | M_WAITOK);
9177 
9178 	rc = 0;
9179 	mtx_lock(&sc->reg_lock);
9180 	if (hw_off_limits(sc))
9181 		rc = ENXIO;
9182 	else
9183 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9184 	mtx_unlock(&sc->reg_lock);
9185 	if (rc)
9186 		goto done;
9187 
9188 	p = buf;
9189 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9190 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9191 		    p[1], p[0]);
9192 	}
9193 
9194 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9195 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9196 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9197 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9198 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9199 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9200 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9201 		    p[0] & 1);
9202 	}
9203 	rc = sbuf_finish(sb);
9204 done:
9205 	sbuf_delete(sb);
9206 	free(buf, M_CXGBE);
9207 	return (rc);
9208 }
9209 
9210 static int
9211 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9212 {
9213 	struct adapter *sc = arg1;
9214 	u_int i;
9215 	struct sbuf *sb;
9216 	uint32_t *buf, *p;
9217 	int rc;
9218 
9219 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9220 	if (sb == NULL)
9221 		return (ENOMEM);
9222 
9223 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9224 	    M_ZERO | M_WAITOK);
9225 
9226 	rc = 0;
9227 	mtx_lock(&sc->reg_lock);
9228 	if (hw_off_limits(sc))
9229 		rc = ENXIO;
9230 	else
9231 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9232 	mtx_unlock(&sc->reg_lock);
9233 	if (rc)
9234 		goto done;
9235 
9236 	p = buf;
9237 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9238 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9239 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9240 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9241 		    p[4], p[3], p[2], p[1], p[0]);
9242 	}
9243 
9244 	sbuf_printf(sb, "\n\nCntl ID               Data");
9245 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9246 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9247 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9248 	}
9249 
9250 	rc = sbuf_finish(sb);
9251 done:
9252 	sbuf_delete(sb);
9253 	free(buf, M_CXGBE);
9254 	return (rc);
9255 }
9256 
9257 static int
9258 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9259 {
9260 	struct adapter *sc = arg1;
9261 	struct sbuf *sb;
9262 	int rc, i;
9263 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9264 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9265 	uint16_t thres[CIM_NUM_IBQ];
9266 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9267 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9268 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9269 
9270 	cim_num_obq = sc->chip_params->cim_num_obq;
9271 	if (is_t4(sc)) {
9272 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9273 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9274 	} else {
9275 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9276 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9277 	}
9278 	nq = CIM_NUM_IBQ + cim_num_obq;
9279 
9280 	mtx_lock(&sc->reg_lock);
9281 	if (hw_off_limits(sc))
9282 		rc = ENXIO;
9283 	else {
9284 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9285 		if (rc == 0) {
9286 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9287 			    obq_wr);
9288 			if (rc == 0)
9289 				t4_read_cimq_cfg(sc, base, size, thres);
9290 		}
9291 	}
9292 	mtx_unlock(&sc->reg_lock);
9293 	if (rc)
9294 		return (rc);
9295 
9296 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9297 	if (sb == NULL)
9298 		return (ENOMEM);
9299 
9300 	sbuf_printf(sb,
9301 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9302 
9303 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9304 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9305 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9306 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9307 		    G_QUEREMFLITS(p[2]) * 16);
9308 	for ( ; i < nq; i++, p += 4, wr += 2)
9309 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9310 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9311 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9312 		    G_QUEREMFLITS(p[2]) * 16);
9313 
9314 	rc = sbuf_finish(sb);
9315 	sbuf_delete(sb);
9316 
9317 	return (rc);
9318 }
9319 
9320 static int
9321 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9322 {
9323 	struct adapter *sc = arg1;
9324 	struct sbuf *sb;
9325 	int rc;
9326 	struct tp_cpl_stats stats;
9327 
9328 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9329 	if (sb == NULL)
9330 		return (ENOMEM);
9331 
9332 	rc = 0;
9333 	mtx_lock(&sc->reg_lock);
9334 	if (hw_off_limits(sc))
9335 		rc = ENXIO;
9336 	else
9337 		t4_tp_get_cpl_stats(sc, &stats, 0);
9338 	mtx_unlock(&sc->reg_lock);
9339 	if (rc)
9340 		goto done;
9341 
9342 	if (sc->chip_params->nchan > 2) {
9343 		sbuf_printf(sb, "                 channel 0  channel 1"
9344 		    "  channel 2  channel 3");
9345 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9346 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9347 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9348 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9349 	} else {
9350 		sbuf_printf(sb, "                 channel 0  channel 1");
9351 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9352 		    stats.req[0], stats.req[1]);
9353 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9354 		    stats.rsp[0], stats.rsp[1]);
9355 	}
9356 
9357 	rc = sbuf_finish(sb);
9358 done:
9359 	sbuf_delete(sb);
9360 	return (rc);
9361 }
9362 
9363 static int
9364 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9365 {
9366 	struct adapter *sc = arg1;
9367 	struct sbuf *sb;
9368 	int rc;
9369 	struct tp_usm_stats stats;
9370 
9371 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9372 	if (sb == NULL)
9373 		return (ENOMEM);
9374 
9375 	rc = 0;
9376 	mtx_lock(&sc->reg_lock);
9377 	if (hw_off_limits(sc))
9378 		rc = ENXIO;
9379 	else
9380 		t4_get_usm_stats(sc, &stats, 1);
9381 	mtx_unlock(&sc->reg_lock);
9382 	if (rc == 0) {
9383 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9384 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9385 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9386 		rc = sbuf_finish(sb);
9387 	}
9388 	sbuf_delete(sb);
9389 
9390 	return (rc);
9391 }
9392 
9393 static int
9394 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9395 {
9396 	struct adapter *sc = arg1;
9397 	struct sbuf *sb;
9398 	int rc;
9399 	struct tp_tid_stats stats;
9400 
9401 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9402 	if (sb == NULL)
9403 		return (ENOMEM);
9404 
9405 	rc = 0;
9406 	mtx_lock(&sc->reg_lock);
9407 	if (hw_off_limits(sc))
9408 		rc = ENXIO;
9409 	else
9410 		t4_tp_get_tid_stats(sc, &stats, 1);
9411 	mtx_unlock(&sc->reg_lock);
9412 	if (rc == 0) {
9413 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9414 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9415 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9416 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9417 		rc = sbuf_finish(sb);
9418 	}
9419 	sbuf_delete(sb);
9420 
9421 	return (rc);
9422 }
9423 
9424 static const char * const devlog_level_strings[] = {
9425 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9426 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9427 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9428 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9429 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9430 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9431 };
9432 
9433 static const char * const devlog_facility_strings[] = {
9434 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9435 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9436 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9437 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9438 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9439 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9440 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9441 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9442 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9443 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9444 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9445 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9446 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9447 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9448 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9449 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9450 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9451 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9452 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9453 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9454 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9455 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9456 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9457 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9458 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9459 };
9460 
9461 static int
9462 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9463 {
9464 	int i, j, rc, nentries, first = 0;
9465 	struct devlog_params *dparams = &sc->params.devlog;
9466 	struct fw_devlog_e *buf, *e;
9467 	uint64_t ftstamp = UINT64_MAX;
9468 
9469 	if (dparams->addr == 0)
9470 		return (ENXIO);
9471 
9472 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9473 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9474 	if (buf == NULL)
9475 		return (ENOMEM);
9476 
9477 	mtx_lock(&sc->reg_lock);
9478 	if (hw_off_limits(sc))
9479 		rc = ENXIO;
9480 	else
9481 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9482 		    dparams->size);
9483 	mtx_unlock(&sc->reg_lock);
9484 	if (rc != 0)
9485 		goto done;
9486 
9487 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9488 	for (i = 0; i < nentries; i++) {
9489 		e = &buf[i];
9490 
9491 		if (e->timestamp == 0)
9492 			break;	/* end */
9493 
9494 		e->timestamp = be64toh(e->timestamp);
9495 		e->seqno = be32toh(e->seqno);
9496 		for (j = 0; j < 8; j++)
9497 			e->params[j] = be32toh(e->params[j]);
9498 
9499 		if (e->timestamp < ftstamp) {
9500 			ftstamp = e->timestamp;
9501 			first = i;
9502 		}
9503 	}
9504 
9505 	if (buf[first].timestamp == 0)
9506 		goto done;	/* nothing in the log */
9507 
9508 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9509 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9510 
9511 	i = first;
9512 	do {
9513 		e = &buf[i];
9514 		if (e->timestamp == 0)
9515 			break;	/* end */
9516 
9517 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9518 		    e->seqno, e->timestamp,
9519 		    (e->level < nitems(devlog_level_strings) ?
9520 			devlog_level_strings[e->level] : "UNKNOWN"),
9521 		    (e->facility < nitems(devlog_facility_strings) ?
9522 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9523 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9524 		    e->params[2], e->params[3], e->params[4],
9525 		    e->params[5], e->params[6], e->params[7]);
9526 
9527 		if (++i == nentries)
9528 			i = 0;
9529 	} while (i != first);
9530 done:
9531 	free(buf, M_CXGBE);
9532 	return (rc);
9533 }
9534 
9535 static int
9536 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9537 {
9538 	struct adapter *sc = arg1;
9539 	int rc;
9540 	struct sbuf *sb;
9541 
9542 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9543 	if (sb == NULL)
9544 		return (ENOMEM);
9545 
9546 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9547 	if (rc == 0)
9548 		rc = sbuf_finish(sb);
9549 	sbuf_delete(sb);
9550 	return (rc);
9551 }
9552 
9553 static void
9554 dump_devlog(struct adapter *sc)
9555 {
9556 	int rc;
9557 	struct sbuf sb;
9558 
9559 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9560 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9561 		    device_get_nameunit(sc->dev));
9562 		return;
9563 	}
9564 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9565 	if (rc == 0) {
9566 		rc = sbuf_finish(&sb);
9567 		if (rc == 0) {
9568 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9569 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9570 		}
9571 	}
9572 	sbuf_delete(&sb);
9573 }
9574 
9575 static int
9576 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9577 {
9578 	struct adapter *sc = arg1;
9579 	struct sbuf *sb;
9580 	int rc;
9581 	struct tp_fcoe_stats stats[MAX_NCHAN];
9582 	int i, nchan = sc->chip_params->nchan;
9583 
9584 	rc = 0;
9585 	mtx_lock(&sc->reg_lock);
9586 	if (hw_off_limits(sc))
9587 		rc = ENXIO;
9588 	else {
9589 		for (i = 0; i < nchan; i++)
9590 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9591 	}
9592 	mtx_unlock(&sc->reg_lock);
9593 	if (rc != 0)
9594 		return (rc);
9595 
9596 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9597 	if (sb == NULL)
9598 		return (ENOMEM);
9599 
9600 	if (nchan > 2) {
9601 		sbuf_printf(sb, "                   channel 0        channel 1"
9602 		    "        channel 2        channel 3");
9603 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9604 		    stats[0].octets_ddp, stats[1].octets_ddp,
9605 		    stats[2].octets_ddp, stats[3].octets_ddp);
9606 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9607 		    stats[0].frames_ddp, stats[1].frames_ddp,
9608 		    stats[2].frames_ddp, stats[3].frames_ddp);
9609 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9610 		    stats[0].frames_drop, stats[1].frames_drop,
9611 		    stats[2].frames_drop, stats[3].frames_drop);
9612 	} else {
9613 		sbuf_printf(sb, "                   channel 0        channel 1");
9614 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9615 		    stats[0].octets_ddp, stats[1].octets_ddp);
9616 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9617 		    stats[0].frames_ddp, stats[1].frames_ddp);
9618 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9619 		    stats[0].frames_drop, stats[1].frames_drop);
9620 	}
9621 
9622 	rc = sbuf_finish(sb);
9623 	sbuf_delete(sb);
9624 
9625 	return (rc);
9626 }
9627 
9628 static int
9629 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9630 {
9631 	struct adapter *sc = arg1;
9632 	struct sbuf *sb;
9633 	int rc, i;
9634 	unsigned int map, kbps, ipg, mode;
9635 	unsigned int pace_tab[NTX_SCHED];
9636 
9637 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9638 	if (sb == NULL)
9639 		return (ENOMEM);
9640 
9641 	mtx_lock(&sc->reg_lock);
9642 	if (hw_off_limits(sc)) {
9643 		mtx_unlock(&sc->reg_lock);
9644 		rc = ENXIO;
9645 		goto done;
9646 	}
9647 
9648 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9649 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9650 	t4_read_pace_tbl(sc, pace_tab);
9651 	mtx_unlock(&sc->reg_lock);
9652 
9653 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9654 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9655 
9656 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9657 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9658 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9659 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9660 		if (kbps)
9661 			sbuf_printf(sb, "%9u     ", kbps);
9662 		else
9663 			sbuf_printf(sb, " disabled     ");
9664 
9665 		if (ipg)
9666 			sbuf_printf(sb, "%13u        ", ipg);
9667 		else
9668 			sbuf_printf(sb, "     disabled        ");
9669 
9670 		if (pace_tab[i])
9671 			sbuf_printf(sb, "%10u", pace_tab[i]);
9672 		else
9673 			sbuf_printf(sb, "  disabled");
9674 	}
9675 	rc = sbuf_finish(sb);
9676 done:
9677 	sbuf_delete(sb);
9678 	return (rc);
9679 }
9680 
9681 static int
9682 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9683 {
9684 	struct adapter *sc = arg1;
9685 	struct sbuf *sb;
9686 	int rc, i, j;
9687 	uint64_t *p0, *p1;
9688 	struct lb_port_stats s[2];
9689 	static const char *stat_name[] = {
9690 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9691 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9692 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9693 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9694 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9695 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9696 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9697 	};
9698 
9699 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9700 	if (sb == NULL)
9701 		return (ENOMEM);
9702 
9703 	memset(s, 0, sizeof(s));
9704 
9705 	rc = 0;
9706 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9707 		mtx_lock(&sc->reg_lock);
9708 		if (hw_off_limits(sc))
9709 			rc = ENXIO;
9710 		else {
9711 			t4_get_lb_stats(sc, i, &s[0]);
9712 			t4_get_lb_stats(sc, i + 1, &s[1]);
9713 		}
9714 		mtx_unlock(&sc->reg_lock);
9715 		if (rc != 0)
9716 			break;
9717 
9718 		p0 = &s[0].octets;
9719 		p1 = &s[1].octets;
9720 		sbuf_printf(sb, "%s                       Loopback %u"
9721 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9722 
9723 		for (j = 0; j < nitems(stat_name); j++)
9724 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9725 				   *p0++, *p1++);
9726 	}
9727 
9728 	if (rc == 0)
9729 		rc = sbuf_finish(sb);
9730 	sbuf_delete(sb);
9731 
9732 	return (rc);
9733 }
9734 
9735 static int
9736 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9737 {
9738 	int rc = 0;
9739 	struct port_info *pi = arg1;
9740 	struct link_config *lc = &pi->link_cfg;
9741 	struct sbuf *sb;
9742 
9743 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9744 	if (sb == NULL)
9745 		return (ENOMEM);
9746 
9747 	if (lc->link_ok || lc->link_down_rc == 255)
9748 		sbuf_printf(sb, "n/a");
9749 	else
9750 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9751 
9752 	rc = sbuf_finish(sb);
9753 	sbuf_delete(sb);
9754 
9755 	return (rc);
9756 }
9757 
9758 struct mem_desc {
9759 	u_int base;
9760 	u_int limit;
9761 	u_int idx;
9762 };
9763 
9764 static int
9765 mem_desc_cmp(const void *a, const void *b)
9766 {
9767 	const u_int v1 = ((const struct mem_desc *)a)->base;
9768 	const u_int v2 = ((const struct mem_desc *)b)->base;
9769 
9770 	if (v1 < v2)
9771 		return (-1);
9772 	else if (v1 > v2)
9773 		return (1);
9774 
9775 	return (0);
9776 }
9777 
9778 static void
9779 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9780     unsigned int to)
9781 {
9782 	unsigned int size;
9783 
9784 	if (from == to)
9785 		return;
9786 
9787 	size = to - from + 1;
9788 	if (size == 0)
9789 		return;
9790 
9791 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9792 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9793 }
9794 
9795 static int
9796 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9797 {
9798 	struct adapter *sc = arg1;
9799 	struct sbuf *sb;
9800 	int rc, i, n;
9801 	uint32_t lo, hi, used, free, alloc;
9802 	static const char *memory[] = {
9803 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9804 	};
9805 	static const char *region[] = {
9806 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9807 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9808 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9809 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9810 		"RQUDP region:", "PBL region:", "TXPBL region:",
9811 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9812 		"ULPTX state:", "On-chip queues:",
9813 	};
9814 	struct mem_desc avail[4];
9815 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9816 	struct mem_desc *md = mem;
9817 
9818 	rc = sysctl_wire_old_buffer(req, 0);
9819 	if (rc != 0)
9820 		return (rc);
9821 
9822 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9823 	if (sb == NULL)
9824 		return (ENOMEM);
9825 
9826 	for (i = 0; i < nitems(mem); i++) {
9827 		mem[i].limit = 0;
9828 		mem[i].idx = i;
9829 	}
9830 
9831 	mtx_lock(&sc->reg_lock);
9832 	if (hw_off_limits(sc)) {
9833 		rc = ENXIO;
9834 		goto done;
9835 	}
9836 
9837 	/* Find and sort the populated memory ranges */
9838 	i = 0;
9839 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9840 	if (lo & F_EDRAM0_ENABLE) {
9841 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9842 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9843 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9844 		avail[i].idx = 0;
9845 		i++;
9846 	}
9847 	if (lo & F_EDRAM1_ENABLE) {
9848 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9849 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9850 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9851 		avail[i].idx = 1;
9852 		i++;
9853 	}
9854 	if (lo & F_EXT_MEM_ENABLE) {
9855 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9856 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9857 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9858 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9859 		i++;
9860 	}
9861 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9862 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9863 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9864 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9865 		avail[i].idx = 4;
9866 		i++;
9867 	}
9868 	if (is_t6(sc) && lo & F_HMA_MUX) {
9869 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9870 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9871 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9872 		avail[i].idx = 5;
9873 		i++;
9874 	}
9875 	MPASS(i <= nitems(avail));
9876 	if (!i)                                    /* no memory available */
9877 		goto done;
9878 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9879 
9880 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9881 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9882 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9883 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9884 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9885 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9886 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9887 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9888 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9889 
9890 	/* the next few have explicit upper bounds */
9891 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9892 	md->limit = md->base - 1 +
9893 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9894 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9895 	md++;
9896 
9897 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9898 	md->limit = md->base - 1 +
9899 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9900 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9901 	md++;
9902 
9903 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9904 		if (chip_id(sc) <= CHELSIO_T5)
9905 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9906 		else
9907 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9908 		md->limit = 0;
9909 	} else {
9910 		md->base = 0;
9911 		md->idx = nitems(region);  /* hide it */
9912 	}
9913 	md++;
9914 
9915 #define ulp_region(reg) \
9916 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9917 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9918 
9919 	ulp_region(RX_ISCSI);
9920 	ulp_region(RX_TDDP);
9921 	ulp_region(TX_TPT);
9922 	ulp_region(RX_STAG);
9923 	ulp_region(RX_RQ);
9924 	ulp_region(RX_RQUDP);
9925 	ulp_region(RX_PBL);
9926 	ulp_region(TX_PBL);
9927 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9928 		ulp_region(RX_TLS_KEY);
9929 	}
9930 #undef ulp_region
9931 
9932 	md->base = 0;
9933 	if (is_t4(sc))
9934 		md->idx = nitems(region);
9935 	else {
9936 		uint32_t size = 0;
9937 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9938 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9939 
9940 		if (is_t5(sc)) {
9941 			if (sge_ctrl & F_VFIFO_ENABLE)
9942 				size = fifo_size << 2;
9943 		} else
9944 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9945 
9946 		if (size) {
9947 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9948 			md->limit = md->base + size - 1;
9949 		} else
9950 			md->idx = nitems(region);
9951 	}
9952 	md++;
9953 
9954 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9955 	md->limit = 0;
9956 	md++;
9957 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9958 	md->limit = 0;
9959 	md++;
9960 
9961 	md->base = sc->vres.ocq.start;
9962 	if (sc->vres.ocq.size)
9963 		md->limit = md->base + sc->vres.ocq.size - 1;
9964 	else
9965 		md->idx = nitems(region);  /* hide it */
9966 	md++;
9967 
9968 	/* add any address-space holes, there can be up to 3 */
9969 	for (n = 0; n < i - 1; n++)
9970 		if (avail[n].limit < avail[n + 1].base)
9971 			(md++)->base = avail[n].limit;
9972 	if (avail[n].limit)
9973 		(md++)->base = avail[n].limit;
9974 
9975 	n = md - mem;
9976 	MPASS(n <= nitems(mem));
9977 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9978 
9979 	for (lo = 0; lo < i; lo++)
9980 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9981 				avail[lo].limit - 1);
9982 
9983 	sbuf_printf(sb, "\n");
9984 	for (i = 0; i < n; i++) {
9985 		if (mem[i].idx >= nitems(region))
9986 			continue;                        /* skip holes */
9987 		if (!mem[i].limit)
9988 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
9989 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
9990 				mem[i].limit);
9991 	}
9992 
9993 	sbuf_printf(sb, "\n");
9994 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
9995 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
9996 	mem_region_show(sb, "uP RAM:", lo, hi);
9997 
9998 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
9999 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10000 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10001 
10002 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10003 	for (i = 0, free = 0; i < 2; i++)
10004 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10005 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10006 		   G_PMRXMAXPAGE(lo), free,
10007 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10008 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10009 
10010 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10011 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10012 	for (i = 0, free = 0; i < 4; i++)
10013 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10014 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10015 		   G_PMTXMAXPAGE(lo), free,
10016 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10017 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10018 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10019 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10020 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10021 
10022 	for (i = 0; i < 4; i++) {
10023 		if (chip_id(sc) > CHELSIO_T5)
10024 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10025 		else
10026 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10027 		if (is_t5(sc)) {
10028 			used = G_T5_USED(lo);
10029 			alloc = G_T5_ALLOC(lo);
10030 		} else {
10031 			used = G_USED(lo);
10032 			alloc = G_ALLOC(lo);
10033 		}
10034 		/* For T6 these are MAC buffer groups */
10035 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10036 		    i, used, alloc);
10037 	}
10038 	for (i = 0; i < sc->chip_params->nchan; i++) {
10039 		if (chip_id(sc) > CHELSIO_T5)
10040 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10041 		else
10042 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10043 		if (is_t5(sc)) {
10044 			used = G_T5_USED(lo);
10045 			alloc = G_T5_ALLOC(lo);
10046 		} else {
10047 			used = G_USED(lo);
10048 			alloc = G_ALLOC(lo);
10049 		}
10050 		/* For T6 these are MAC buffer groups */
10051 		sbuf_printf(sb,
10052 		    "\nLoopback %d using %u pages out of %u allocated",
10053 		    i, used, alloc);
10054 	}
10055 done:
10056 	mtx_unlock(&sc->reg_lock);
10057 	if (rc == 0)
10058 		rc = sbuf_finish(sb);
10059 	sbuf_delete(sb);
10060 	return (rc);
10061 }
10062 
10063 static inline void
10064 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10065 {
10066 	*mask = x | y;
10067 	y = htobe64(y);
10068 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10069 }
10070 
10071 static int
10072 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10073 {
10074 	struct adapter *sc = arg1;
10075 	struct sbuf *sb;
10076 	int rc, i;
10077 
10078 	MPASS(chip_id(sc) <= CHELSIO_T5);
10079 
10080 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10081 	if (sb == NULL)
10082 		return (ENOMEM);
10083 
10084 	sbuf_printf(sb,
10085 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10086 	    "  VF              Replication             P0 P1 P2 P3  ML");
10087 	rc = 0;
10088 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10089 		uint64_t tcamx, tcamy, mask;
10090 		uint32_t cls_lo, cls_hi;
10091 		uint8_t addr[ETHER_ADDR_LEN];
10092 
10093 		mtx_lock(&sc->reg_lock);
10094 		if (hw_off_limits(sc))
10095 			rc = ENXIO;
10096 		else {
10097 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10098 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10099 		}
10100 		mtx_unlock(&sc->reg_lock);
10101 		if (rc != 0)
10102 			break;
10103 		if (tcamx & tcamy)
10104 			continue;
10105 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10106 		mtx_lock(&sc->reg_lock);
10107 		if (hw_off_limits(sc))
10108 			rc = ENXIO;
10109 		else {
10110 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10111 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10112 		}
10113 		mtx_unlock(&sc->reg_lock);
10114 		if (rc != 0)
10115 			break;
10116 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10117 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10118 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10119 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10120 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10121 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10122 
10123 		if (cls_lo & F_REPLICATE) {
10124 			struct fw_ldst_cmd ldst_cmd;
10125 
10126 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10127 			ldst_cmd.op_to_addrspace =
10128 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10129 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10130 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10131 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10132 			ldst_cmd.u.mps.rplc.fid_idx =
10133 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10134 				V_FW_LDST_CMD_IDX(i));
10135 
10136 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10137 			    "t4mps");
10138 			if (rc)
10139 				break;
10140 			if (hw_off_limits(sc))
10141 				rc = ENXIO;
10142 			else
10143 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10144 				    sizeof(ldst_cmd), &ldst_cmd);
10145 			end_synchronized_op(sc, 0);
10146 			if (rc != 0)
10147 				break;
10148 			else {
10149 				sbuf_printf(sb, " %08x %08x %08x %08x",
10150 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10151 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10152 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10153 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10154 			}
10155 		} else
10156 			sbuf_printf(sb, "%36s", "");
10157 
10158 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10159 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10160 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10161 	}
10162 
10163 	if (rc)
10164 		(void) sbuf_finish(sb);
10165 	else
10166 		rc = sbuf_finish(sb);
10167 	sbuf_delete(sb);
10168 
10169 	return (rc);
10170 }
10171 
10172 static int
10173 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10174 {
10175 	struct adapter *sc = arg1;
10176 	struct sbuf *sb;
10177 	int rc, i;
10178 
10179 	MPASS(chip_id(sc) > CHELSIO_T5);
10180 
10181 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10182 	if (sb == NULL)
10183 		return (ENOMEM);
10184 
10185 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10186 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10187 	    "                           Replication"
10188 	    "                                    P0 P1 P2 P3  ML\n");
10189 
10190 	rc = 0;
10191 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10192 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10193 		uint16_t ivlan;
10194 		uint64_t tcamx, tcamy, val, mask;
10195 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10196 		uint8_t addr[ETHER_ADDR_LEN];
10197 
10198 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10199 		if (i < 256)
10200 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10201 		else
10202 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10203 		mtx_lock(&sc->reg_lock);
10204 		if (hw_off_limits(sc))
10205 			rc = ENXIO;
10206 		else {
10207 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10208 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10209 			tcamy = G_DMACH(val) << 32;
10210 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10211 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10212 		}
10213 		mtx_unlock(&sc->reg_lock);
10214 		if (rc != 0)
10215 			break;
10216 
10217 		lookup_type = G_DATALKPTYPE(data2);
10218 		port_num = G_DATAPORTNUM(data2);
10219 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10220 			/* Inner header VNI */
10221 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10222 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10223 			dip_hit = data2 & F_DATADIPHIT;
10224 			vlan_vld = 0;
10225 		} else {
10226 			vniy = 0;
10227 			dip_hit = 0;
10228 			vlan_vld = data2 & F_DATAVIDH2;
10229 			ivlan = G_VIDL(val);
10230 		}
10231 
10232 		ctl |= V_CTLXYBITSEL(1);
10233 		mtx_lock(&sc->reg_lock);
10234 		if (hw_off_limits(sc))
10235 			rc = ENXIO;
10236 		else {
10237 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10238 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10239 			tcamx = G_DMACH(val) << 32;
10240 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10241 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10242 		}
10243 		mtx_unlock(&sc->reg_lock);
10244 		if (rc != 0)
10245 			break;
10246 
10247 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10248 			/* Inner header VNI mask */
10249 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10250 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10251 		} else
10252 			vnix = 0;
10253 
10254 		if (tcamx & tcamy)
10255 			continue;
10256 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10257 
10258 		mtx_lock(&sc->reg_lock);
10259 		if (hw_off_limits(sc))
10260 			rc = ENXIO;
10261 		else {
10262 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10263 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10264 		}
10265 		mtx_unlock(&sc->reg_lock);
10266 		if (rc != 0)
10267 			break;
10268 
10269 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10270 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10271 			    "%012jx %06x %06x    -    -   %3c"
10272 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10273 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10274 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10275 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10276 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10277 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10278 		} else {
10279 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10280 			    "%012jx    -       -   ", i, addr[0], addr[1],
10281 			    addr[2], addr[3], addr[4], addr[5],
10282 			    (uintmax_t)mask);
10283 
10284 			if (vlan_vld)
10285 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10286 			else
10287 				sbuf_printf(sb, "  -    N     ");
10288 
10289 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10290 			    lookup_type ? 'I' : 'O', port_num,
10291 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10292 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10293 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10294 		}
10295 
10296 
10297 		if (cls_lo & F_T6_REPLICATE) {
10298 			struct fw_ldst_cmd ldst_cmd;
10299 
10300 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10301 			ldst_cmd.op_to_addrspace =
10302 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10303 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10304 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10305 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10306 			ldst_cmd.u.mps.rplc.fid_idx =
10307 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10308 				V_FW_LDST_CMD_IDX(i));
10309 
10310 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10311 			    "t6mps");
10312 			if (rc)
10313 				break;
10314 			if (hw_off_limits(sc))
10315 				rc = ENXIO;
10316 			else
10317 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10318 				    sizeof(ldst_cmd), &ldst_cmd);
10319 			end_synchronized_op(sc, 0);
10320 			if (rc != 0)
10321 				break;
10322 			else {
10323 				sbuf_printf(sb, " %08x %08x %08x %08x"
10324 				    " %08x %08x %08x %08x",
10325 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10326 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10327 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10328 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10329 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10330 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10331 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10332 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10333 			}
10334 		} else
10335 			sbuf_printf(sb, "%72s", "");
10336 
10337 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10338 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10339 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10340 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10341 	}
10342 
10343 	if (rc)
10344 		(void) sbuf_finish(sb);
10345 	else
10346 		rc = sbuf_finish(sb);
10347 	sbuf_delete(sb);
10348 
10349 	return (rc);
10350 }
10351 
10352 static int
10353 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10354 {
10355 	struct adapter *sc = arg1;
10356 	struct sbuf *sb;
10357 	int rc;
10358 	uint16_t mtus[NMTUS];
10359 
10360 	rc = 0;
10361 	mtx_lock(&sc->reg_lock);
10362 	if (hw_off_limits(sc))
10363 		rc = ENXIO;
10364 	else
10365 		t4_read_mtu_tbl(sc, mtus, NULL);
10366 	mtx_unlock(&sc->reg_lock);
10367 	if (rc != 0)
10368 		return (rc);
10369 
10370 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10371 	if (sb == NULL)
10372 		return (ENOMEM);
10373 
10374 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10375 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10376 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10377 	    mtus[14], mtus[15]);
10378 
10379 	rc = sbuf_finish(sb);
10380 	sbuf_delete(sb);
10381 
10382 	return (rc);
10383 }
10384 
10385 static int
10386 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10387 {
10388 	struct adapter *sc = arg1;
10389 	struct sbuf *sb;
10390 	int rc, i;
10391 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10392 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10393 	static const char *tx_stats[MAX_PM_NSTATS] = {
10394 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10395 		"Tx FIFO wait", NULL, "Tx latency"
10396 	};
10397 	static const char *rx_stats[MAX_PM_NSTATS] = {
10398 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10399 		"Rx FIFO wait", NULL, "Rx latency"
10400 	};
10401 
10402 	rc = 0;
10403 	mtx_lock(&sc->reg_lock);
10404 	if (hw_off_limits(sc))
10405 		rc = ENXIO;
10406 	else {
10407 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10408 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10409 	}
10410 	mtx_unlock(&sc->reg_lock);
10411 	if (rc != 0)
10412 		return (rc);
10413 
10414 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10415 	if (sb == NULL)
10416 		return (ENOMEM);
10417 
10418 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10419 	for (i = 0; i < 4; i++) {
10420 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10421 		    tx_cyc[i]);
10422 	}
10423 
10424 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10425 	for (i = 0; i < 4; i++) {
10426 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10427 		    rx_cyc[i]);
10428 	}
10429 
10430 	if (chip_id(sc) > CHELSIO_T5) {
10431 		sbuf_printf(sb,
10432 		    "\n              Total wait      Total occupancy");
10433 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10434 		    tx_cyc[i]);
10435 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10436 		    rx_cyc[i]);
10437 
10438 		i += 2;
10439 		MPASS(i < nitems(tx_stats));
10440 
10441 		sbuf_printf(sb,
10442 		    "\n                   Reads           Total wait");
10443 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10444 		    tx_cyc[i]);
10445 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10446 		    rx_cyc[i]);
10447 	}
10448 
10449 	rc = sbuf_finish(sb);
10450 	sbuf_delete(sb);
10451 
10452 	return (rc);
10453 }
10454 
10455 static int
10456 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10457 {
10458 	struct adapter *sc = arg1;
10459 	struct sbuf *sb;
10460 	int rc;
10461 	struct tp_rdma_stats stats;
10462 
10463 	rc = 0;
10464 	mtx_lock(&sc->reg_lock);
10465 	if (hw_off_limits(sc))
10466 		rc = ENXIO;
10467 	else
10468 		t4_tp_get_rdma_stats(sc, &stats, 0);
10469 	mtx_unlock(&sc->reg_lock);
10470 	if (rc != 0)
10471 		return (rc);
10472 
10473 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10474 	if (sb == NULL)
10475 		return (ENOMEM);
10476 
10477 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10478 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10479 
10480 	rc = sbuf_finish(sb);
10481 	sbuf_delete(sb);
10482 
10483 	return (rc);
10484 }
10485 
10486 static int
10487 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10488 {
10489 	struct adapter *sc = arg1;
10490 	struct sbuf *sb;
10491 	int rc;
10492 	struct tp_tcp_stats v4, v6;
10493 
10494 	rc = 0;
10495 	mtx_lock(&sc->reg_lock);
10496 	if (hw_off_limits(sc))
10497 		rc = ENXIO;
10498 	else
10499 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10500 	mtx_unlock(&sc->reg_lock);
10501 	if (rc != 0)
10502 		return (rc);
10503 
10504 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10505 	if (sb == NULL)
10506 		return (ENOMEM);
10507 
10508 	sbuf_printf(sb,
10509 	    "                                IP                 IPv6\n");
10510 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10511 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10512 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10513 	    v4.tcp_in_segs, v6.tcp_in_segs);
10514 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10515 	    v4.tcp_out_segs, v6.tcp_out_segs);
10516 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10517 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10518 
10519 	rc = sbuf_finish(sb);
10520 	sbuf_delete(sb);
10521 
10522 	return (rc);
10523 }
10524 
10525 static int
10526 sysctl_tids(SYSCTL_HANDLER_ARGS)
10527 {
10528 	struct adapter *sc = arg1;
10529 	struct sbuf *sb;
10530 	int rc;
10531 	uint32_t x, y;
10532 	struct tid_info *t = &sc->tids;
10533 
10534 	rc = 0;
10535 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10536 	if (sb == NULL)
10537 		return (ENOMEM);
10538 
10539 	if (t->natids) {
10540 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10541 		    t->atids_in_use);
10542 	}
10543 
10544 	if (t->nhpftids) {
10545 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10546 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10547 	}
10548 
10549 	if (t->ntids) {
10550 		bool hashen = false;
10551 
10552 		mtx_lock(&sc->reg_lock);
10553 		if (hw_off_limits(sc))
10554 			rc = ENXIO;
10555 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10556 			hashen = true;
10557 			if (chip_id(sc) <= CHELSIO_T5) {
10558 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10559 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10560 			} else {
10561 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10562 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10563 			}
10564 		}
10565 		mtx_unlock(&sc->reg_lock);
10566 		if (rc != 0)
10567 			goto done;
10568 
10569 		sbuf_printf(sb, "TID range: ");
10570 		if (hashen) {
10571 			if (x)
10572 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10573 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10574 		} else {
10575 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10576 			    t->ntids - 1);
10577 		}
10578 		sbuf_printf(sb, ", in use: %u\n",
10579 		    atomic_load_acq_int(&t->tids_in_use));
10580 	}
10581 
10582 	if (t->nstids) {
10583 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10584 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10585 	}
10586 
10587 	if (t->nftids) {
10588 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10589 		    t->ftid_end, t->ftids_in_use);
10590 	}
10591 
10592 	if (t->netids) {
10593 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10594 		    t->etid_base + t->netids - 1, t->etids_in_use);
10595 	}
10596 
10597 	mtx_lock(&sc->reg_lock);
10598 	if (hw_off_limits(sc))
10599 		rc = ENXIO;
10600 	else {
10601 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10602 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10603 	}
10604 	mtx_unlock(&sc->reg_lock);
10605 	if (rc != 0)
10606 		goto done;
10607 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10608 done:
10609 	if (rc == 0)
10610 		rc = sbuf_finish(sb);
10611 	else
10612 		(void)sbuf_finish(sb);
10613 	sbuf_delete(sb);
10614 
10615 	return (rc);
10616 }
10617 
10618 static int
10619 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10620 {
10621 	struct adapter *sc = arg1;
10622 	struct sbuf *sb;
10623 	int rc;
10624 	struct tp_err_stats stats;
10625 
10626 	rc = 0;
10627 	mtx_lock(&sc->reg_lock);
10628 	if (hw_off_limits(sc))
10629 		rc = ENXIO;
10630 	else
10631 		t4_tp_get_err_stats(sc, &stats, 0);
10632 	mtx_unlock(&sc->reg_lock);
10633 	if (rc != 0)
10634 		return (rc);
10635 
10636 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10637 	if (sb == NULL)
10638 		return (ENOMEM);
10639 
10640 	if (sc->chip_params->nchan > 2) {
10641 		sbuf_printf(sb, "                 channel 0  channel 1"
10642 		    "  channel 2  channel 3\n");
10643 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10644 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10645 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10646 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10647 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10648 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10649 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10650 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10651 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10652 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10653 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10654 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10655 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10656 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10657 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10658 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10659 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10660 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10661 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10662 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10663 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10664 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10665 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10666 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10667 	} else {
10668 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10669 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10670 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10671 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10672 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10673 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10674 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10675 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10676 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10677 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10678 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10679 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10680 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10681 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10682 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10683 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10684 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10685 	}
10686 
10687 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10688 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10689 
10690 	rc = sbuf_finish(sb);
10691 	sbuf_delete(sb);
10692 
10693 	return (rc);
10694 }
10695 
10696 static int
10697 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10698 {
10699 	struct adapter *sc = arg1;
10700 	struct sbuf *sb;
10701 	int rc;
10702 	struct tp_tnl_stats stats;
10703 
10704 	rc = 0;
10705 	mtx_lock(&sc->reg_lock);
10706 	if (hw_off_limits(sc))
10707 		rc = ENXIO;
10708 	else
10709 		t4_tp_get_tnl_stats(sc, &stats, 1);
10710 	mtx_unlock(&sc->reg_lock);
10711 	if (rc != 0)
10712 		return (rc);
10713 
10714 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10715 	if (sb == NULL)
10716 		return (ENOMEM);
10717 
10718 	if (sc->chip_params->nchan > 2) {
10719 		sbuf_printf(sb, "           channel 0  channel 1"
10720 		    "  channel 2  channel 3\n");
10721 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10722 		    stats.out_pkt[0], stats.out_pkt[1],
10723 		    stats.out_pkt[2], stats.out_pkt[3]);
10724 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10725 		    stats.in_pkt[0], stats.in_pkt[1],
10726 		    stats.in_pkt[2], stats.in_pkt[3]);
10727 	} else {
10728 		sbuf_printf(sb, "           channel 0  channel 1\n");
10729 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10730 		    stats.out_pkt[0], stats.out_pkt[1]);
10731 		sbuf_printf(sb, "InPkts:   %10u %10u",
10732 		    stats.in_pkt[0], stats.in_pkt[1]);
10733 	}
10734 
10735 	rc = sbuf_finish(sb);
10736 	sbuf_delete(sb);
10737 
10738 	return (rc);
10739 }
10740 
10741 static int
10742 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10743 {
10744 	struct adapter *sc = arg1;
10745 	struct tp_params *tpp = &sc->params.tp;
10746 	u_int mask;
10747 	int rc;
10748 
10749 	mask = tpp->la_mask >> 16;
10750 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10751 	if (rc != 0 || req->newptr == NULL)
10752 		return (rc);
10753 	if (mask > 0xffff)
10754 		return (EINVAL);
10755 	mtx_lock(&sc->reg_lock);
10756 	if (hw_off_limits(sc))
10757 		rc = ENXIO;
10758 	else {
10759 		tpp->la_mask = mask << 16;
10760 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10761 		    tpp->la_mask);
10762 	}
10763 	mtx_unlock(&sc->reg_lock);
10764 
10765 	return (rc);
10766 }
10767 
10768 struct field_desc {
10769 	const char *name;
10770 	u_int start;
10771 	u_int width;
10772 };
10773 
10774 static void
10775 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10776 {
10777 	char buf[32];
10778 	int line_size = 0;
10779 
10780 	while (f->name) {
10781 		uint64_t mask = (1ULL << f->width) - 1;
10782 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10783 		    ((uintmax_t)v >> f->start) & mask);
10784 
10785 		if (line_size + len >= 79) {
10786 			line_size = 8;
10787 			sbuf_printf(sb, "\n        ");
10788 		}
10789 		sbuf_printf(sb, "%s ", buf);
10790 		line_size += len + 1;
10791 		f++;
10792 	}
10793 	sbuf_printf(sb, "\n");
10794 }
10795 
10796 static const struct field_desc tp_la0[] = {
10797 	{ "RcfOpCodeOut", 60, 4 },
10798 	{ "State", 56, 4 },
10799 	{ "WcfState", 52, 4 },
10800 	{ "RcfOpcSrcOut", 50, 2 },
10801 	{ "CRxError", 49, 1 },
10802 	{ "ERxError", 48, 1 },
10803 	{ "SanityFailed", 47, 1 },
10804 	{ "SpuriousMsg", 46, 1 },
10805 	{ "FlushInputMsg", 45, 1 },
10806 	{ "FlushInputCpl", 44, 1 },
10807 	{ "RssUpBit", 43, 1 },
10808 	{ "RssFilterHit", 42, 1 },
10809 	{ "Tid", 32, 10 },
10810 	{ "InitTcb", 31, 1 },
10811 	{ "LineNumber", 24, 7 },
10812 	{ "Emsg", 23, 1 },
10813 	{ "EdataOut", 22, 1 },
10814 	{ "Cmsg", 21, 1 },
10815 	{ "CdataOut", 20, 1 },
10816 	{ "EreadPdu", 19, 1 },
10817 	{ "CreadPdu", 18, 1 },
10818 	{ "TunnelPkt", 17, 1 },
10819 	{ "RcfPeerFin", 16, 1 },
10820 	{ "RcfReasonOut", 12, 4 },
10821 	{ "TxCchannel", 10, 2 },
10822 	{ "RcfTxChannel", 8, 2 },
10823 	{ "RxEchannel", 6, 2 },
10824 	{ "RcfRxChannel", 5, 1 },
10825 	{ "RcfDataOutSrdy", 4, 1 },
10826 	{ "RxDvld", 3, 1 },
10827 	{ "RxOoDvld", 2, 1 },
10828 	{ "RxCongestion", 1, 1 },
10829 	{ "TxCongestion", 0, 1 },
10830 	{ NULL }
10831 };
10832 
10833 static const struct field_desc tp_la1[] = {
10834 	{ "CplCmdIn", 56, 8 },
10835 	{ "CplCmdOut", 48, 8 },
10836 	{ "ESynOut", 47, 1 },
10837 	{ "EAckOut", 46, 1 },
10838 	{ "EFinOut", 45, 1 },
10839 	{ "ERstOut", 44, 1 },
10840 	{ "SynIn", 43, 1 },
10841 	{ "AckIn", 42, 1 },
10842 	{ "FinIn", 41, 1 },
10843 	{ "RstIn", 40, 1 },
10844 	{ "DataIn", 39, 1 },
10845 	{ "DataInVld", 38, 1 },
10846 	{ "PadIn", 37, 1 },
10847 	{ "RxBufEmpty", 36, 1 },
10848 	{ "RxDdp", 35, 1 },
10849 	{ "RxFbCongestion", 34, 1 },
10850 	{ "TxFbCongestion", 33, 1 },
10851 	{ "TxPktSumSrdy", 32, 1 },
10852 	{ "RcfUlpType", 28, 4 },
10853 	{ "Eread", 27, 1 },
10854 	{ "Ebypass", 26, 1 },
10855 	{ "Esave", 25, 1 },
10856 	{ "Static0", 24, 1 },
10857 	{ "Cread", 23, 1 },
10858 	{ "Cbypass", 22, 1 },
10859 	{ "Csave", 21, 1 },
10860 	{ "CPktOut", 20, 1 },
10861 	{ "RxPagePoolFull", 18, 2 },
10862 	{ "RxLpbkPkt", 17, 1 },
10863 	{ "TxLpbkPkt", 16, 1 },
10864 	{ "RxVfValid", 15, 1 },
10865 	{ "SynLearned", 14, 1 },
10866 	{ "SetDelEntry", 13, 1 },
10867 	{ "SetInvEntry", 12, 1 },
10868 	{ "CpcmdDvld", 11, 1 },
10869 	{ "CpcmdSave", 10, 1 },
10870 	{ "RxPstructsFull", 8, 2 },
10871 	{ "EpcmdDvld", 7, 1 },
10872 	{ "EpcmdFlush", 6, 1 },
10873 	{ "EpcmdTrimPrefix", 5, 1 },
10874 	{ "EpcmdTrimPostfix", 4, 1 },
10875 	{ "ERssIp4Pkt", 3, 1 },
10876 	{ "ERssIp6Pkt", 2, 1 },
10877 	{ "ERssTcpUdpPkt", 1, 1 },
10878 	{ "ERssFceFipPkt", 0, 1 },
10879 	{ NULL }
10880 };
10881 
10882 static const struct field_desc tp_la2[] = {
10883 	{ "CplCmdIn", 56, 8 },
10884 	{ "MpsVfVld", 55, 1 },
10885 	{ "MpsPf", 52, 3 },
10886 	{ "MpsVf", 44, 8 },
10887 	{ "SynIn", 43, 1 },
10888 	{ "AckIn", 42, 1 },
10889 	{ "FinIn", 41, 1 },
10890 	{ "RstIn", 40, 1 },
10891 	{ "DataIn", 39, 1 },
10892 	{ "DataInVld", 38, 1 },
10893 	{ "PadIn", 37, 1 },
10894 	{ "RxBufEmpty", 36, 1 },
10895 	{ "RxDdp", 35, 1 },
10896 	{ "RxFbCongestion", 34, 1 },
10897 	{ "TxFbCongestion", 33, 1 },
10898 	{ "TxPktSumSrdy", 32, 1 },
10899 	{ "RcfUlpType", 28, 4 },
10900 	{ "Eread", 27, 1 },
10901 	{ "Ebypass", 26, 1 },
10902 	{ "Esave", 25, 1 },
10903 	{ "Static0", 24, 1 },
10904 	{ "Cread", 23, 1 },
10905 	{ "Cbypass", 22, 1 },
10906 	{ "Csave", 21, 1 },
10907 	{ "CPktOut", 20, 1 },
10908 	{ "RxPagePoolFull", 18, 2 },
10909 	{ "RxLpbkPkt", 17, 1 },
10910 	{ "TxLpbkPkt", 16, 1 },
10911 	{ "RxVfValid", 15, 1 },
10912 	{ "SynLearned", 14, 1 },
10913 	{ "SetDelEntry", 13, 1 },
10914 	{ "SetInvEntry", 12, 1 },
10915 	{ "CpcmdDvld", 11, 1 },
10916 	{ "CpcmdSave", 10, 1 },
10917 	{ "RxPstructsFull", 8, 2 },
10918 	{ "EpcmdDvld", 7, 1 },
10919 	{ "EpcmdFlush", 6, 1 },
10920 	{ "EpcmdTrimPrefix", 5, 1 },
10921 	{ "EpcmdTrimPostfix", 4, 1 },
10922 	{ "ERssIp4Pkt", 3, 1 },
10923 	{ "ERssIp6Pkt", 2, 1 },
10924 	{ "ERssTcpUdpPkt", 1, 1 },
10925 	{ "ERssFceFipPkt", 0, 1 },
10926 	{ NULL }
10927 };
10928 
10929 static void
10930 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10931 {
10932 
10933 	field_desc_show(sb, *p, tp_la0);
10934 }
10935 
10936 static void
10937 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10938 {
10939 
10940 	if (idx)
10941 		sbuf_printf(sb, "\n");
10942 	field_desc_show(sb, p[0], tp_la0);
10943 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10944 		field_desc_show(sb, p[1], tp_la0);
10945 }
10946 
10947 static void
10948 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10949 {
10950 
10951 	if (idx)
10952 		sbuf_printf(sb, "\n");
10953 	field_desc_show(sb, p[0], tp_la0);
10954 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10955 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10956 }
10957 
10958 static int
10959 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10960 {
10961 	struct adapter *sc = arg1;
10962 	struct sbuf *sb;
10963 	uint64_t *buf, *p;
10964 	int rc;
10965 	u_int i, inc;
10966 	void (*show_func)(struct sbuf *, uint64_t *, int);
10967 
10968 	rc = 0;
10969 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10970 	if (sb == NULL)
10971 		return (ENOMEM);
10972 
10973 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
10974 
10975 	mtx_lock(&sc->reg_lock);
10976 	if (hw_off_limits(sc))
10977 		rc = ENXIO;
10978 	else {
10979 		t4_tp_read_la(sc, buf, NULL);
10980 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
10981 		case 2:
10982 			inc = 2;
10983 			show_func = tp_la_show2;
10984 			break;
10985 		case 3:
10986 			inc = 2;
10987 			show_func = tp_la_show3;
10988 			break;
10989 		default:
10990 			inc = 1;
10991 			show_func = tp_la_show;
10992 		}
10993 	}
10994 	mtx_unlock(&sc->reg_lock);
10995 	if (rc != 0)
10996 		goto done;
10997 
10998 	p = buf;
10999 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11000 		(*show_func)(sb, p, i);
11001 	rc = sbuf_finish(sb);
11002 done:
11003 	sbuf_delete(sb);
11004 	free(buf, M_CXGBE);
11005 	return (rc);
11006 }
11007 
11008 static int
11009 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11010 {
11011 	struct adapter *sc = arg1;
11012 	struct sbuf *sb;
11013 	int rc;
11014 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11015 
11016 	rc = 0;
11017 	mtx_lock(&sc->reg_lock);
11018 	if (hw_off_limits(sc))
11019 		rc = ENXIO;
11020 	else
11021 		t4_get_chan_txrate(sc, nrate, orate);
11022 	mtx_unlock(&sc->reg_lock);
11023 	if (rc != 0)
11024 		return (rc);
11025 
11026 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11027 	if (sb == NULL)
11028 		return (ENOMEM);
11029 
11030 	if (sc->chip_params->nchan > 2) {
11031 		sbuf_printf(sb, "              channel 0   channel 1"
11032 		    "   channel 2   channel 3\n");
11033 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11034 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11035 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11036 		    orate[0], orate[1], orate[2], orate[3]);
11037 	} else {
11038 		sbuf_printf(sb, "              channel 0   channel 1\n");
11039 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11040 		    nrate[0], nrate[1]);
11041 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11042 		    orate[0], orate[1]);
11043 	}
11044 
11045 	rc = sbuf_finish(sb);
11046 	sbuf_delete(sb);
11047 
11048 	return (rc);
11049 }
11050 
11051 static int
11052 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11053 {
11054 	struct adapter *sc = arg1;
11055 	struct sbuf *sb;
11056 	uint32_t *buf, *p;
11057 	int rc, i;
11058 
11059 	rc = 0;
11060 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11061 	if (sb == NULL)
11062 		return (ENOMEM);
11063 
11064 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11065 	    M_ZERO | M_WAITOK);
11066 
11067 	mtx_lock(&sc->reg_lock);
11068 	if (hw_off_limits(sc))
11069 		rc = ENXIO;
11070 	else
11071 		t4_ulprx_read_la(sc, buf);
11072 	mtx_unlock(&sc->reg_lock);
11073 	if (rc != 0)
11074 		goto done;
11075 
11076 	p = buf;
11077 	sbuf_printf(sb, "      Pcmd        Type   Message"
11078 	    "                Data");
11079 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11080 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11081 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11082 	}
11083 	rc = sbuf_finish(sb);
11084 done:
11085 	sbuf_delete(sb);
11086 	free(buf, M_CXGBE);
11087 	return (rc);
11088 }
11089 
11090 static int
11091 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11092 {
11093 	struct adapter *sc = arg1;
11094 	struct sbuf *sb;
11095 	int rc;
11096 	uint32_t cfg, s1, s2;
11097 
11098 	MPASS(chip_id(sc) >= CHELSIO_T5);
11099 
11100 	rc = 0;
11101 	mtx_lock(&sc->reg_lock);
11102 	if (hw_off_limits(sc))
11103 		rc = ENXIO;
11104 	else {
11105 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11106 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11107 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11108 	}
11109 	mtx_unlock(&sc->reg_lock);
11110 	if (rc != 0)
11111 		return (rc);
11112 
11113 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11114 	if (sb == NULL)
11115 		return (ENOMEM);
11116 
11117 	if (G_STATSOURCE_T5(cfg) == 7) {
11118 		int mode;
11119 
11120 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11121 		if (mode == 0)
11122 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11123 		else if (mode == 1)
11124 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11125 		else
11126 			sbuf_printf(sb, "unknown mode %d", mode);
11127 	}
11128 	rc = sbuf_finish(sb);
11129 	sbuf_delete(sb);
11130 
11131 	return (rc);
11132 }
11133 
11134 static int
11135 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11136 {
11137 	struct adapter *sc = arg1;
11138 	enum cpu_sets op = arg2;
11139 	cpuset_t cpuset;
11140 	struct sbuf *sb;
11141 	int i, rc;
11142 
11143 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11144 
11145 	CPU_ZERO(&cpuset);
11146 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11147 	if (rc != 0)
11148 		return (rc);
11149 
11150 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11151 	if (sb == NULL)
11152 		return (ENOMEM);
11153 
11154 	CPU_FOREACH(i)
11155 		sbuf_printf(sb, "%d ", i);
11156 	rc = sbuf_finish(sb);
11157 	sbuf_delete(sb);
11158 
11159 	return (rc);
11160 }
11161 
11162 static int
11163 sysctl_reset(SYSCTL_HANDLER_ARGS)
11164 {
11165 	struct adapter *sc = arg1;
11166 	u_int val;
11167 	int rc;
11168 
11169 	val = atomic_load_int(&sc->num_resets);
11170 	rc = sysctl_handle_int(oidp, &val, 0, req);
11171 	if (rc != 0 || req->newptr == NULL)
11172 		return (rc);
11173 
11174 	if (val == 0) {
11175 		/* Zero out the counter that tracks reset. */
11176 		atomic_store_int(&sc->num_resets, 0);
11177 		return (0);
11178 	}
11179 
11180 	if (val != 1)
11181 		return (EINVAL);	/* 0 or 1 are the only legal values */
11182 
11183 	if (hw_off_limits(sc))		/* harmless race */
11184 		return (EALREADY);
11185 
11186 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11187 	return (0);
11188 }
11189 
11190 #ifdef TCP_OFFLOAD
11191 static int
11192 sysctl_tls(SYSCTL_HANDLER_ARGS)
11193 {
11194 	struct adapter *sc = arg1;
11195 	int i, j, v, rc;
11196 	struct vi_info *vi;
11197 
11198 	v = sc->tt.tls;
11199 	rc = sysctl_handle_int(oidp, &v, 0, req);
11200 	if (rc != 0 || req->newptr == NULL)
11201 		return (rc);
11202 
11203 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11204 		return (ENOTSUP);
11205 
11206 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11207 	if (rc)
11208 		return (rc);
11209 	if (hw_off_limits(sc))
11210 		rc = ENXIO;
11211 	else {
11212 		sc->tt.tls = !!v;
11213 		for_each_port(sc, i) {
11214 			for_each_vi(sc->port[i], j, vi) {
11215 				if (vi->flags & VI_INIT_DONE)
11216 					t4_update_fl_bufsize(vi->ifp);
11217 			}
11218 		}
11219 	}
11220 	end_synchronized_op(sc, 0);
11221 
11222 	return (rc);
11223 
11224 }
11225 
11226 static void
11227 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11228 {
11229 	u_int rem = val % factor;
11230 
11231 	if (rem == 0)
11232 		snprintf(buf, len, "%u", val / factor);
11233 	else {
11234 		while (rem % 10 == 0)
11235 			rem /= 10;
11236 		snprintf(buf, len, "%u.%u", val / factor, rem);
11237 	}
11238 }
11239 
11240 static int
11241 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11242 {
11243 	struct adapter *sc = arg1;
11244 	char buf[16];
11245 	u_int res, re;
11246 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11247 
11248 	mtx_lock(&sc->reg_lock);
11249 	if (hw_off_limits(sc))
11250 		res = (u_int)-1;
11251 	else
11252 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11253 	mtx_unlock(&sc->reg_lock);
11254 	if (res == (u_int)-1)
11255 		return (ENXIO);
11256 
11257 	switch (arg2) {
11258 	case 0:
11259 		/* timer_tick */
11260 		re = G_TIMERRESOLUTION(res);
11261 		break;
11262 	case 1:
11263 		/* TCP timestamp tick */
11264 		re = G_TIMESTAMPRESOLUTION(res);
11265 		break;
11266 	case 2:
11267 		/* DACK tick */
11268 		re = G_DELAYEDACKRESOLUTION(res);
11269 		break;
11270 	default:
11271 		return (EDOOFUS);
11272 	}
11273 
11274 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11275 
11276 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11277 }
11278 
11279 static int
11280 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11281 {
11282 	struct adapter *sc = arg1;
11283 	int rc;
11284 	u_int dack_tmr, dack_re, v;
11285 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11286 
11287 	mtx_lock(&sc->reg_lock);
11288 	if (hw_off_limits(sc))
11289 		rc = ENXIO;
11290 	else {
11291 		rc = 0;
11292 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11293 		    A_TP_TIMER_RESOLUTION));
11294 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11295 	}
11296 	mtx_unlock(&sc->reg_lock);
11297 	if (rc != 0)
11298 		return (rc);
11299 
11300 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11301 
11302 	return (sysctl_handle_int(oidp, &v, 0, req));
11303 }
11304 
11305 static int
11306 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11307 {
11308 	struct adapter *sc = arg1;
11309 	int rc, reg = arg2;
11310 	u_int tre;
11311 	u_long tp_tick_us, v;
11312 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11313 
11314 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11315 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11316 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11317 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11318 
11319 	mtx_lock(&sc->reg_lock);
11320 	if (hw_off_limits(sc))
11321 		rc = ENXIO;
11322 	else {
11323 		rc = 0;
11324 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11325 		tp_tick_us = (cclk_ps << tre) / 1000000;
11326 		if (reg == A_TP_INIT_SRTT)
11327 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11328 		else
11329 			v = tp_tick_us * t4_read_reg(sc, reg);
11330 	}
11331 	mtx_unlock(&sc->reg_lock);
11332 	if (rc != 0)
11333 		return (rc);
11334 	else
11335 		return (sysctl_handle_long(oidp, &v, 0, req));
11336 }
11337 
11338 /*
11339  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11340  * passed to this function.
11341  */
11342 static int
11343 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11344 {
11345 	struct adapter *sc = arg1;
11346 	int rc, idx = arg2;
11347 	u_int v;
11348 
11349 	MPASS(idx >= 0 && idx <= 24);
11350 
11351 	mtx_lock(&sc->reg_lock);
11352 	if (hw_off_limits(sc))
11353 		rc = ENXIO;
11354 	else {
11355 		rc = 0;
11356 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11357 	}
11358 	mtx_unlock(&sc->reg_lock);
11359 	if (rc != 0)
11360 		return (rc);
11361 	else
11362 		return (sysctl_handle_int(oidp, &v, 0, req));
11363 }
11364 
11365 static int
11366 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11367 {
11368 	struct adapter *sc = arg1;
11369 	int rc, idx = arg2;
11370 	u_int shift, v, r;
11371 
11372 	MPASS(idx >= 0 && idx < 16);
11373 
11374 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11375 	shift = (idx & 3) << 3;
11376 	mtx_lock(&sc->reg_lock);
11377 	if (hw_off_limits(sc))
11378 		rc = ENXIO;
11379 	else {
11380 		rc = 0;
11381 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11382 	}
11383 	mtx_unlock(&sc->reg_lock);
11384 	if (rc != 0)
11385 		return (rc);
11386 	else
11387 		return (sysctl_handle_int(oidp, &v, 0, req));
11388 }
11389 
11390 static int
11391 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11392 {
11393 	struct vi_info *vi = arg1;
11394 	struct adapter *sc = vi->adapter;
11395 	int idx, rc, i;
11396 	struct sge_ofld_rxq *ofld_rxq;
11397 	uint8_t v;
11398 
11399 	idx = vi->ofld_tmr_idx;
11400 
11401 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11402 	if (rc != 0 || req->newptr == NULL)
11403 		return (rc);
11404 
11405 	if (idx < 0 || idx >= SGE_NTIMERS)
11406 		return (EINVAL);
11407 
11408 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11409 	    "t4otmr");
11410 	if (rc)
11411 		return (rc);
11412 
11413 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11414 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11415 #ifdef atomic_store_rel_8
11416 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11417 #else
11418 		ofld_rxq->iq.intr_params = v;
11419 #endif
11420 	}
11421 	vi->ofld_tmr_idx = idx;
11422 
11423 	end_synchronized_op(sc, LOCK_HELD);
11424 	return (0);
11425 }
11426 
11427 static int
11428 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11429 {
11430 	struct vi_info *vi = arg1;
11431 	struct adapter *sc = vi->adapter;
11432 	int idx, rc;
11433 
11434 	idx = vi->ofld_pktc_idx;
11435 
11436 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11437 	if (rc != 0 || req->newptr == NULL)
11438 		return (rc);
11439 
11440 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11441 		return (EINVAL);
11442 
11443 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11444 	    "t4opktc");
11445 	if (rc)
11446 		return (rc);
11447 
11448 	if (vi->flags & VI_INIT_DONE)
11449 		rc = EBUSY; /* cannot be changed once the queues are created */
11450 	else
11451 		vi->ofld_pktc_idx = idx;
11452 
11453 	end_synchronized_op(sc, LOCK_HELD);
11454 	return (rc);
11455 }
11456 #endif
11457 
11458 static int
11459 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11460 {
11461 	int rc;
11462 
11463 	if (cntxt->cid > M_CTXTQID)
11464 		return (EINVAL);
11465 
11466 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11467 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11468 		return (EINVAL);
11469 
11470 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11471 	if (rc)
11472 		return (rc);
11473 
11474 	if (hw_off_limits(sc)) {
11475 		rc = ENXIO;
11476 		goto done;
11477 	}
11478 
11479 	if (sc->flags & FW_OK) {
11480 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11481 		    &cntxt->data[0]);
11482 		if (rc == 0)
11483 			goto done;
11484 	}
11485 
11486 	/*
11487 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11488 	 * the backdoor.
11489 	 */
11490 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11491 done:
11492 	end_synchronized_op(sc, 0);
11493 	return (rc);
11494 }
11495 
11496 static int
11497 load_fw(struct adapter *sc, struct t4_data *fw)
11498 {
11499 	int rc;
11500 	uint8_t *fw_data;
11501 
11502 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11503 	if (rc)
11504 		return (rc);
11505 
11506 	if (hw_off_limits(sc)) {
11507 		rc = ENXIO;
11508 		goto done;
11509 	}
11510 
11511 	/*
11512 	 * The firmware, with the sole exception of the memory parity error
11513 	 * handler, runs from memory and not flash.  It is almost always safe to
11514 	 * install a new firmware on a running system.  Just set bit 1 in
11515 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11516 	 */
11517 	if (sc->flags & FULL_INIT_DONE &&
11518 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11519 		rc = EBUSY;
11520 		goto done;
11521 	}
11522 
11523 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11524 
11525 	rc = copyin(fw->data, fw_data, fw->len);
11526 	if (rc == 0)
11527 		rc = -t4_load_fw(sc, fw_data, fw->len);
11528 
11529 	free(fw_data, M_CXGBE);
11530 done:
11531 	end_synchronized_op(sc, 0);
11532 	return (rc);
11533 }
11534 
11535 static int
11536 load_cfg(struct adapter *sc, struct t4_data *cfg)
11537 {
11538 	int rc;
11539 	uint8_t *cfg_data = NULL;
11540 
11541 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11542 	if (rc)
11543 		return (rc);
11544 
11545 	if (hw_off_limits(sc)) {
11546 		rc = ENXIO;
11547 		goto done;
11548 	}
11549 
11550 	if (cfg->len == 0) {
11551 		/* clear */
11552 		rc = -t4_load_cfg(sc, NULL, 0);
11553 		goto done;
11554 	}
11555 
11556 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11557 
11558 	rc = copyin(cfg->data, cfg_data, cfg->len);
11559 	if (rc == 0)
11560 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11561 
11562 	free(cfg_data, M_CXGBE);
11563 done:
11564 	end_synchronized_op(sc, 0);
11565 	return (rc);
11566 }
11567 
11568 static int
11569 load_boot(struct adapter *sc, struct t4_bootrom *br)
11570 {
11571 	int rc;
11572 	uint8_t *br_data = NULL;
11573 	u_int offset;
11574 
11575 	if (br->len > 1024 * 1024)
11576 		return (EFBIG);
11577 
11578 	if (br->pf_offset == 0) {
11579 		/* pfidx */
11580 		if (br->pfidx_addr > 7)
11581 			return (EINVAL);
11582 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11583 		    A_PCIE_PF_EXPROM_OFST)));
11584 	} else if (br->pf_offset == 1) {
11585 		/* offset */
11586 		offset = G_OFFSET(br->pfidx_addr);
11587 	} else {
11588 		return (EINVAL);
11589 	}
11590 
11591 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11592 	if (rc)
11593 		return (rc);
11594 
11595 	if (hw_off_limits(sc)) {
11596 		rc = ENXIO;
11597 		goto done;
11598 	}
11599 
11600 	if (br->len == 0) {
11601 		/* clear */
11602 		rc = -t4_load_boot(sc, NULL, offset, 0);
11603 		goto done;
11604 	}
11605 
11606 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11607 
11608 	rc = copyin(br->data, br_data, br->len);
11609 	if (rc == 0)
11610 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11611 
11612 	free(br_data, M_CXGBE);
11613 done:
11614 	end_synchronized_op(sc, 0);
11615 	return (rc);
11616 }
11617 
11618 static int
11619 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11620 {
11621 	int rc;
11622 	uint8_t *bc_data = NULL;
11623 
11624 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11625 	if (rc)
11626 		return (rc);
11627 
11628 	if (hw_off_limits(sc)) {
11629 		rc = ENXIO;
11630 		goto done;
11631 	}
11632 
11633 	if (bc->len == 0) {
11634 		/* clear */
11635 		rc = -t4_load_bootcfg(sc, NULL, 0);
11636 		goto done;
11637 	}
11638 
11639 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11640 
11641 	rc = copyin(bc->data, bc_data, bc->len);
11642 	if (rc == 0)
11643 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11644 
11645 	free(bc_data, M_CXGBE);
11646 done:
11647 	end_synchronized_op(sc, 0);
11648 	return (rc);
11649 }
11650 
11651 static int
11652 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11653 {
11654 	int rc;
11655 	struct cudbg_init *cudbg;
11656 	void *handle, *buf;
11657 
11658 	/* buf is large, don't block if no memory is available */
11659 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11660 	if (buf == NULL)
11661 		return (ENOMEM);
11662 
11663 	handle = cudbg_alloc_handle();
11664 	if (handle == NULL) {
11665 		rc = ENOMEM;
11666 		goto done;
11667 	}
11668 
11669 	cudbg = cudbg_get_init(handle);
11670 	cudbg->adap = sc;
11671 	cudbg->print = (cudbg_print_cb)printf;
11672 
11673 #ifndef notyet
11674 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11675 	    __func__, dump->wr_flash, dump->len, dump->data);
11676 #endif
11677 
11678 	if (dump->wr_flash)
11679 		cudbg->use_flash = 1;
11680 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11681 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11682 
11683 	rc = cudbg_collect(handle, buf, &dump->len);
11684 	if (rc != 0)
11685 		goto done;
11686 
11687 	rc = copyout(buf, dump->data, dump->len);
11688 done:
11689 	cudbg_free_handle(handle);
11690 	free(buf, M_CXGBE);
11691 	return (rc);
11692 }
11693 
11694 static void
11695 free_offload_policy(struct t4_offload_policy *op)
11696 {
11697 	struct offload_rule *r;
11698 	int i;
11699 
11700 	if (op == NULL)
11701 		return;
11702 
11703 	r = &op->rule[0];
11704 	for (i = 0; i < op->nrules; i++, r++) {
11705 		free(r->bpf_prog.bf_insns, M_CXGBE);
11706 	}
11707 	free(op->rule, M_CXGBE);
11708 	free(op, M_CXGBE);
11709 }
11710 
11711 static int
11712 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11713 {
11714 	int i, rc, len;
11715 	struct t4_offload_policy *op, *old;
11716 	struct bpf_program *bf;
11717 	const struct offload_settings *s;
11718 	struct offload_rule *r;
11719 	void *u;
11720 
11721 	if (!is_offload(sc))
11722 		return (ENODEV);
11723 
11724 	if (uop->nrules == 0) {
11725 		/* Delete installed policies. */
11726 		op = NULL;
11727 		goto set_policy;
11728 	} else if (uop->nrules > 256) { /* arbitrary */
11729 		return (E2BIG);
11730 	}
11731 
11732 	/* Copy userspace offload policy to kernel */
11733 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11734 	op->nrules = uop->nrules;
11735 	len = op->nrules * sizeof(struct offload_rule);
11736 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11737 	rc = copyin(uop->rule, op->rule, len);
11738 	if (rc) {
11739 		free(op->rule, M_CXGBE);
11740 		free(op, M_CXGBE);
11741 		return (rc);
11742 	}
11743 
11744 	r = &op->rule[0];
11745 	for (i = 0; i < op->nrules; i++, r++) {
11746 
11747 		/* Validate open_type */
11748 		if (r->open_type != OPEN_TYPE_LISTEN &&
11749 		    r->open_type != OPEN_TYPE_ACTIVE &&
11750 		    r->open_type != OPEN_TYPE_PASSIVE &&
11751 		    r->open_type != OPEN_TYPE_DONTCARE) {
11752 error:
11753 			/*
11754 			 * Rules 0 to i have malloc'd filters that need to be
11755 			 * freed.  Rules i+1 to nrules have userspace pointers
11756 			 * and should be left alone.
11757 			 */
11758 			op->nrules = i;
11759 			free_offload_policy(op);
11760 			return (rc);
11761 		}
11762 
11763 		/* Validate settings */
11764 		s = &r->settings;
11765 		if ((s->offload != 0 && s->offload != 1) ||
11766 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11767 		    s->sched_class < -1 ||
11768 		    s->sched_class >= sc->params.nsched_cls) {
11769 			rc = EINVAL;
11770 			goto error;
11771 		}
11772 
11773 		bf = &r->bpf_prog;
11774 		u = bf->bf_insns;	/* userspace ptr */
11775 		bf->bf_insns = NULL;
11776 		if (bf->bf_len == 0) {
11777 			/* legal, matches everything */
11778 			continue;
11779 		}
11780 		len = bf->bf_len * sizeof(*bf->bf_insns);
11781 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11782 		rc = copyin(u, bf->bf_insns, len);
11783 		if (rc != 0)
11784 			goto error;
11785 
11786 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11787 			rc = EINVAL;
11788 			goto error;
11789 		}
11790 	}
11791 set_policy:
11792 	rw_wlock(&sc->policy_lock);
11793 	old = sc->policy;
11794 	sc->policy = op;
11795 	rw_wunlock(&sc->policy_lock);
11796 	free_offload_policy(old);
11797 
11798 	return (0);
11799 }
11800 
11801 #define MAX_READ_BUF_SIZE (128 * 1024)
11802 static int
11803 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11804 {
11805 	uint32_t addr, remaining, n;
11806 	uint32_t *buf;
11807 	int rc;
11808 	uint8_t *dst;
11809 
11810 	mtx_lock(&sc->reg_lock);
11811 	if (hw_off_limits(sc))
11812 		rc = ENXIO;
11813 	else
11814 		rc = validate_mem_range(sc, mr->addr, mr->len);
11815 	mtx_unlock(&sc->reg_lock);
11816 	if (rc != 0)
11817 		return (rc);
11818 
11819 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11820 	addr = mr->addr;
11821 	remaining = mr->len;
11822 	dst = (void *)mr->data;
11823 
11824 	while (remaining) {
11825 		n = min(remaining, MAX_READ_BUF_SIZE);
11826 		mtx_lock(&sc->reg_lock);
11827 		if (hw_off_limits(sc))
11828 			rc = ENXIO;
11829 		else
11830 			read_via_memwin(sc, 2, addr, buf, n);
11831 		mtx_unlock(&sc->reg_lock);
11832 		if (rc != 0)
11833 			break;
11834 
11835 		rc = copyout(buf, dst, n);
11836 		if (rc != 0)
11837 			break;
11838 
11839 		dst += n;
11840 		remaining -= n;
11841 		addr += n;
11842 	}
11843 
11844 	free(buf, M_CXGBE);
11845 	return (rc);
11846 }
11847 #undef MAX_READ_BUF_SIZE
11848 
11849 static int
11850 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11851 {
11852 	int rc;
11853 
11854 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11855 		return (EINVAL);
11856 
11857 	if (i2cd->len > sizeof(i2cd->data))
11858 		return (EFBIG);
11859 
11860 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11861 	if (rc)
11862 		return (rc);
11863 	if (hw_off_limits(sc))
11864 		rc = ENXIO;
11865 	else
11866 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11867 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11868 	end_synchronized_op(sc, 0);
11869 
11870 	return (rc);
11871 }
11872 
11873 static int
11874 clear_stats(struct adapter *sc, u_int port_id)
11875 {
11876 	int i, v, chan_map;
11877 	struct port_info *pi;
11878 	struct vi_info *vi;
11879 	struct sge_rxq *rxq;
11880 	struct sge_txq *txq;
11881 	struct sge_wrq *wrq;
11882 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11883 	struct sge_ofld_txq *ofld_txq;
11884 #endif
11885 #ifdef TCP_OFFLOAD
11886 	struct sge_ofld_rxq *ofld_rxq;
11887 #endif
11888 
11889 	if (port_id >= sc->params.nports)
11890 		return (EINVAL);
11891 	pi = sc->port[port_id];
11892 	if (pi == NULL)
11893 		return (EIO);
11894 
11895 	mtx_lock(&sc->reg_lock);
11896 	if (!hw_off_limits(sc)) {
11897 		/* MAC stats */
11898 		t4_clr_port_stats(sc, pi->tx_chan);
11899 		if (is_t6(sc)) {
11900 			if (pi->fcs_reg != -1)
11901 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11902 			else
11903 				pi->stats.rx_fcs_err = 0;
11904 		}
11905 		for_each_vi(pi, v, vi) {
11906 			if (vi->flags & VI_INIT_DONE)
11907 				t4_clr_vi_stats(sc, vi->vin);
11908 		}
11909 		chan_map = pi->rx_e_chan_map;
11910 		v = 0;	/* reuse */
11911 		while (chan_map) {
11912 			i = ffs(chan_map) - 1;
11913 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11914 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11915 			chan_map &= ~(1 << i);
11916 		}
11917 	}
11918 	mtx_unlock(&sc->reg_lock);
11919 	pi->tx_parse_error = 0;
11920 	pi->tnl_cong_drops = 0;
11921 
11922 	/*
11923 	 * Since this command accepts a port, clear stats for
11924 	 * all VIs on this port.
11925 	 */
11926 	for_each_vi(pi, v, vi) {
11927 		if (vi->flags & VI_INIT_DONE) {
11928 
11929 			for_each_rxq(vi, i, rxq) {
11930 #if defined(INET) || defined(INET6)
11931 				rxq->lro.lro_queued = 0;
11932 				rxq->lro.lro_flushed = 0;
11933 #endif
11934 				rxq->rxcsum = 0;
11935 				rxq->vlan_extraction = 0;
11936 				rxq->vxlan_rxcsum = 0;
11937 
11938 				rxq->fl.cl_allocated = 0;
11939 				rxq->fl.cl_recycled = 0;
11940 				rxq->fl.cl_fast_recycled = 0;
11941 			}
11942 
11943 			for_each_txq(vi, i, txq) {
11944 				txq->txcsum = 0;
11945 				txq->tso_wrs = 0;
11946 				txq->vlan_insertion = 0;
11947 				txq->imm_wrs = 0;
11948 				txq->sgl_wrs = 0;
11949 				txq->txpkt_wrs = 0;
11950 				txq->txpkts0_wrs = 0;
11951 				txq->txpkts1_wrs = 0;
11952 				txq->txpkts0_pkts = 0;
11953 				txq->txpkts1_pkts = 0;
11954 				txq->txpkts_flush = 0;
11955 				txq->raw_wrs = 0;
11956 				txq->vxlan_tso_wrs = 0;
11957 				txq->vxlan_txcsum = 0;
11958 				txq->kern_tls_records = 0;
11959 				txq->kern_tls_short = 0;
11960 				txq->kern_tls_partial = 0;
11961 				txq->kern_tls_full = 0;
11962 				txq->kern_tls_octets = 0;
11963 				txq->kern_tls_waste = 0;
11964 				txq->kern_tls_options = 0;
11965 				txq->kern_tls_header = 0;
11966 				txq->kern_tls_fin = 0;
11967 				txq->kern_tls_fin_short = 0;
11968 				txq->kern_tls_cbc = 0;
11969 				txq->kern_tls_gcm = 0;
11970 				mp_ring_reset_stats(txq->r);
11971 			}
11972 
11973 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11974 			for_each_ofld_txq(vi, i, ofld_txq) {
11975 				ofld_txq->wrq.tx_wrs_direct = 0;
11976 				ofld_txq->wrq.tx_wrs_copied = 0;
11977 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
11978 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
11979 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
11980 				counter_u64_zero(ofld_txq->tx_aio_jobs);
11981 				counter_u64_zero(ofld_txq->tx_aio_octets);
11982 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
11983 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
11984 			}
11985 #endif
11986 #ifdef TCP_OFFLOAD
11987 			for_each_ofld_rxq(vi, i, ofld_rxq) {
11988 				ofld_rxq->fl.cl_allocated = 0;
11989 				ofld_rxq->fl.cl_recycled = 0;
11990 				ofld_rxq->fl.cl_fast_recycled = 0;
11991 				counter_u64_zero(
11992 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
11993 				counter_u64_zero(
11994 				    ofld_rxq->rx_iscsi_ddp_setup_error);
11995 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
11996 				ofld_rxq->rx_iscsi_ddp_octets = 0;
11997 				ofld_rxq->rx_iscsi_fl_pdus = 0;
11998 				ofld_rxq->rx_iscsi_fl_octets = 0;
11999 				ofld_rxq->rx_aio_ddp_jobs = 0;
12000 				ofld_rxq->rx_aio_ddp_octets = 0;
12001 				ofld_rxq->rx_toe_tls_records = 0;
12002 				ofld_rxq->rx_toe_tls_octets = 0;
12003 				ofld_rxq->rx_toe_ddp_octets = 0;
12004 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12005 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12006 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12007 			}
12008 #endif
12009 
12010 			if (IS_MAIN_VI(vi)) {
12011 				wrq = &sc->sge.ctrlq[pi->port_id];
12012 				wrq->tx_wrs_direct = 0;
12013 				wrq->tx_wrs_copied = 0;
12014 			}
12015 		}
12016 	}
12017 
12018 	return (0);
12019 }
12020 
12021 static int
12022 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12023 {
12024 #ifdef INET6
12025 	struct in6_addr in6;
12026 
12027 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12028 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12029 		return (0);
12030 	else
12031 		return (EIO);
12032 #else
12033 	return (ENOTSUP);
12034 #endif
12035 }
12036 
12037 static int
12038 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12039 {
12040 #ifdef INET6
12041 	struct in6_addr in6;
12042 
12043 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12044 	return (t4_release_clip_addr(sc, &in6));
12045 #else
12046 	return (ENOTSUP);
12047 #endif
12048 }
12049 
12050 int
12051 t4_os_find_pci_capability(struct adapter *sc, int cap)
12052 {
12053 	int i;
12054 
12055 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12056 }
12057 
12058 int
12059 t4_os_pci_save_state(struct adapter *sc)
12060 {
12061 	device_t dev;
12062 	struct pci_devinfo *dinfo;
12063 
12064 	dev = sc->dev;
12065 	dinfo = device_get_ivars(dev);
12066 
12067 	pci_cfg_save(dev, dinfo, 0);
12068 	return (0);
12069 }
12070 
12071 int
12072 t4_os_pci_restore_state(struct adapter *sc)
12073 {
12074 	device_t dev;
12075 	struct pci_devinfo *dinfo;
12076 
12077 	dev = sc->dev;
12078 	dinfo = device_get_ivars(dev);
12079 
12080 	pci_cfg_restore(dev, dinfo);
12081 	return (0);
12082 }
12083 
12084 void
12085 t4_os_portmod_changed(struct port_info *pi)
12086 {
12087 	struct adapter *sc = pi->adapter;
12088 	struct vi_info *vi;
12089 	if_t ifp;
12090 	static const char *mod_str[] = {
12091 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12092 	};
12093 
12094 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12095 	    ("%s: port_type %u", __func__, pi->port_type));
12096 
12097 	vi = &pi->vi[0];
12098 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12099 		PORT_LOCK(pi);
12100 		build_medialist(pi);
12101 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12102 			fixup_link_config(pi);
12103 			apply_link_config(pi);
12104 		}
12105 		PORT_UNLOCK(pi);
12106 		end_synchronized_op(sc, LOCK_HELD);
12107 	}
12108 
12109 	ifp = vi->ifp;
12110 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12111 		if_printf(ifp, "transceiver unplugged.\n");
12112 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12113 		if_printf(ifp, "unknown transceiver inserted.\n");
12114 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12115 		if_printf(ifp, "unsupported transceiver inserted.\n");
12116 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12117 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12118 		    port_top_speed(pi), mod_str[pi->mod_type]);
12119 	} else {
12120 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12121 		    pi->mod_type);
12122 	}
12123 }
12124 
12125 void
12126 t4_os_link_changed(struct port_info *pi)
12127 {
12128 	struct vi_info *vi;
12129 	if_t ifp;
12130 	struct link_config *lc = &pi->link_cfg;
12131 	struct adapter *sc = pi->adapter;
12132 	int v;
12133 
12134 	PORT_LOCK_ASSERT_OWNED(pi);
12135 
12136 	if (is_t6(sc)) {
12137 		if (lc->link_ok) {
12138 			if (lc->speed > 25000 ||
12139 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12140 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12141 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12142 			} else {
12143 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12144 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12145 			}
12146 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12147 			pi->stats.rx_fcs_err = 0;
12148 		} else {
12149 			pi->fcs_reg = -1;
12150 		}
12151 	} else {
12152 		MPASS(pi->fcs_reg != -1);
12153 		MPASS(pi->fcs_base == 0);
12154 	}
12155 
12156 	for_each_vi(pi, v, vi) {
12157 		ifp = vi->ifp;
12158 		if (ifp == NULL || IS_DETACHING(vi))
12159 			continue;
12160 
12161 		if (lc->link_ok) {
12162 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12163 			if_link_state_change(ifp, LINK_STATE_UP);
12164 		} else {
12165 			if_link_state_change(ifp, LINK_STATE_DOWN);
12166 		}
12167 	}
12168 }
12169 
12170 void
12171 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12172 {
12173 	struct adapter *sc;
12174 
12175 	sx_slock(&t4_list_lock);
12176 	SLIST_FOREACH(sc, &t4_list, link) {
12177 		/*
12178 		 * func should not make any assumptions about what state sc is
12179 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12180 		 */
12181 		func(sc, arg);
12182 	}
12183 	sx_sunlock(&t4_list_lock);
12184 }
12185 
12186 static int
12187 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12188     struct thread *td)
12189 {
12190 	int rc;
12191 	struct adapter *sc = dev->si_drv1;
12192 
12193 	rc = priv_check(td, PRIV_DRIVER);
12194 	if (rc != 0)
12195 		return (rc);
12196 
12197 	switch (cmd) {
12198 	case CHELSIO_T4_GETREG: {
12199 		struct t4_reg *edata = (struct t4_reg *)data;
12200 
12201 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12202 			return (EFAULT);
12203 
12204 		mtx_lock(&sc->reg_lock);
12205 		if (hw_off_limits(sc))
12206 			rc = ENXIO;
12207 		else if (edata->size == 4)
12208 			edata->val = t4_read_reg(sc, edata->addr);
12209 		else if (edata->size == 8)
12210 			edata->val = t4_read_reg64(sc, edata->addr);
12211 		else
12212 			rc = EINVAL;
12213 		mtx_unlock(&sc->reg_lock);
12214 
12215 		break;
12216 	}
12217 	case CHELSIO_T4_SETREG: {
12218 		struct t4_reg *edata = (struct t4_reg *)data;
12219 
12220 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12221 			return (EFAULT);
12222 
12223 		mtx_lock(&sc->reg_lock);
12224 		if (hw_off_limits(sc))
12225 			rc = ENXIO;
12226 		else if (edata->size == 4) {
12227 			if (edata->val & 0xffffffff00000000)
12228 				rc = EINVAL;
12229 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12230 		} else if (edata->size == 8)
12231 			t4_write_reg64(sc, edata->addr, edata->val);
12232 		else
12233 			rc = EINVAL;
12234 		mtx_unlock(&sc->reg_lock);
12235 
12236 		break;
12237 	}
12238 	case CHELSIO_T4_REGDUMP: {
12239 		struct t4_regdump *regs = (struct t4_regdump *)data;
12240 		int reglen = t4_get_regs_len(sc);
12241 		uint8_t *buf;
12242 
12243 		if (regs->len < reglen) {
12244 			regs->len = reglen; /* hint to the caller */
12245 			return (ENOBUFS);
12246 		}
12247 
12248 		regs->len = reglen;
12249 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12250 		mtx_lock(&sc->reg_lock);
12251 		if (hw_off_limits(sc))
12252 			rc = ENXIO;
12253 		else
12254 			get_regs(sc, regs, buf);
12255 		mtx_unlock(&sc->reg_lock);
12256 		if (rc == 0)
12257 			rc = copyout(buf, regs->data, reglen);
12258 		free(buf, M_CXGBE);
12259 		break;
12260 	}
12261 	case CHELSIO_T4_GET_FILTER_MODE:
12262 		rc = get_filter_mode(sc, (uint32_t *)data);
12263 		break;
12264 	case CHELSIO_T4_SET_FILTER_MODE:
12265 		rc = set_filter_mode(sc, *(uint32_t *)data);
12266 		break;
12267 	case CHELSIO_T4_SET_FILTER_MASK:
12268 		rc = set_filter_mask(sc, *(uint32_t *)data);
12269 		break;
12270 	case CHELSIO_T4_GET_FILTER:
12271 		rc = get_filter(sc, (struct t4_filter *)data);
12272 		break;
12273 	case CHELSIO_T4_SET_FILTER:
12274 		rc = set_filter(sc, (struct t4_filter *)data);
12275 		break;
12276 	case CHELSIO_T4_DEL_FILTER:
12277 		rc = del_filter(sc, (struct t4_filter *)data);
12278 		break;
12279 	case CHELSIO_T4_GET_SGE_CONTEXT:
12280 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12281 		break;
12282 	case CHELSIO_T4_LOAD_FW:
12283 		rc = load_fw(sc, (struct t4_data *)data);
12284 		break;
12285 	case CHELSIO_T4_GET_MEM:
12286 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12287 		break;
12288 	case CHELSIO_T4_GET_I2C:
12289 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12290 		break;
12291 	case CHELSIO_T4_CLEAR_STATS:
12292 		rc = clear_stats(sc, *(uint32_t *)data);
12293 		break;
12294 	case CHELSIO_T4_SCHED_CLASS:
12295 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12296 		break;
12297 	case CHELSIO_T4_SCHED_QUEUE:
12298 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12299 		break;
12300 	case CHELSIO_T4_GET_TRACER:
12301 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12302 		break;
12303 	case CHELSIO_T4_SET_TRACER:
12304 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12305 		break;
12306 	case CHELSIO_T4_LOAD_CFG:
12307 		rc = load_cfg(sc, (struct t4_data *)data);
12308 		break;
12309 	case CHELSIO_T4_LOAD_BOOT:
12310 		rc = load_boot(sc, (struct t4_bootrom *)data);
12311 		break;
12312 	case CHELSIO_T4_LOAD_BOOTCFG:
12313 		rc = load_bootcfg(sc, (struct t4_data *)data);
12314 		break;
12315 	case CHELSIO_T4_CUDBG_DUMP:
12316 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12317 		break;
12318 	case CHELSIO_T4_SET_OFLD_POLICY:
12319 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12320 		break;
12321 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12322 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12323 		break;
12324 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12325 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12326 		break;
12327 	default:
12328 		rc = ENOTTY;
12329 	}
12330 
12331 	return (rc);
12332 }
12333 
12334 #ifdef TCP_OFFLOAD
12335 static int
12336 toe_capability(struct vi_info *vi, bool enable)
12337 {
12338 	int rc;
12339 	struct port_info *pi = vi->pi;
12340 	struct adapter *sc = pi->adapter;
12341 
12342 	ASSERT_SYNCHRONIZED_OP(sc);
12343 
12344 	if (!is_offload(sc))
12345 		return (ENODEV);
12346 	if (hw_off_limits(sc))
12347 		return (ENXIO);
12348 
12349 	if (enable) {
12350 #ifdef KERN_TLS
12351 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12352 			int i, j, n;
12353 			struct port_info *p;
12354 			struct vi_info *v;
12355 
12356 			/*
12357 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12358 			 * on any ifnet.
12359 			 */
12360 			n = 0;
12361 			for_each_port(sc, i) {
12362 				p = sc->port[i];
12363 				for_each_vi(p, j, v) {
12364 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12365 						CH_WARN(sc,
12366 						    "%s has NIC TLS enabled.\n",
12367 						    device_get_nameunit(v->dev));
12368 						n++;
12369 					}
12370 				}
12371 			}
12372 			if (n > 0) {
12373 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12374 				    "associated with this adapter before "
12375 				    "trying to enable TOE.\n");
12376 				return (EAGAIN);
12377 			}
12378 			rc = t6_config_kern_tls(sc, false);
12379 			if (rc)
12380 				return (rc);
12381 		}
12382 #endif
12383 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12384 			/* TOE is already enabled. */
12385 			return (0);
12386 		}
12387 
12388 		/*
12389 		 * We need the port's queues around so that we're able to send
12390 		 * and receive CPLs to/from the TOE even if the ifnet for this
12391 		 * port has never been UP'd administratively.
12392 		 */
12393 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12394 			return (rc);
12395 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12396 		    ((rc = vi_init(&pi->vi[0])) != 0))
12397 			return (rc);
12398 
12399 		if (isset(&sc->offload_map, pi->port_id)) {
12400 			/* TOE is enabled on another VI of this port. */
12401 			pi->uld_vis++;
12402 			return (0);
12403 		}
12404 
12405 		if (!uld_active(sc, ULD_TOM)) {
12406 			rc = t4_activate_uld(sc, ULD_TOM);
12407 			if (rc == EAGAIN) {
12408 				log(LOG_WARNING,
12409 				    "You must kldload t4_tom.ko before trying "
12410 				    "to enable TOE on a cxgbe interface.\n");
12411 			}
12412 			if (rc != 0)
12413 				return (rc);
12414 			KASSERT(sc->tom_softc != NULL,
12415 			    ("%s: TOM activated but softc NULL", __func__));
12416 			KASSERT(uld_active(sc, ULD_TOM),
12417 			    ("%s: TOM activated but flag not set", __func__));
12418 		}
12419 
12420 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12421 		if (!uld_active(sc, ULD_IWARP))
12422 			(void) t4_activate_uld(sc, ULD_IWARP);
12423 		if (!uld_active(sc, ULD_ISCSI))
12424 			(void) t4_activate_uld(sc, ULD_ISCSI);
12425 
12426 		pi->uld_vis++;
12427 		setbit(&sc->offload_map, pi->port_id);
12428 	} else {
12429 		pi->uld_vis--;
12430 
12431 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12432 			return (0);
12433 
12434 		KASSERT(uld_active(sc, ULD_TOM),
12435 		    ("%s: TOM never initialized?", __func__));
12436 		clrbit(&sc->offload_map, pi->port_id);
12437 	}
12438 
12439 	return (0);
12440 }
12441 
12442 /*
12443  * Add an upper layer driver to the global list.
12444  */
12445 int
12446 t4_register_uld(struct uld_info *ui, int id)
12447 {
12448 	int rc;
12449 
12450 	if (id < 0 || id > ULD_MAX)
12451 		return (EINVAL);
12452 	sx_xlock(&t4_uld_list_lock);
12453 	if (t4_uld_list[id] != NULL)
12454 		rc = EEXIST;
12455 	else {
12456 		t4_uld_list[id] = ui;
12457 		rc = 0;
12458 	}
12459 	sx_xunlock(&t4_uld_list_lock);
12460 	return (rc);
12461 }
12462 
12463 int
12464 t4_unregister_uld(struct uld_info *ui, int id)
12465 {
12466 
12467 	if (id < 0 || id > ULD_MAX)
12468 		return (EINVAL);
12469 	sx_xlock(&t4_uld_list_lock);
12470 	MPASS(t4_uld_list[id] == ui);
12471 	t4_uld_list[id] = NULL;
12472 	sx_xunlock(&t4_uld_list_lock);
12473 	return (0);
12474 }
12475 
12476 int
12477 t4_activate_uld(struct adapter *sc, int id)
12478 {
12479 	int rc;
12480 
12481 	ASSERT_SYNCHRONIZED_OP(sc);
12482 
12483 	if (id < 0 || id > ULD_MAX)
12484 		return (EINVAL);
12485 
12486 	/* Adapter needs to be initialized before any ULD can be activated. */
12487 	if (!(sc->flags & FULL_INIT_DONE)) {
12488 		rc = adapter_init(sc);
12489 		if (rc != 0)
12490 			return (rc);
12491 	}
12492 
12493 	sx_slock(&t4_uld_list_lock);
12494 	if (t4_uld_list[id] == NULL)
12495 		rc = EAGAIN;	/* load the KLD with this ULD and try again. */
12496 	else {
12497 		rc = t4_uld_list[id]->uld_activate(sc);
12498 		if (rc == 0)
12499 			setbit(&sc->active_ulds, id);
12500 	}
12501 	sx_sunlock(&t4_uld_list_lock);
12502 
12503 	return (rc);
12504 }
12505 
12506 int
12507 t4_deactivate_uld(struct adapter *sc, int id)
12508 {
12509 	int rc;
12510 
12511 	ASSERT_SYNCHRONIZED_OP(sc);
12512 
12513 	if (id < 0 || id > ULD_MAX)
12514 		return (EINVAL);
12515 
12516 	sx_slock(&t4_uld_list_lock);
12517 	if (t4_uld_list[id] == NULL)
12518 		rc = ENXIO;
12519 	else {
12520 		rc = t4_uld_list[id]->uld_deactivate(sc);
12521 		if (rc == 0)
12522 			clrbit(&sc->active_ulds, id);
12523 	}
12524 	sx_sunlock(&t4_uld_list_lock);
12525 
12526 	return (rc);
12527 }
12528 
12529 static int
12530 deactivate_all_uld(struct adapter *sc)
12531 {
12532 	int i, rc;
12533 
12534 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12535 	if (rc != 0)
12536 		return (ENXIO);
12537 	sx_slock(&t4_uld_list_lock);
12538 	for (i = 0; i <= ULD_MAX; i++) {
12539 		if (t4_uld_list[i] == NULL || !uld_active(sc, i))
12540 			continue;
12541 		rc = t4_uld_list[i]->uld_deactivate(sc);
12542 		if (rc != 0)
12543 			break;
12544 		clrbit(&sc->active_ulds, i);
12545 	}
12546 	sx_sunlock(&t4_uld_list_lock);
12547 	end_synchronized_op(sc, 0);
12548 
12549 	return (rc);
12550 }
12551 
12552 static void
12553 stop_all_uld(struct adapter *sc)
12554 {
12555 	int i;
12556 
12557 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldst") != 0)
12558 		return;
12559 	sx_slock(&t4_uld_list_lock);
12560 	for (i = 0; i <= ULD_MAX; i++) {
12561 		if (t4_uld_list[i] == NULL || !uld_active(sc, i) ||
12562 		    t4_uld_list[i]->uld_stop == NULL)
12563 			continue;
12564 		(void) t4_uld_list[i]->uld_stop(sc);
12565 	}
12566 	sx_sunlock(&t4_uld_list_lock);
12567 	end_synchronized_op(sc, 0);
12568 }
12569 
12570 static void
12571 restart_all_uld(struct adapter *sc)
12572 {
12573 	int i;
12574 
12575 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4uldre") != 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_restart == NULL)
12581 			continue;
12582 		(void) t4_uld_list[i]->uld_restart(sc);
12583 	}
12584 	sx_sunlock(&t4_uld_list_lock);
12585 	end_synchronized_op(sc, 0);
12586 }
12587 
12588 int
12589 uld_active(struct adapter *sc, int id)
12590 {
12591 
12592 	MPASS(id >= 0 && id <= ULD_MAX);
12593 
12594 	return (isset(&sc->active_ulds, id));
12595 }
12596 #endif
12597 
12598 #ifdef KERN_TLS
12599 static int
12600 ktls_capability(struct adapter *sc, bool enable)
12601 {
12602 	ASSERT_SYNCHRONIZED_OP(sc);
12603 
12604 	if (!is_ktls(sc))
12605 		return (ENODEV);
12606 	if (!is_t6(sc))
12607 		return (0);
12608 	if (hw_off_limits(sc))
12609 		return (ENXIO);
12610 
12611 	if (enable) {
12612 		if (sc->flags & KERN_TLS_ON)
12613 			return (0);	/* already on */
12614 		if (sc->offload_map != 0) {
12615 			CH_WARN(sc,
12616 			    "Disable TOE on all interfaces associated with "
12617 			    "this adapter before trying to enable NIC TLS.\n");
12618 			return (EAGAIN);
12619 		}
12620 		return (t6_config_kern_tls(sc, true));
12621 	} else {
12622 		/*
12623 		 * Nothing to do for disable.  If TOE is enabled sometime later
12624 		 * then toe_capability will reconfigure the hardware.
12625 		 */
12626 		return (0);
12627 	}
12628 }
12629 #endif
12630 
12631 /*
12632  * t  = ptr to tunable.
12633  * nc = number of CPUs.
12634  * c  = compiled in default for that tunable.
12635  */
12636 static void
12637 calculate_nqueues(int *t, int nc, const int c)
12638 {
12639 	int nq;
12640 
12641 	if (*t > 0)
12642 		return;
12643 	nq = *t < 0 ? -*t : c;
12644 	*t = min(nc, nq);
12645 }
12646 
12647 /*
12648  * Come up with reasonable defaults for some of the tunables, provided they're
12649  * not set by the user (in which case we'll use the values as is).
12650  */
12651 static void
12652 tweak_tunables(void)
12653 {
12654 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12655 
12656 	if (t4_ntxq < 1) {
12657 #ifdef RSS
12658 		t4_ntxq = rss_getnumbuckets();
12659 #else
12660 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12661 #endif
12662 	}
12663 
12664 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12665 
12666 	if (t4_nrxq < 1) {
12667 #ifdef RSS
12668 		t4_nrxq = rss_getnumbuckets();
12669 #else
12670 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12671 #endif
12672 	}
12673 
12674 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12675 
12676 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12677 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12678 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12679 #endif
12680 #ifdef TCP_OFFLOAD
12681 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12682 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12683 #endif
12684 
12685 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12686 	if (t4_toecaps_allowed == -1)
12687 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12688 #else
12689 	if (t4_toecaps_allowed == -1)
12690 		t4_toecaps_allowed = 0;
12691 #endif
12692 
12693 #ifdef TCP_OFFLOAD
12694 	if (t4_rdmacaps_allowed == -1) {
12695 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12696 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12697 	}
12698 
12699 	if (t4_iscsicaps_allowed == -1) {
12700 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12701 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12702 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12703 	}
12704 
12705 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12706 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12707 
12708 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12709 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12710 #else
12711 	if (t4_rdmacaps_allowed == -1)
12712 		t4_rdmacaps_allowed = 0;
12713 
12714 	if (t4_iscsicaps_allowed == -1)
12715 		t4_iscsicaps_allowed = 0;
12716 #endif
12717 
12718 #ifdef DEV_NETMAP
12719 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12720 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12721 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12722 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12723 #endif
12724 
12725 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12726 		t4_tmr_idx = TMR_IDX;
12727 
12728 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12729 		t4_pktc_idx = PKTC_IDX;
12730 
12731 	if (t4_qsize_txq < 128)
12732 		t4_qsize_txq = 128;
12733 
12734 	if (t4_qsize_rxq < 128)
12735 		t4_qsize_rxq = 128;
12736 	while (t4_qsize_rxq & 7)
12737 		t4_qsize_rxq++;
12738 
12739 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12740 
12741 	/*
12742 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12743 	 * VI for the port.  The rest are additional virtual interfaces on the
12744 	 * same physical port.  Note that the main VI does not have native
12745 	 * netmap support but the extra VIs do.
12746 	 *
12747 	 * Limit the number of VIs per port to the number of available
12748 	 * MAC addresses per port.
12749 	 */
12750 	if (t4_num_vis < 1)
12751 		t4_num_vis = 1;
12752 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12753 		t4_num_vis = nitems(vi_mac_funcs);
12754 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12755 	}
12756 
12757 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12758 		pcie_relaxed_ordering = 1;
12759 #if defined(__i386__) || defined(__amd64__)
12760 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12761 			pcie_relaxed_ordering = 0;
12762 #endif
12763 	}
12764 }
12765 
12766 #ifdef DDB
12767 static void
12768 t4_dump_mem(struct adapter *sc, u_int addr, u_int len)
12769 {
12770 	uint32_t base, j, off, pf, reg, save, win_pos;
12771 
12772 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12773 	save = t4_read_reg(sc, reg);
12774 	base = sc->memwin[2].mw_base;
12775 
12776 	if (is_t4(sc)) {
12777 		pf = 0;
12778 		win_pos = addr & ~0xf;	/* start must be 16B aligned */
12779 	} else {
12780 		pf = V_PFNUM(sc->pf);
12781 		win_pos = addr & ~0x7f;	/* start must be 128B aligned */
12782 	}
12783 	off = addr - win_pos;
12784 	t4_write_reg(sc, reg, win_pos | pf);
12785 	t4_read_reg(sc, reg);
12786 
12787 	while (len > 0 && !db_pager_quit) {
12788 		uint32_t buf[8];
12789 		for (j = 0; j < 8; j++, off += 4)
12790 			buf[j] = htonl(t4_read_reg(sc, base + off));
12791 
12792 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12793 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12794 		    buf[7]);
12795 		if (len <= sizeof(buf))
12796 			len = 0;
12797 		else
12798 			len -= sizeof(buf);
12799 	}
12800 
12801 	t4_write_reg(sc, reg, save);
12802 	t4_read_reg(sc, reg);
12803 }
12804 
12805 static void
12806 t4_dump_tcb(struct adapter *sc, int tid)
12807 {
12808 	uint32_t tcb_addr;
12809 
12810 	/* Dump TCB for the tid */
12811 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12812 	tcb_addr += tid * TCB_SIZE;
12813 	t4_dump_mem(sc, tcb_addr, TCB_SIZE);
12814 }
12815 
12816 static void
12817 t4_dump_devlog(struct adapter *sc)
12818 {
12819 	struct devlog_params *dparams = &sc->params.devlog;
12820 	struct fw_devlog_e e;
12821 	int i, first, j, m, nentries, rc;
12822 	uint64_t ftstamp = UINT64_MAX;
12823 
12824 	if (dparams->start == 0) {
12825 		db_printf("devlog params not valid\n");
12826 		return;
12827 	}
12828 
12829 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12830 	m = fwmtype_to_hwmtype(dparams->memtype);
12831 
12832 	/* Find the first entry. */
12833 	first = -1;
12834 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12835 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12836 		    sizeof(e), (void *)&e);
12837 		if (rc != 0)
12838 			break;
12839 
12840 		if (e.timestamp == 0)
12841 			break;
12842 
12843 		e.timestamp = be64toh(e.timestamp);
12844 		if (e.timestamp < ftstamp) {
12845 			ftstamp = e.timestamp;
12846 			first = i;
12847 		}
12848 	}
12849 
12850 	if (first == -1)
12851 		return;
12852 
12853 	i = first;
12854 	do {
12855 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12856 		    sizeof(e), (void *)&e);
12857 		if (rc != 0)
12858 			return;
12859 
12860 		if (e.timestamp == 0)
12861 			return;
12862 
12863 		e.timestamp = be64toh(e.timestamp);
12864 		e.seqno = be32toh(e.seqno);
12865 		for (j = 0; j < 8; j++)
12866 			e.params[j] = be32toh(e.params[j]);
12867 
12868 		db_printf("%10d  %15ju  %8s  %8s  ",
12869 		    e.seqno, e.timestamp,
12870 		    (e.level < nitems(devlog_level_strings) ?
12871 			devlog_level_strings[e.level] : "UNKNOWN"),
12872 		    (e.facility < nitems(devlog_facility_strings) ?
12873 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12874 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12875 		    e.params[3], e.params[4], e.params[5], e.params[6],
12876 		    e.params[7]);
12877 
12878 		if (++i == nentries)
12879 			i = 0;
12880 	} while (i != first && !db_pager_quit);
12881 }
12882 
12883 static DB_DEFINE_TABLE(show, t4, show_t4);
12884 
12885 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12886 {
12887 	device_t dev;
12888 	int t;
12889 	bool valid;
12890 
12891 	valid = false;
12892 	t = db_read_token();
12893 	if (t == tIDENT) {
12894 		dev = device_lookup_by_name(db_tok_string);
12895 		valid = true;
12896 	}
12897 	db_skip_to_eol();
12898 	if (!valid) {
12899 		db_printf("usage: show t4 devlog <nexus>\n");
12900 		return;
12901 	}
12902 
12903 	if (dev == NULL) {
12904 		db_printf("device not found\n");
12905 		return;
12906 	}
12907 
12908 	t4_dump_devlog(device_get_softc(dev));
12909 }
12910 
12911 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12912 {
12913 	device_t dev;
12914 	int radix, tid, t;
12915 	bool valid;
12916 
12917 	valid = false;
12918 	radix = db_radix;
12919 	db_radix = 10;
12920 	t = db_read_token();
12921 	if (t == tIDENT) {
12922 		dev = device_lookup_by_name(db_tok_string);
12923 		t = db_read_token();
12924 		if (t == tNUMBER) {
12925 			tid = db_tok_number;
12926 			valid = true;
12927 		}
12928 	}
12929 	db_radix = radix;
12930 	db_skip_to_eol();
12931 	if (!valid) {
12932 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12933 		return;
12934 	}
12935 
12936 	if (dev == NULL) {
12937 		db_printf("device not found\n");
12938 		return;
12939 	}
12940 	if (tid < 0) {
12941 		db_printf("invalid tid\n");
12942 		return;
12943 	}
12944 
12945 	t4_dump_tcb(device_get_softc(dev), tid);
12946 }
12947 
12948 DB_TABLE_COMMAND_FLAGS(show_t4, memdump, db_show_memdump, CS_OWN)
12949 {
12950 	device_t dev;
12951 	int radix, t;
12952 	bool valid;
12953 
12954 	valid = false;
12955 	radix = db_radix;
12956 	db_radix = 10;
12957 	t = db_read_token();
12958 	if (t == tIDENT) {
12959 		dev = device_lookup_by_name(db_tok_string);
12960 		t = db_read_token();
12961 		if (t == tNUMBER) {
12962 			addr = db_tok_number;
12963 			t = db_read_token();
12964 			if (t == tNUMBER) {
12965 				count = db_tok_number;
12966 				valid = true;
12967 			}
12968 		}
12969 	}
12970 	db_radix = radix;
12971 	db_skip_to_eol();
12972 	if (!valid) {
12973 		db_printf("usage: show t4 memdump <nexus> <addr> <len>\n");
12974 		return;
12975 	}
12976 
12977 	if (dev == NULL) {
12978 		db_printf("device not found\n");
12979 		return;
12980 	}
12981 	if (addr < 0) {
12982 		db_printf("invalid address\n");
12983 		return;
12984 	}
12985 	if (count <= 0) {
12986 		db_printf("invalid length\n");
12987 		return;
12988 	}
12989 
12990 	t4_dump_mem(device_get_softc(dev), addr, count);
12991 }
12992 #endif
12993 
12994 static eventhandler_tag vxlan_start_evtag;
12995 static eventhandler_tag vxlan_stop_evtag;
12996 
12997 struct vxlan_evargs {
12998 	if_t ifp;
12999 	uint16_t port;
13000 };
13001 
13002 static void
13003 enable_vxlan_rx(struct adapter *sc)
13004 {
13005 	int i, rc;
13006 	struct port_info *pi;
13007 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13008 
13009 	ASSERT_SYNCHRONIZED_OP(sc);
13010 
13011 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13012 	    F_VXLAN_EN);
13013 	for_each_port(sc, i) {
13014 		pi = sc->port[i];
13015 		if (pi->vxlan_tcam_entry == true)
13016 			continue;
13017 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13018 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13019 		    true);
13020 		if (rc < 0) {
13021 			rc = -rc;
13022 			CH_ERR(&pi->vi[0],
13023 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13024 		} else {
13025 			MPASS(rc == sc->rawf_base + pi->port_id);
13026 			pi->vxlan_tcam_entry = true;
13027 		}
13028 	}
13029 }
13030 
13031 static void
13032 t4_vxlan_start(struct adapter *sc, void *arg)
13033 {
13034 	struct vxlan_evargs *v = arg;
13035 
13036 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13037 		return;
13038 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13039 		return;
13040 
13041 	if (sc->vxlan_refcount == 0) {
13042 		sc->vxlan_port = v->port;
13043 		sc->vxlan_refcount = 1;
13044 		if (!hw_off_limits(sc))
13045 			enable_vxlan_rx(sc);
13046 	} else if (sc->vxlan_port == v->port) {
13047 		sc->vxlan_refcount++;
13048 	} else {
13049 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13050 		    "ignoring attempt to configure it on port %d\n",
13051 		    sc->vxlan_port, v->port);
13052 	}
13053 	end_synchronized_op(sc, 0);
13054 }
13055 
13056 static void
13057 t4_vxlan_stop(struct adapter *sc, void *arg)
13058 {
13059 	struct vxlan_evargs *v = arg;
13060 
13061 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13062 		return;
13063 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13064 		return;
13065 
13066 	/*
13067 	 * VXLANs may have been configured before the driver was loaded so we
13068 	 * may see more stops than starts.  This is not handled cleanly but at
13069 	 * least we keep the refcount sane.
13070 	 */
13071 	if (sc->vxlan_port != v->port)
13072 		goto done;
13073 	if (sc->vxlan_refcount == 0) {
13074 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13075 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13076 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13077 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13078 done:
13079 	end_synchronized_op(sc, 0);
13080 }
13081 
13082 static void
13083 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13084     sa_family_t family, u_int port)
13085 {
13086 	struct vxlan_evargs v;
13087 
13088 	MPASS(family == AF_INET || family == AF_INET6);
13089 	v.ifp = ifp;
13090 	v.port = port;
13091 
13092 	t4_iterate(t4_vxlan_start, &v);
13093 }
13094 
13095 static void
13096 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13097     u_int port)
13098 {
13099 	struct vxlan_evargs v;
13100 
13101 	MPASS(family == AF_INET || family == AF_INET6);
13102 	v.ifp = ifp;
13103 	v.port = port;
13104 
13105 	t4_iterate(t4_vxlan_stop, &v);
13106 }
13107 
13108 
13109 static struct sx mlu;	/* mod load unload */
13110 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13111 
13112 static int
13113 mod_event(module_t mod, int cmd, void *arg)
13114 {
13115 	int rc = 0;
13116 	static int loaded = 0;
13117 
13118 	switch (cmd) {
13119 	case MOD_LOAD:
13120 		sx_xlock(&mlu);
13121 		if (loaded++ == 0) {
13122 			t4_sge_modload();
13123 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13124 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13125 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13126 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13127 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13128 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13129 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13130 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13131 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13132 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13133 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13134 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13135 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13136 			    do_smt_write_rpl);
13137 			sx_init(&t4_list_lock, "T4/T5 adapters");
13138 			SLIST_INIT(&t4_list);
13139 			callout_init(&fatal_callout, 1);
13140 #ifdef TCP_OFFLOAD
13141 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13142 #endif
13143 #ifdef INET6
13144 			t4_clip_modload();
13145 #endif
13146 #ifdef KERN_TLS
13147 			t6_ktls_modload();
13148 #endif
13149 			t4_tracer_modload();
13150 			tweak_tunables();
13151 			vxlan_start_evtag =
13152 			    EVENTHANDLER_REGISTER(vxlan_start,
13153 				t4_vxlan_start_handler, NULL,
13154 				EVENTHANDLER_PRI_ANY);
13155 			vxlan_stop_evtag =
13156 			    EVENTHANDLER_REGISTER(vxlan_stop,
13157 				t4_vxlan_stop_handler, NULL,
13158 				EVENTHANDLER_PRI_ANY);
13159 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13160 			    taskqueue_thread_enqueue, &reset_tq);
13161 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13162 			    "t4_rst_thr");
13163 		}
13164 		sx_xunlock(&mlu);
13165 		break;
13166 
13167 	case MOD_UNLOAD:
13168 		sx_xlock(&mlu);
13169 		if (--loaded == 0) {
13170 #ifdef TCP_OFFLOAD
13171 			int i;
13172 #endif
13173 			int tries;
13174 
13175 			taskqueue_free(reset_tq);
13176 
13177 			tries = 0;
13178 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13179 				uprintf("%ju clusters with custom free routine "
13180 				    "still is use.\n", t4_sge_extfree_refs());
13181 				pause("t4unload", 2 * hz);
13182 			}
13183 
13184 			sx_slock(&t4_list_lock);
13185 			if (!SLIST_EMPTY(&t4_list)) {
13186 				rc = EBUSY;
13187 				sx_sunlock(&t4_list_lock);
13188 				goto done_unload;
13189 			}
13190 #ifdef TCP_OFFLOAD
13191 			sx_slock(&t4_uld_list_lock);
13192 			for (i = 0; i <= ULD_MAX; i++) {
13193 				if (t4_uld_list[i] != NULL) {
13194 					rc = EBUSY;
13195 					sx_sunlock(&t4_uld_list_lock);
13196 					sx_sunlock(&t4_list_lock);
13197 					goto done_unload;
13198 				}
13199 			}
13200 			sx_sunlock(&t4_uld_list_lock);
13201 #endif
13202 			sx_sunlock(&t4_list_lock);
13203 
13204 			if (t4_sge_extfree_refs() == 0) {
13205 				EVENTHANDLER_DEREGISTER(vxlan_start,
13206 				    vxlan_start_evtag);
13207 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13208 				    vxlan_stop_evtag);
13209 				t4_tracer_modunload();
13210 #ifdef KERN_TLS
13211 				t6_ktls_modunload();
13212 #endif
13213 #ifdef INET6
13214 				t4_clip_modunload();
13215 #endif
13216 #ifdef TCP_OFFLOAD
13217 				sx_destroy(&t4_uld_list_lock);
13218 #endif
13219 				sx_destroy(&t4_list_lock);
13220 				t4_sge_modunload();
13221 				loaded = 0;
13222 			} else {
13223 				rc = EBUSY;
13224 				loaded++;	/* undo earlier decrement */
13225 			}
13226 		}
13227 done_unload:
13228 		sx_xunlock(&mlu);
13229 		break;
13230 	}
13231 
13232 	return (rc);
13233 }
13234 
13235 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13236 MODULE_VERSION(t4nex, 1);
13237 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13238 #ifdef DEV_NETMAP
13239 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13240 #endif /* DEV_NETMAP */
13241 
13242 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13243 MODULE_VERSION(t5nex, 1);
13244 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13245 #ifdef DEV_NETMAP
13246 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13247 #endif /* DEV_NETMAP */
13248 
13249 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13250 MODULE_VERSION(t6nex, 1);
13251 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13252 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13253 #ifdef DEV_NETMAP
13254 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13255 #endif /* DEV_NETMAP */
13256 
13257 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13258 MODULE_VERSION(cxgbe, 1);
13259 
13260 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13261 MODULE_VERSION(cxl, 1);
13262 
13263 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13264 MODULE_VERSION(cc, 1);
13265 
13266 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13267 MODULE_VERSION(vcxgbe, 1);
13268 
13269 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13270 MODULE_VERSION(vcxl, 1);
13271 
13272 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13273 MODULE_VERSION(vcc, 1);
13274