xref: /freebsd/sys/dev/cxgbe/t4_main.c (revision b1fd95c9e24791d44593e611406b41e57826a5b8)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2011 Chelsio Communications, Inc.
5  * All rights reserved.
6  * Written by: Navdeep Parhar <np@FreeBSD.org>
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 #include "opt_ddb.h"
32 #include "opt_inet.h"
33 #include "opt_inet6.h"
34 #include "opt_kern_tls.h"
35 #include "opt_ratelimit.h"
36 #include "opt_rss.h"
37 
38 #include <sys/param.h>
39 #include <sys/conf.h>
40 #include <sys/priv.h>
41 #include <sys/kernel.h>
42 #include <sys/bus.h>
43 #include <sys/eventhandler.h>
44 #include <sys/module.h>
45 #include <sys/malloc.h>
46 #include <sys/queue.h>
47 #include <sys/taskqueue.h>
48 #include <sys/pciio.h>
49 #include <dev/pci/pcireg.h>
50 #include <dev/pci/pcivar.h>
51 #include <dev/pci/pci_private.h>
52 #include <sys/firmware.h>
53 #include <sys/sbuf.h>
54 #include <sys/smp.h>
55 #include <sys/socket.h>
56 #include <sys/sockio.h>
57 #include <sys/sysctl.h>
58 #include <net/ethernet.h>
59 #include <net/if.h>
60 #include <net/if_types.h>
61 #include <net/if_dl.h>
62 #include <net/if_vlan_var.h>
63 #ifdef RSS
64 #include <net/rss_config.h>
65 #endif
66 #include <netinet/in.h>
67 #include <netinet/ip.h>
68 #ifdef KERN_TLS
69 #include <netinet/tcp_seq.h>
70 #endif
71 #if defined(__i386__) || defined(__amd64__)
72 #include <machine/md_var.h>
73 #include <machine/cputypes.h>
74 #include <vm/vm.h>
75 #include <vm/pmap.h>
76 #endif
77 #ifdef DDB
78 #include <ddb/ddb.h>
79 #include <ddb/db_lex.h>
80 #endif
81 
82 #include "common/common.h"
83 #include "common/t4_msg.h"
84 #include "common/t4_regs.h"
85 #include "common/t4_regs_values.h"
86 #include "cudbg/cudbg.h"
87 #include "t4_clip.h"
88 #include "t4_ioctl.h"
89 #include "t4_l2t.h"
90 #include "t4_mp_ring.h"
91 #include "t4_if.h"
92 #include "t4_smt.h"
93 
94 /* T4 bus driver interface */
95 static int t4_probe(device_t);
96 static int t4_attach(device_t);
97 static int t4_detach(device_t);
98 static int t4_child_location(device_t, device_t, struct sbuf *);
99 static int t4_ready(device_t);
100 static int t4_read_port_device(device_t, int, device_t *);
101 static int t4_suspend(device_t);
102 static int t4_resume(device_t);
103 static int t4_reset_prepare(device_t, device_t);
104 static int t4_reset_post(device_t, device_t);
105 static device_method_t t4_methods[] = {
106 	DEVMETHOD(device_probe,		t4_probe),
107 	DEVMETHOD(device_attach,	t4_attach),
108 	DEVMETHOD(device_detach,	t4_detach),
109 	DEVMETHOD(device_suspend,	t4_suspend),
110 	DEVMETHOD(device_resume,	t4_resume),
111 
112 	DEVMETHOD(bus_child_location,	t4_child_location),
113 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
114 	DEVMETHOD(bus_reset_post,	t4_reset_post),
115 
116 	DEVMETHOD(t4_is_main_ready,	t4_ready),
117 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
118 
119 	DEVMETHOD_END
120 };
121 static driver_t t4_driver = {
122 	"t4nex",
123 	t4_methods,
124 	sizeof(struct adapter)
125 };
126 
127 
128 /* T4 port (cxgbe) interface */
129 static int cxgbe_probe(device_t);
130 static int cxgbe_attach(device_t);
131 static int cxgbe_detach(device_t);
132 device_method_t cxgbe_methods[] = {
133 	DEVMETHOD(device_probe,		cxgbe_probe),
134 	DEVMETHOD(device_attach,	cxgbe_attach),
135 	DEVMETHOD(device_detach,	cxgbe_detach),
136 	{ 0, 0 }
137 };
138 static driver_t cxgbe_driver = {
139 	"cxgbe",
140 	cxgbe_methods,
141 	sizeof(struct port_info)
142 };
143 
144 /* T4 VI (vcxgbe) interface */
145 static int vcxgbe_probe(device_t);
146 static int vcxgbe_attach(device_t);
147 static int vcxgbe_detach(device_t);
148 static device_method_t vcxgbe_methods[] = {
149 	DEVMETHOD(device_probe,		vcxgbe_probe),
150 	DEVMETHOD(device_attach,	vcxgbe_attach),
151 	DEVMETHOD(device_detach,	vcxgbe_detach),
152 	{ 0, 0 }
153 };
154 static driver_t vcxgbe_driver = {
155 	"vcxgbe",
156 	vcxgbe_methods,
157 	sizeof(struct vi_info)
158 };
159 
160 static d_ioctl_t t4_ioctl;
161 
162 static struct cdevsw t4_cdevsw = {
163        .d_version = D_VERSION,
164        .d_ioctl = t4_ioctl,
165        .d_name = "t4nex",
166 };
167 
168 /* T5 bus driver interface */
169 static int t5_probe(device_t);
170 static device_method_t t5_methods[] = {
171 	DEVMETHOD(device_probe,		t5_probe),
172 	DEVMETHOD(device_attach,	t4_attach),
173 	DEVMETHOD(device_detach,	t4_detach),
174 	DEVMETHOD(device_suspend,	t4_suspend),
175 	DEVMETHOD(device_resume,	t4_resume),
176 
177 	DEVMETHOD(bus_child_location,	t4_child_location),
178 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
179 	DEVMETHOD(bus_reset_post,	t4_reset_post),
180 
181 	DEVMETHOD(t4_is_main_ready,	t4_ready),
182 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
183 
184 	DEVMETHOD_END
185 };
186 static driver_t t5_driver = {
187 	"t5nex",
188 	t5_methods,
189 	sizeof(struct adapter)
190 };
191 
192 
193 /* T5 port (cxl) interface */
194 static driver_t cxl_driver = {
195 	"cxl",
196 	cxgbe_methods,
197 	sizeof(struct port_info)
198 };
199 
200 /* T5 VI (vcxl) interface */
201 static driver_t vcxl_driver = {
202 	"vcxl",
203 	vcxgbe_methods,
204 	sizeof(struct vi_info)
205 };
206 
207 /* T6 bus driver interface */
208 static int t6_probe(device_t);
209 static device_method_t t6_methods[] = {
210 	DEVMETHOD(device_probe,		t6_probe),
211 	DEVMETHOD(device_attach,	t4_attach),
212 	DEVMETHOD(device_detach,	t4_detach),
213 	DEVMETHOD(device_suspend,	t4_suspend),
214 	DEVMETHOD(device_resume,	t4_resume),
215 
216 	DEVMETHOD(bus_child_location,	t4_child_location),
217 	DEVMETHOD(bus_reset_prepare,	t4_reset_prepare),
218 	DEVMETHOD(bus_reset_post,	t4_reset_post),
219 
220 	DEVMETHOD(t4_is_main_ready,	t4_ready),
221 	DEVMETHOD(t4_read_port_device,	t4_read_port_device),
222 
223 	DEVMETHOD_END
224 };
225 static driver_t t6_driver = {
226 	"t6nex",
227 	t6_methods,
228 	sizeof(struct adapter)
229 };
230 
231 
232 /* T6 port (cc) interface */
233 static driver_t cc_driver = {
234 	"cc",
235 	cxgbe_methods,
236 	sizeof(struct port_info)
237 };
238 
239 /* T6 VI (vcc) interface */
240 static driver_t vcc_driver = {
241 	"vcc",
242 	vcxgbe_methods,
243 	sizeof(struct vi_info)
244 };
245 
246 /* ifnet interface */
247 static void cxgbe_init(void *);
248 static int cxgbe_ioctl(if_t, unsigned long, caddr_t);
249 static int cxgbe_transmit(if_t, struct mbuf *);
250 static void cxgbe_qflush(if_t);
251 #if defined(KERN_TLS) || defined(RATELIMIT)
252 static int cxgbe_snd_tag_alloc(if_t, union if_snd_tag_alloc_params *,
253     struct m_snd_tag **);
254 #endif
255 
256 MALLOC_DEFINE(M_CXGBE, "cxgbe", "Chelsio T4/T5 Ethernet driver and services");
257 
258 /*
259  * Correct lock order when you need to acquire multiple locks is t4_list_lock,
260  * then ADAPTER_LOCK, then t4_uld_list_lock.
261  */
262 static struct sx t4_list_lock;
263 SLIST_HEAD(, adapter) t4_list;
264 #ifdef TCP_OFFLOAD
265 static struct sx t4_uld_list_lock;
266 SLIST_HEAD(, uld_info) t4_uld_list;
267 #endif
268 
269 /*
270  * Tunables.  See tweak_tunables() too.
271  *
272  * Each tunable is set to a default value here if it's known at compile-time.
273  * Otherwise it is set to -n as an indication to tweak_tunables() that it should
274  * provide a reasonable default (upto n) when the driver is loaded.
275  *
276  * Tunables applicable to both T4 and T5 are under hw.cxgbe.  Those specific to
277  * T5 are under hw.cxl.
278  */
279 SYSCTL_NODE(_hw, OID_AUTO, cxgbe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
280     "cxgbe(4) parameters");
281 SYSCTL_NODE(_hw, OID_AUTO, cxl, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
282     "cxgbe(4) T5+ parameters");
283 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, toe, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
284     "cxgbe(4) TOE parameters");
285 
286 /*
287  * Number of queues for tx and rx, NIC and offload.
288  */
289 #define NTXQ 16
290 int t4_ntxq = -NTXQ;
291 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq, CTLFLAG_RDTUN, &t4_ntxq, 0,
292     "Number of TX queues per port");
293 TUNABLE_INT("hw.cxgbe.ntxq10g", &t4_ntxq);	/* Old name, undocumented */
294 
295 #define NRXQ 8
296 int t4_nrxq = -NRXQ;
297 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq, CTLFLAG_RDTUN, &t4_nrxq, 0,
298     "Number of RX queues per port");
299 TUNABLE_INT("hw.cxgbe.nrxq10g", &t4_nrxq);	/* Old name, undocumented */
300 
301 #define NTXQ_VI 1
302 static int t4_ntxq_vi = -NTXQ_VI;
303 SYSCTL_INT(_hw_cxgbe, OID_AUTO, ntxq_vi, CTLFLAG_RDTUN, &t4_ntxq_vi, 0,
304     "Number of TX queues per VI");
305 
306 #define NRXQ_VI 1
307 static int t4_nrxq_vi = -NRXQ_VI;
308 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nrxq_vi, CTLFLAG_RDTUN, &t4_nrxq_vi, 0,
309     "Number of RX queues per VI");
310 
311 static int t4_rsrv_noflowq = 0;
312 SYSCTL_INT(_hw_cxgbe, OID_AUTO, rsrv_noflowq, CTLFLAG_RDTUN, &t4_rsrv_noflowq,
313     0, "Reserve TX queue 0 of each VI for non-flowid packets");
314 
315 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
316 #define NOFLDTXQ 8
317 static int t4_nofldtxq = -NOFLDTXQ;
318 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq, CTLFLAG_RDTUN, &t4_nofldtxq, 0,
319     "Number of offload TX queues per port");
320 
321 #define NOFLDRXQ 2
322 static int t4_nofldrxq = -NOFLDRXQ;
323 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq, CTLFLAG_RDTUN, &t4_nofldrxq, 0,
324     "Number of offload RX queues per port");
325 
326 #define NOFLDTXQ_VI 1
327 static int t4_nofldtxq_vi = -NOFLDTXQ_VI;
328 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldtxq_vi, CTLFLAG_RDTUN, &t4_nofldtxq_vi, 0,
329     "Number of offload TX queues per VI");
330 
331 #define NOFLDRXQ_VI 1
332 static int t4_nofldrxq_vi = -NOFLDRXQ_VI;
333 SYSCTL_INT(_hw_cxgbe, OID_AUTO, nofldrxq_vi, CTLFLAG_RDTUN, &t4_nofldrxq_vi, 0,
334     "Number of offload RX queues per VI");
335 
336 #define TMR_IDX_OFLD 1
337 int t4_tmr_idx_ofld = TMR_IDX_OFLD;
338 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_timer_idx_ofld, CTLFLAG_RDTUN,
339     &t4_tmr_idx_ofld, 0, "Holdoff timer index for offload queues");
340 
341 #define PKTC_IDX_OFLD (-1)
342 int t4_pktc_idx_ofld = PKTC_IDX_OFLD;
343 SYSCTL_INT(_hw_cxgbe, OID_AUTO, holdoff_pktc_idx_ofld, CTLFLAG_RDTUN,
344     &t4_pktc_idx_ofld, 0, "holdoff packet counter index for offload queues");
345 
346 /* 0 means chip/fw default, non-zero number is value in microseconds */
347 static u_long t4_toe_keepalive_idle = 0;
348 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_idle, CTLFLAG_RDTUN,
349     &t4_toe_keepalive_idle, 0, "TOE keepalive idle timer (us)");
350 
351 /* 0 means chip/fw default, non-zero number is value in microseconds */
352 static u_long t4_toe_keepalive_interval = 0;
353 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, keepalive_interval, CTLFLAG_RDTUN,
354     &t4_toe_keepalive_interval, 0, "TOE keepalive interval timer (us)");
355 
356 /* 0 means chip/fw default, non-zero number is # of keepalives before abort */
357 static int t4_toe_keepalive_count = 0;
358 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, keepalive_count, CTLFLAG_RDTUN,
359     &t4_toe_keepalive_count, 0, "Number of TOE keepalive probes before abort");
360 
361 /* 0 means chip/fw default, non-zero number is value in microseconds */
362 static u_long t4_toe_rexmt_min = 0;
363 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_min, CTLFLAG_RDTUN,
364     &t4_toe_rexmt_min, 0, "Minimum TOE retransmit interval (us)");
365 
366 /* 0 means chip/fw default, non-zero number is value in microseconds */
367 static u_long t4_toe_rexmt_max = 0;
368 SYSCTL_ULONG(_hw_cxgbe_toe, OID_AUTO, rexmt_max, CTLFLAG_RDTUN,
369     &t4_toe_rexmt_max, 0, "Maximum TOE retransmit interval (us)");
370 
371 /* 0 means chip/fw default, non-zero number is # of rexmt before abort */
372 static int t4_toe_rexmt_count = 0;
373 SYSCTL_INT(_hw_cxgbe_toe, OID_AUTO, rexmt_count, CTLFLAG_RDTUN,
374     &t4_toe_rexmt_count, 0, "Number of TOE retransmissions before abort");
375 
376 /* -1 means chip/fw default, other values are raw backoff values to use */
377 static int t4_toe_rexmt_backoff[16] = {
378 	-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1
379 };
380 SYSCTL_NODE(_hw_cxgbe_toe, OID_AUTO, rexmt_backoff,
381     CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
382     "cxgbe(4) TOE retransmit backoff values");
383 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 0, CTLFLAG_RDTUN,
384     &t4_toe_rexmt_backoff[0], 0, "");
385 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 1, CTLFLAG_RDTUN,
386     &t4_toe_rexmt_backoff[1], 0, "");
387 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 2, CTLFLAG_RDTUN,
388     &t4_toe_rexmt_backoff[2], 0, "");
389 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 3, CTLFLAG_RDTUN,
390     &t4_toe_rexmt_backoff[3], 0, "");
391 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 4, CTLFLAG_RDTUN,
392     &t4_toe_rexmt_backoff[4], 0, "");
393 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 5, CTLFLAG_RDTUN,
394     &t4_toe_rexmt_backoff[5], 0, "");
395 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 6, CTLFLAG_RDTUN,
396     &t4_toe_rexmt_backoff[6], 0, "");
397 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 7, CTLFLAG_RDTUN,
398     &t4_toe_rexmt_backoff[7], 0, "");
399 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 8, CTLFLAG_RDTUN,
400     &t4_toe_rexmt_backoff[8], 0, "");
401 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 9, CTLFLAG_RDTUN,
402     &t4_toe_rexmt_backoff[9], 0, "");
403 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 10, CTLFLAG_RDTUN,
404     &t4_toe_rexmt_backoff[10], 0, "");
405 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 11, CTLFLAG_RDTUN,
406     &t4_toe_rexmt_backoff[11], 0, "");
407 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 12, CTLFLAG_RDTUN,
408     &t4_toe_rexmt_backoff[12], 0, "");
409 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 13, CTLFLAG_RDTUN,
410     &t4_toe_rexmt_backoff[13], 0, "");
411 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 14, CTLFLAG_RDTUN,
412     &t4_toe_rexmt_backoff[14], 0, "");
413 SYSCTL_INT(_hw_cxgbe_toe_rexmt_backoff, OID_AUTO, 15, CTLFLAG_RDTUN,
414     &t4_toe_rexmt_backoff[15], 0, "");
415 
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 static int t4_num_vis = 1;
608 SYSCTL_INT(_hw_cxgbe, OID_AUTO, num_vis, CTLFLAG_RDTUN, &t4_num_vis, 0,
609     "Number of VIs per port");
610 
611 /*
612  * PCIe Relaxed Ordering.
613  * -1: driver should figure out a good value.
614  * 0: disable RO.
615  * 1: enable RO.
616  * 2: leave RO alone.
617  */
618 static int pcie_relaxed_ordering = -1;
619 SYSCTL_INT(_hw_cxgbe, OID_AUTO, pcie_relaxed_ordering, CTLFLAG_RDTUN,
620     &pcie_relaxed_ordering, 0,
621     "PCIe Relaxed Ordering: 0 = disable, 1 = enable, 2 = leave alone");
622 
623 static int t4_panic_on_fatal_err = 0;
624 SYSCTL_INT(_hw_cxgbe, OID_AUTO, panic_on_fatal_err, CTLFLAG_RWTUN,
625     &t4_panic_on_fatal_err, 0, "panic on fatal errors");
626 
627 static int t4_reset_on_fatal_err = 0;
628 SYSCTL_INT(_hw_cxgbe, OID_AUTO, reset_on_fatal_err, CTLFLAG_RWTUN,
629     &t4_reset_on_fatal_err, 0, "reset adapter on fatal errors");
630 
631 static int t4_clock_gate_on_suspend = 0;
632 SYSCTL_INT(_hw_cxgbe, OID_AUTO, clock_gate_on_suspend, CTLFLAG_RWTUN,
633     &t4_clock_gate_on_suspend, 0, "gate the clock on suspend");
634 
635 static int t4_tx_vm_wr = 0;
636 SYSCTL_INT(_hw_cxgbe, OID_AUTO, tx_vm_wr, CTLFLAG_RWTUN, &t4_tx_vm_wr, 0,
637     "Use VM work requests to transmit packets.");
638 
639 /*
640  * Set to non-zero to enable the attack filter.  A packet that matches any of
641  * these conditions will get dropped on ingress:
642  * 1) IP && source address == destination address.
643  * 2) TCP/IP && source address is not a unicast address.
644  * 3) TCP/IP && destination address is not a unicast address.
645  * 4) IP && source address is loopback (127.x.y.z).
646  * 5) IP && destination address is loopback (127.x.y.z).
647  * 6) IPv6 && source address == destination address.
648  * 7) IPv6 && source address is not a unicast address.
649  * 8) IPv6 && source address is loopback (::1/128).
650  * 9) IPv6 && destination address is loopback (::1/128).
651  * 10) IPv6 && source address is unspecified (::/128).
652  * 11) IPv6 && destination address is unspecified (::/128).
653  * 12) TCP/IPv6 && source address is multicast (ff00::/8).
654  * 13) TCP/IPv6 && destination address is multicast (ff00::/8).
655  */
656 static int t4_attack_filter = 0;
657 SYSCTL_INT(_hw_cxgbe, OID_AUTO, attack_filter, CTLFLAG_RDTUN,
658     &t4_attack_filter, 0, "Drop suspicious traffic");
659 
660 static int t4_drop_ip_fragments = 0;
661 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_ip_fragments, CTLFLAG_RDTUN,
662     &t4_drop_ip_fragments, 0, "Drop IP fragments");
663 
664 static int t4_drop_pkts_with_l2_errors = 1;
665 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l2_errors, CTLFLAG_RDTUN,
666     &t4_drop_pkts_with_l2_errors, 0,
667     "Drop all frames with Layer 2 length or checksum errors");
668 
669 static int t4_drop_pkts_with_l3_errors = 0;
670 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l3_errors, CTLFLAG_RDTUN,
671     &t4_drop_pkts_with_l3_errors, 0,
672     "Drop all frames with IP version, length, or checksum errors");
673 
674 static int t4_drop_pkts_with_l4_errors = 0;
675 SYSCTL_INT(_hw_cxgbe, OID_AUTO, drop_pkts_with_l4_errors, CTLFLAG_RDTUN,
676     &t4_drop_pkts_with_l4_errors, 0,
677     "Drop all frames with Layer 4 length, checksum, or other errors");
678 
679 #ifdef TCP_OFFLOAD
680 /*
681  * TOE tunables.
682  */
683 static int t4_cop_managed_offloading = 0;
684 SYSCTL_INT(_hw_cxgbe, OID_AUTO, cop_managed_offloading, CTLFLAG_RDTUN,
685     &t4_cop_managed_offloading, 0,
686     "COP (Connection Offload Policy) controls all TOE offload");
687 #endif
688 
689 #ifdef KERN_TLS
690 /*
691  * This enables KERN_TLS for all adapters if set.
692  */
693 static int t4_kern_tls = 0;
694 SYSCTL_INT(_hw_cxgbe, OID_AUTO, kern_tls, CTLFLAG_RDTUN, &t4_kern_tls, 0,
695     "Enable KERN_TLS mode for T6 adapters");
696 
697 SYSCTL_NODE(_hw_cxgbe, OID_AUTO, tls, CTLFLAG_RD | CTLFLAG_MPSAFE, 0,
698     "cxgbe(4) KERN_TLS parameters");
699 
700 static int t4_tls_inline_keys = 0;
701 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, inline_keys, CTLFLAG_RDTUN,
702     &t4_tls_inline_keys, 0,
703     "Always pass TLS keys in work requests (1) or attempt to store TLS keys "
704     "in card memory.");
705 
706 static int t4_tls_combo_wrs = 0;
707 SYSCTL_INT(_hw_cxgbe_tls, OID_AUTO, combo_wrs, CTLFLAG_RDTUN, &t4_tls_combo_wrs,
708     0, "Attempt to combine TCB field updates with TLS record work requests.");
709 #endif
710 
711 /* Functions used by VIs to obtain unique MAC addresses for each VI. */
712 static int vi_mac_funcs[] = {
713 	FW_VI_FUNC_ETH,
714 	FW_VI_FUNC_OFLD,
715 	FW_VI_FUNC_IWARP,
716 	FW_VI_FUNC_OPENISCSI,
717 	FW_VI_FUNC_OPENFCOE,
718 	FW_VI_FUNC_FOISCSI,
719 	FW_VI_FUNC_FOFCOE,
720 };
721 
722 struct intrs_and_queues {
723 	uint16_t intr_type;	/* INTx, MSI, or MSI-X */
724 	uint16_t num_vis;	/* number of VIs for each port */
725 	uint16_t nirq;		/* Total # of vectors */
726 	uint16_t ntxq;		/* # of NIC txq's for each port */
727 	uint16_t nrxq;		/* # of NIC rxq's for each port */
728 	uint16_t nofldtxq;	/* # of TOE/ETHOFLD txq's for each port */
729 	uint16_t nofldrxq;	/* # of TOE rxq's for each port */
730 	uint16_t nnmtxq;	/* # of netmap txq's */
731 	uint16_t nnmrxq;	/* # of netmap rxq's */
732 
733 	/* The vcxgbe/vcxl interfaces use these and not the ones above. */
734 	uint16_t ntxq_vi;	/* # of NIC txq's */
735 	uint16_t nrxq_vi;	/* # of NIC rxq's */
736 	uint16_t nofldtxq_vi;	/* # of TOE txq's */
737 	uint16_t nofldrxq_vi;	/* # of TOE rxq's */
738 	uint16_t nnmtxq_vi;	/* # of netmap txq's */
739 	uint16_t nnmrxq_vi;	/* # of netmap rxq's */
740 };
741 
742 static void setup_memwin(struct adapter *);
743 static void position_memwin(struct adapter *, int, uint32_t);
744 static int validate_mem_range(struct adapter *, uint32_t, uint32_t);
745 static int fwmtype_to_hwmtype(int);
746 static int validate_mt_off_len(struct adapter *, int, uint32_t, uint32_t,
747     uint32_t *);
748 static int fixup_devlog_params(struct adapter *);
749 static int cfg_itype_and_nqueues(struct adapter *, struct intrs_and_queues *);
750 static int contact_firmware(struct adapter *);
751 static int partition_resources(struct adapter *);
752 static int get_params__pre_init(struct adapter *);
753 static int set_params__pre_init(struct adapter *);
754 static int get_params__post_init(struct adapter *);
755 static int set_params__post_init(struct adapter *);
756 static void t4_set_desc(struct adapter *);
757 static bool fixed_ifmedia(struct port_info *);
758 static void build_medialist(struct port_info *);
759 static void init_link_config(struct port_info *);
760 static int fixup_link_config(struct port_info *);
761 static int apply_link_config(struct port_info *);
762 static int cxgbe_init_synchronized(struct vi_info *);
763 static int cxgbe_uninit_synchronized(struct vi_info *);
764 static int adapter_full_init(struct adapter *);
765 static void adapter_full_uninit(struct adapter *);
766 static int vi_full_init(struct vi_info *);
767 static void vi_full_uninit(struct vi_info *);
768 static int alloc_extra_vi(struct adapter *, struct port_info *, struct vi_info *);
769 static void quiesce_txq(struct sge_txq *);
770 static void quiesce_wrq(struct sge_wrq *);
771 static void quiesce_iq_fl(struct adapter *, struct sge_iq *, struct sge_fl *);
772 static void quiesce_vi(struct vi_info *);
773 static int t4_alloc_irq(struct adapter *, struct irq *, int rid,
774     driver_intr_t *, void *, char *);
775 static int t4_free_irq(struct adapter *, struct irq *);
776 static void t4_init_atid_table(struct adapter *);
777 static void t4_free_atid_table(struct adapter *);
778 static void get_regs(struct adapter *, struct t4_regdump *, uint8_t *);
779 static void vi_refresh_stats(struct vi_info *);
780 static void cxgbe_refresh_stats(struct vi_info *);
781 static void cxgbe_tick(void *);
782 static void vi_tick(void *);
783 static void cxgbe_sysctls(struct port_info *);
784 static int sysctl_int_array(SYSCTL_HANDLER_ARGS);
785 static int sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS);
786 static int sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS);
787 static int sysctl_btphy(SYSCTL_HANDLER_ARGS);
788 static int sysctl_noflowq(SYSCTL_HANDLER_ARGS);
789 static int sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS);
790 static int sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS);
791 static int sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS);
792 static int sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS);
793 static int sysctl_qsize_txq(SYSCTL_HANDLER_ARGS);
794 static int sysctl_pause_settings(SYSCTL_HANDLER_ARGS);
795 static int sysctl_link_fec(SYSCTL_HANDLER_ARGS);
796 static int sysctl_requested_fec(SYSCTL_HANDLER_ARGS);
797 static int sysctl_module_fec(SYSCTL_HANDLER_ARGS);
798 static int sysctl_autoneg(SYSCTL_HANDLER_ARGS);
799 static int sysctl_force_fec(SYSCTL_HANDLER_ARGS);
800 static int sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS);
801 static int sysctl_temperature(SYSCTL_HANDLER_ARGS);
802 static int sysctl_vdd(SYSCTL_HANDLER_ARGS);
803 static int sysctl_reset_sensor(SYSCTL_HANDLER_ARGS);
804 static int sysctl_loadavg(SYSCTL_HANDLER_ARGS);
805 static int sysctl_cctrl(SYSCTL_HANDLER_ARGS);
806 static int sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS);
807 static int sysctl_cim_la(SYSCTL_HANDLER_ARGS);
808 static int sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS);
809 static int sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS);
810 static int sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS);
811 static int sysctl_cpl_stats(SYSCTL_HANDLER_ARGS);
812 static int sysctl_ddp_stats(SYSCTL_HANDLER_ARGS);
813 static int sysctl_tid_stats(SYSCTL_HANDLER_ARGS);
814 static int sysctl_devlog(SYSCTL_HANDLER_ARGS);
815 static int sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS);
816 static int sysctl_hw_sched(SYSCTL_HANDLER_ARGS);
817 static int sysctl_lb_stats(SYSCTL_HANDLER_ARGS);
818 static int sysctl_linkdnrc(SYSCTL_HANDLER_ARGS);
819 static int sysctl_meminfo(SYSCTL_HANDLER_ARGS);
820 static int sysctl_mps_tcam(SYSCTL_HANDLER_ARGS);
821 static int sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS);
822 static int sysctl_path_mtus(SYSCTL_HANDLER_ARGS);
823 static int sysctl_pm_stats(SYSCTL_HANDLER_ARGS);
824 static int sysctl_rdma_stats(SYSCTL_HANDLER_ARGS);
825 static int sysctl_tcp_stats(SYSCTL_HANDLER_ARGS);
826 static int sysctl_tids(SYSCTL_HANDLER_ARGS);
827 static int sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS);
828 static int sysctl_tnl_stats(SYSCTL_HANDLER_ARGS);
829 static int sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS);
830 static int sysctl_tp_la(SYSCTL_HANDLER_ARGS);
831 static int sysctl_tx_rate(SYSCTL_HANDLER_ARGS);
832 static int sysctl_ulprx_la(SYSCTL_HANDLER_ARGS);
833 static int sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS);
834 static int sysctl_cpus(SYSCTL_HANDLER_ARGS);
835 static int sysctl_reset(SYSCTL_HANDLER_ARGS);
836 #ifdef TCP_OFFLOAD
837 static int sysctl_tls(SYSCTL_HANDLER_ARGS);
838 static int sysctl_tp_tick(SYSCTL_HANDLER_ARGS);
839 static int sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS);
840 static int sysctl_tp_timer(SYSCTL_HANDLER_ARGS);
841 static int sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS);
842 static int sysctl_tp_backoff(SYSCTL_HANDLER_ARGS);
843 static int sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS);
844 static int sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS);
845 #endif
846 static int get_sge_context(struct adapter *, struct t4_sge_context *);
847 static int load_fw(struct adapter *, struct t4_data *);
848 static int load_cfg(struct adapter *, struct t4_data *);
849 static int load_boot(struct adapter *, struct t4_bootrom *);
850 static int load_bootcfg(struct adapter *, struct t4_data *);
851 static int cudbg_dump(struct adapter *, struct t4_cudbg_dump *);
852 static void free_offload_policy(struct t4_offload_policy *);
853 static int set_offload_policy(struct adapter *, struct t4_offload_policy *);
854 static int read_card_mem(struct adapter *, int, struct t4_mem_range *);
855 static int read_i2c(struct adapter *, struct t4_i2c_data *);
856 static int clear_stats(struct adapter *, u_int);
857 static int hold_clip_addr(struct adapter *, struct t4_clip_addr *);
858 static int release_clip_addr(struct adapter *, struct t4_clip_addr *);
859 #ifdef TCP_OFFLOAD
860 static int toe_capability(struct vi_info *, bool);
861 static int t4_deactivate_all_uld(struct adapter *);
862 static void t4_async_event(struct adapter *);
863 #endif
864 #ifdef KERN_TLS
865 static int ktls_capability(struct adapter *, bool);
866 #endif
867 static int mod_event(module_t, int, void *);
868 static int notify_siblings(device_t, int);
869 static uint64_t vi_get_counter(if_t, ift_counter);
870 static uint64_t cxgbe_get_counter(if_t, ift_counter);
871 static void enable_vxlan_rx(struct adapter *);
872 static void reset_adapter_task(void *, int);
873 static void fatal_error_task(void *, int);
874 static void dump_devlog(struct adapter *);
875 static void dump_cim_regs(struct adapter *);
876 static void dump_cimla(struct adapter *);
877 
878 struct {
879 	uint16_t device;
880 	char *desc;
881 } t4_pciids[] = {
882 	{0xa000, "Chelsio Terminator 4 FPGA"},
883 	{0x4400, "Chelsio T440-dbg"},
884 	{0x4401, "Chelsio T420-CR"},
885 	{0x4402, "Chelsio T422-CR"},
886 	{0x4403, "Chelsio T440-CR"},
887 	{0x4404, "Chelsio T420-BCH"},
888 	{0x4405, "Chelsio T440-BCH"},
889 	{0x4406, "Chelsio T440-CH"},
890 	{0x4407, "Chelsio T420-SO"},
891 	{0x4408, "Chelsio T420-CX"},
892 	{0x4409, "Chelsio T420-BT"},
893 	{0x440a, "Chelsio T404-BT"},
894 	{0x440e, "Chelsio T440-LP-CR"},
895 }, t5_pciids[] = {
896 	{0xb000, "Chelsio Terminator 5 FPGA"},
897 	{0x5400, "Chelsio T580-dbg"},
898 	{0x5401,  "Chelsio T520-CR"},		/* 2 x 10G */
899 	{0x5402,  "Chelsio T522-CR"},		/* 2 x 10G, 2 X 1G */
900 	{0x5403,  "Chelsio T540-CR"},		/* 4 x 10G */
901 	{0x5407,  "Chelsio T520-SO"},		/* 2 x 10G, nomem */
902 	{0x5409,  "Chelsio T520-BT"},		/* 2 x 10GBaseT */
903 	{0x540a,  "Chelsio T504-BT"},		/* 4 x 1G */
904 	{0x540d,  "Chelsio T580-CR"},		/* 2 x 40G */
905 	{0x540e,  "Chelsio T540-LP-CR"},	/* 4 x 10G */
906 	{0x5410,  "Chelsio T580-LP-CR"},	/* 2 x 40G */
907 	{0x5411,  "Chelsio T520-LL-CR"},	/* 2 x 10G */
908 	{0x5412,  "Chelsio T560-CR"},		/* 1 x 40G, 2 x 10G */
909 	{0x5414,  "Chelsio T580-LP-SO-CR"},	/* 2 x 40G, nomem */
910 	{0x5415,  "Chelsio T502-BT"},		/* 2 x 1G */
911 	{0x5418,  "Chelsio T540-BT"},		/* 4 x 10GBaseT */
912 	{0x5419,  "Chelsio T540-LP-BT"},	/* 4 x 10GBaseT */
913 	{0x541a,  "Chelsio T540-SO-BT"},	/* 4 x 10GBaseT, nomem */
914 	{0x541b,  "Chelsio T540-SO-CR"},	/* 4 x 10G, nomem */
915 
916 	/* Custom */
917 	{0x5483, "Custom T540-CR"},
918 	{0x5484, "Custom T540-BT"},
919 }, t6_pciids[] = {
920 	{0xc006, "Chelsio Terminator 6 FPGA"},	/* T6 PE10K6 FPGA (PF0) */
921 	{0x6400, "Chelsio T6-DBG-25"},		/* 2 x 10/25G, debug */
922 	{0x6401, "Chelsio T6225-CR"},		/* 2 x 10/25G */
923 	{0x6402, "Chelsio T6225-SO-CR"},	/* 2 x 10/25G, nomem */
924 	{0x6403, "Chelsio T6425-CR"},		/* 4 x 10/25G */
925 	{0x6404, "Chelsio T6425-SO-CR"},	/* 4 x 10/25G, nomem */
926 	{0x6405, "Chelsio T6225-OCP-SO"},	/* 2 x 10/25G, nomem */
927 	{0x6406, "Chelsio T62100-OCP-SO"},	/* 2 x 40/50/100G, nomem */
928 	{0x6407, "Chelsio T62100-LP-CR"},	/* 2 x 40/50/100G */
929 	{0x6408, "Chelsio T62100-SO-CR"},	/* 2 x 40/50/100G, nomem */
930 	{0x6409, "Chelsio T6210-BT"},		/* 2 x 10GBASE-T */
931 	{0x640d, "Chelsio T62100-CR"},		/* 2 x 40/50/100G */
932 	{0x6410, "Chelsio T6-DBG-100"},		/* 2 x 40/50/100G, debug */
933 	{0x6411, "Chelsio T6225-LL-CR"},	/* 2 x 10/25G */
934 	{0x6414, "Chelsio T61100-OCP-SO"},	/* 1 x 40/50/100G, nomem */
935 	{0x6415, "Chelsio T6201-BT"},		/* 2 x 1000BASE-T */
936 
937 	/* Custom */
938 	{0x6480, "Custom T6225-CR"},
939 	{0x6481, "Custom T62100-CR"},
940 	{0x6482, "Custom T6225-CR"},
941 	{0x6483, "Custom T62100-CR"},
942 	{0x6484, "Custom T64100-CR"},
943 	{0x6485, "Custom T6240-SO"},
944 	{0x6486, "Custom T6225-SO-CR"},
945 	{0x6487, "Custom T6225-CR"},
946 };
947 
948 #ifdef TCP_OFFLOAD
949 /*
950  * service_iq_fl() has an iq and needs the fl.  Offset of fl from the iq should
951  * be exactly the same for both rxq and ofld_rxq.
952  */
953 CTASSERT(offsetof(struct sge_ofld_rxq, iq) == offsetof(struct sge_rxq, iq));
954 CTASSERT(offsetof(struct sge_ofld_rxq, fl) == offsetof(struct sge_rxq, fl));
955 #endif
956 CTASSERT(sizeof(struct cluster_metadata) <= CL_METADATA_SIZE);
957 
958 static int
959 t4_probe(device_t dev)
960 {
961 	int i;
962 	uint16_t v = pci_get_vendor(dev);
963 	uint16_t d = pci_get_device(dev);
964 	uint8_t f = pci_get_function(dev);
965 
966 	if (v != PCI_VENDOR_ID_CHELSIO)
967 		return (ENXIO);
968 
969 	/* Attach only to PF0 of the FPGA */
970 	if (d == 0xa000 && f != 0)
971 		return (ENXIO);
972 
973 	for (i = 0; i < nitems(t4_pciids); i++) {
974 		if (d == t4_pciids[i].device) {
975 			device_set_desc(dev, t4_pciids[i].desc);
976 			return (BUS_PROBE_DEFAULT);
977 		}
978 	}
979 
980 	return (ENXIO);
981 }
982 
983 static int
984 t5_probe(device_t dev)
985 {
986 	int i;
987 	uint16_t v = pci_get_vendor(dev);
988 	uint16_t d = pci_get_device(dev);
989 	uint8_t f = pci_get_function(dev);
990 
991 	if (v != PCI_VENDOR_ID_CHELSIO)
992 		return (ENXIO);
993 
994 	/* Attach only to PF0 of the FPGA */
995 	if (d == 0xb000 && f != 0)
996 		return (ENXIO);
997 
998 	for (i = 0; i < nitems(t5_pciids); i++) {
999 		if (d == t5_pciids[i].device) {
1000 			device_set_desc(dev, t5_pciids[i].desc);
1001 			return (BUS_PROBE_DEFAULT);
1002 		}
1003 	}
1004 
1005 	return (ENXIO);
1006 }
1007 
1008 static int
1009 t6_probe(device_t dev)
1010 {
1011 	int i;
1012 	uint16_t v = pci_get_vendor(dev);
1013 	uint16_t d = pci_get_device(dev);
1014 
1015 	if (v != PCI_VENDOR_ID_CHELSIO)
1016 		return (ENXIO);
1017 
1018 	for (i = 0; i < nitems(t6_pciids); i++) {
1019 		if (d == t6_pciids[i].device) {
1020 			device_set_desc(dev, t6_pciids[i].desc);
1021 			return (BUS_PROBE_DEFAULT);
1022 		}
1023 	}
1024 
1025 	return (ENXIO);
1026 }
1027 
1028 static void
1029 t5_attribute_workaround(device_t dev)
1030 {
1031 	device_t root_port;
1032 	uint32_t v;
1033 
1034 	/*
1035 	 * The T5 chips do not properly echo the No Snoop and Relaxed
1036 	 * Ordering attributes when replying to a TLP from a Root
1037 	 * Port.  As a workaround, find the parent Root Port and
1038 	 * disable No Snoop and Relaxed Ordering.  Note that this
1039 	 * affects all devices under this root port.
1040 	 */
1041 	root_port = pci_find_pcie_root_port(dev);
1042 	if (root_port == NULL) {
1043 		device_printf(dev, "Unable to find parent root port\n");
1044 		return;
1045 	}
1046 
1047 	v = pcie_adjust_config(root_port, PCIER_DEVICE_CTL,
1048 	    PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE, 0, 2);
1049 	if ((v & (PCIEM_CTL_RELAXED_ORD_ENABLE | PCIEM_CTL_NOSNOOP_ENABLE)) !=
1050 	    0)
1051 		device_printf(dev, "Disabled No Snoop/Relaxed Ordering on %s\n",
1052 		    device_get_nameunit(root_port));
1053 }
1054 
1055 static const struct devnames devnames[] = {
1056 	{
1057 		.nexus_name = "t4nex",
1058 		.ifnet_name = "cxgbe",
1059 		.vi_ifnet_name = "vcxgbe",
1060 		.pf03_drv_name = "t4iov",
1061 		.vf_nexus_name = "t4vf",
1062 		.vf_ifnet_name = "cxgbev"
1063 	}, {
1064 		.nexus_name = "t5nex",
1065 		.ifnet_name = "cxl",
1066 		.vi_ifnet_name = "vcxl",
1067 		.pf03_drv_name = "t5iov",
1068 		.vf_nexus_name = "t5vf",
1069 		.vf_ifnet_name = "cxlv"
1070 	}, {
1071 		.nexus_name = "t6nex",
1072 		.ifnet_name = "cc",
1073 		.vi_ifnet_name = "vcc",
1074 		.pf03_drv_name = "t6iov",
1075 		.vf_nexus_name = "t6vf",
1076 		.vf_ifnet_name = "ccv"
1077 	}
1078 };
1079 
1080 void
1081 t4_init_devnames(struct adapter *sc)
1082 {
1083 	int id;
1084 
1085 	id = chip_id(sc);
1086 	if (id >= CHELSIO_T4 && id - CHELSIO_T4 < nitems(devnames))
1087 		sc->names = &devnames[id - CHELSIO_T4];
1088 	else {
1089 		device_printf(sc->dev, "chip id %d is not supported.\n", id);
1090 		sc->names = NULL;
1091 	}
1092 }
1093 
1094 static int
1095 t4_ifnet_unit(struct adapter *sc, struct port_info *pi)
1096 {
1097 	const char *parent, *name;
1098 	long value;
1099 	int line, unit;
1100 
1101 	line = 0;
1102 	parent = device_get_nameunit(sc->dev);
1103 	name = sc->names->ifnet_name;
1104 	while (resource_find_dev(&line, name, &unit, "at", parent) == 0) {
1105 		if (resource_long_value(name, unit, "port", &value) == 0 &&
1106 		    value == pi->port_id)
1107 			return (unit);
1108 	}
1109 	return (-1);
1110 }
1111 
1112 static void
1113 t4_calibration(void *arg)
1114 {
1115 	struct adapter *sc;
1116 	struct clock_sync *cur, *nex;
1117 	uint64_t hw;
1118 	sbintime_t sbt;
1119 	int next_up;
1120 
1121 	sc = (struct adapter *)arg;
1122 
1123 	KASSERT((hw_off_limits(sc) == 0), ("hw_off_limits at t4_calibration"));
1124 	hw = t4_read_reg64(sc, A_SGE_TIMESTAMP_LO);
1125 	sbt = sbinuptime();
1126 
1127 	cur = &sc->cal_info[sc->cal_current];
1128 	next_up = (sc->cal_current + 1) % CNT_CAL_INFO;
1129 	nex = &sc->cal_info[next_up];
1130 	if (__predict_false(sc->cal_count == 0)) {
1131 		/* First time in, just get the values in */
1132 		cur->hw_cur = hw;
1133 		cur->sbt_cur = sbt;
1134 		sc->cal_count++;
1135 		goto done;
1136 	}
1137 
1138 	if (cur->hw_cur == hw) {
1139 		/* The clock is not advancing? */
1140 		sc->cal_count = 0;
1141 		atomic_store_rel_int(&cur->gen, 0);
1142 		goto done;
1143 	}
1144 
1145 	seqc_write_begin(&nex->gen);
1146 	nex->hw_prev = cur->hw_cur;
1147 	nex->sbt_prev = cur->sbt_cur;
1148 	nex->hw_cur = hw;
1149 	nex->sbt_cur = sbt;
1150 	seqc_write_end(&nex->gen);
1151 	sc->cal_current = next_up;
1152 done:
1153 	callout_reset_sbt_curcpu(&sc->cal_callout, SBT_1S, 0, t4_calibration,
1154 	    sc, C_DIRECT_EXEC);
1155 }
1156 
1157 static void
1158 t4_calibration_start(struct adapter *sc)
1159 {
1160 	/*
1161 	 * Here if we have not done a calibration
1162 	 * then do so otherwise start the appropriate
1163 	 * timer.
1164 	 */
1165 	int i;
1166 
1167 	for (i = 0; i < CNT_CAL_INFO; i++) {
1168 		sc->cal_info[i].gen = 0;
1169 	}
1170 	sc->cal_current = 0;
1171 	sc->cal_count = 0;
1172 	sc->cal_gen = 0;
1173 	t4_calibration(sc);
1174 }
1175 
1176 static int
1177 t4_attach(device_t dev)
1178 {
1179 	struct adapter *sc;
1180 	int rc = 0, i, j, rqidx, tqidx, nports;
1181 	struct make_dev_args mda;
1182 	struct intrs_and_queues iaq;
1183 	struct sge *s;
1184 	uint32_t *buf;
1185 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1186 	int ofld_tqidx;
1187 #endif
1188 #ifdef TCP_OFFLOAD
1189 	int ofld_rqidx;
1190 #endif
1191 #ifdef DEV_NETMAP
1192 	int nm_rqidx, nm_tqidx;
1193 #endif
1194 	int num_vis;
1195 
1196 	sc = device_get_softc(dev);
1197 	sc->dev = dev;
1198 	sysctl_ctx_init(&sc->ctx);
1199 	TUNABLE_INT_FETCH("hw.cxgbe.dflags", &sc->debug_flags);
1200 
1201 	if ((pci_get_device(dev) & 0xff00) == 0x5400)
1202 		t5_attribute_workaround(dev);
1203 	pci_enable_busmaster(dev);
1204 	if (pci_find_cap(dev, PCIY_EXPRESS, &i) == 0) {
1205 		uint32_t v;
1206 
1207 		pci_set_max_read_req(dev, 4096);
1208 		v = pci_read_config(dev, i + PCIER_DEVICE_CTL, 2);
1209 		sc->params.pci.mps = 128 << ((v & PCIEM_CTL_MAX_PAYLOAD) >> 5);
1210 		if (pcie_relaxed_ordering == 0 &&
1211 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) != 0) {
1212 			v &= ~PCIEM_CTL_RELAXED_ORD_ENABLE;
1213 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1214 		} else if (pcie_relaxed_ordering == 1 &&
1215 		    (v & PCIEM_CTL_RELAXED_ORD_ENABLE) == 0) {
1216 			v |= PCIEM_CTL_RELAXED_ORD_ENABLE;
1217 			pci_write_config(dev, i + PCIER_DEVICE_CTL, v, 2);
1218 		}
1219 	}
1220 
1221 	sc->sge_gts_reg = MYPF_REG(A_SGE_PF_GTS);
1222 	sc->sge_kdoorbell_reg = MYPF_REG(A_SGE_PF_KDOORBELL);
1223 	sc->traceq = -1;
1224 	mtx_init(&sc->ifp_lock, sc->ifp_lockname, 0, MTX_DEF);
1225 	snprintf(sc->ifp_lockname, sizeof(sc->ifp_lockname), "%s tracer",
1226 	    device_get_nameunit(dev));
1227 
1228 	snprintf(sc->lockname, sizeof(sc->lockname), "%s",
1229 	    device_get_nameunit(dev));
1230 	mtx_init(&sc->sc_lock, sc->lockname, 0, MTX_DEF);
1231 	t4_add_adapter(sc);
1232 
1233 	mtx_init(&sc->sfl_lock, "starving freelists", 0, MTX_DEF);
1234 	TAILQ_INIT(&sc->sfl);
1235 	callout_init_mtx(&sc->sfl_callout, &sc->sfl_lock, 0);
1236 
1237 	mtx_init(&sc->reg_lock, "indirect register access", 0, MTX_DEF);
1238 
1239 	sc->policy = NULL;
1240 	rw_init(&sc->policy_lock, "connection offload policy");
1241 
1242 	callout_init(&sc->ktls_tick, 1);
1243 
1244 	callout_init(&sc->cal_callout, 1);
1245 
1246 	refcount_init(&sc->vxlan_refcount, 0);
1247 
1248 	TASK_INIT(&sc->reset_task, 0, reset_adapter_task, sc);
1249 	TASK_INIT(&sc->fatal_error_task, 0, fatal_error_task, sc);
1250 
1251 	sc->ctrlq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1252 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "ctrlq",
1253 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "control queues");
1254 	sc->fwq_oid = SYSCTL_ADD_NODE(&sc->ctx,
1255 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO, "fwq",
1256 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "firmware event queue");
1257 
1258 	rc = t4_map_bars_0_and_4(sc);
1259 	if (rc != 0)
1260 		goto done; /* error message displayed already */
1261 
1262 	memset(sc->chan_map, 0xff, sizeof(sc->chan_map));
1263 
1264 	/* Prepare the adapter for operation. */
1265 	buf = malloc(PAGE_SIZE, M_CXGBE, M_ZERO | M_WAITOK);
1266 	rc = -t4_prep_adapter(sc, buf);
1267 	free(buf, M_CXGBE);
1268 	if (rc != 0) {
1269 		device_printf(dev, "failed to prepare adapter: %d.\n", rc);
1270 		goto done;
1271 	}
1272 
1273 	/*
1274 	 * This is the real PF# to which we're attaching.  Works from within PCI
1275 	 * passthrough environments too, where pci_get_function() could return a
1276 	 * different PF# depending on the passthrough configuration.  We need to
1277 	 * use the real PF# in all our communication with the firmware.
1278 	 */
1279 	j = t4_read_reg(sc, A_PL_WHOAMI);
1280 	sc->pf = chip_id(sc) <= CHELSIO_T5 ? G_SOURCEPF(j) : G_T6_SOURCEPF(j);
1281 	sc->mbox = sc->pf;
1282 
1283 	t4_init_devnames(sc);
1284 	if (sc->names == NULL) {
1285 		rc = ENOTSUP;
1286 		goto done; /* error message displayed already */
1287 	}
1288 
1289 	/*
1290 	 * Do this really early, with the memory windows set up even before the
1291 	 * character device.  The userland tool's register i/o and mem read
1292 	 * will work even in "recovery mode".
1293 	 */
1294 	setup_memwin(sc);
1295 	if (t4_init_devlog_params(sc, 0) == 0)
1296 		fixup_devlog_params(sc);
1297 	make_dev_args_init(&mda);
1298 	mda.mda_devsw = &t4_cdevsw;
1299 	mda.mda_uid = UID_ROOT;
1300 	mda.mda_gid = GID_WHEEL;
1301 	mda.mda_mode = 0600;
1302 	mda.mda_si_drv1 = sc;
1303 	rc = make_dev_s(&mda, &sc->cdev, "%s", device_get_nameunit(dev));
1304 	if (rc != 0)
1305 		device_printf(dev, "failed to create nexus char device: %d.\n",
1306 		    rc);
1307 
1308 	/* Go no further if recovery mode has been requested. */
1309 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
1310 		device_printf(dev, "recovery mode.\n");
1311 		goto done;
1312 	}
1313 
1314 #if defined(__i386__)
1315 	if ((cpu_feature & CPUID_CX8) == 0) {
1316 		device_printf(dev, "64 bit atomics not available.\n");
1317 		rc = ENOTSUP;
1318 		goto done;
1319 	}
1320 #endif
1321 
1322 	/* Contact the firmware and try to become the master driver. */
1323 	rc = contact_firmware(sc);
1324 	if (rc != 0)
1325 		goto done; /* error message displayed already */
1326 	MPASS(sc->flags & FW_OK);
1327 
1328 	rc = get_params__pre_init(sc);
1329 	if (rc != 0)
1330 		goto done; /* error message displayed already */
1331 
1332 	if (sc->flags & MASTER_PF) {
1333 		rc = partition_resources(sc);
1334 		if (rc != 0)
1335 			goto done; /* error message displayed already */
1336 		t4_intr_clear(sc);
1337 	}
1338 
1339 	rc = get_params__post_init(sc);
1340 	if (rc != 0)
1341 		goto done; /* error message displayed already */
1342 
1343 	rc = set_params__post_init(sc);
1344 	if (rc != 0)
1345 		goto done; /* error message displayed already */
1346 
1347 	rc = t4_map_bar_2(sc);
1348 	if (rc != 0)
1349 		goto done; /* error message displayed already */
1350 
1351 	rc = t4_create_dma_tag(sc);
1352 	if (rc != 0)
1353 		goto done; /* error message displayed already */
1354 
1355 	/*
1356 	 * First pass over all the ports - allocate VIs and initialize some
1357 	 * basic parameters like mac address, port type, etc.
1358 	 */
1359 	for_each_port(sc, i) {
1360 		struct port_info *pi;
1361 
1362 		pi = malloc(sizeof(*pi), M_CXGBE, M_ZERO | M_WAITOK);
1363 		sc->port[i] = pi;
1364 
1365 		/* These must be set before t4_port_init */
1366 		pi->adapter = sc;
1367 		pi->port_id = i;
1368 		/*
1369 		 * XXX: vi[0] is special so we can't delay this allocation until
1370 		 * pi->nvi's final value is known.
1371 		 */
1372 		pi->vi = malloc(sizeof(struct vi_info) * t4_num_vis, M_CXGBE,
1373 		    M_ZERO | M_WAITOK);
1374 
1375 		/*
1376 		 * Allocate the "main" VI and initialize parameters
1377 		 * like mac addr.
1378 		 */
1379 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
1380 		if (rc != 0) {
1381 			device_printf(dev, "unable to initialize port %d: %d\n",
1382 			    i, rc);
1383 			free(pi->vi, M_CXGBE);
1384 			free(pi, M_CXGBE);
1385 			sc->port[i] = NULL;
1386 			goto done;
1387 		}
1388 
1389 		if (is_bt(pi->port_type))
1390 			setbit(&sc->bt_map, pi->tx_chan);
1391 		else
1392 			MPASS(!isset(&sc->bt_map, pi->tx_chan));
1393 
1394 		snprintf(pi->lockname, sizeof(pi->lockname), "%sp%d",
1395 		    device_get_nameunit(dev), i);
1396 		mtx_init(&pi->pi_lock, pi->lockname, 0, MTX_DEF);
1397 		sc->chan_map[pi->tx_chan] = i;
1398 
1399 		/*
1400 		 * The MPS counter for FCS errors doesn't work correctly on the
1401 		 * T6 so we use the MAC counter here.  Which MAC is in use
1402 		 * depends on the link settings which will be known when the
1403 		 * link comes up.
1404 		 */
1405 		if (is_t6(sc)) {
1406 			pi->fcs_reg = -1;
1407 		} else if (is_t4(sc)) {
1408 			pi->fcs_reg = PORT_REG(pi->tx_chan,
1409 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1410 		} else {
1411 			pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
1412 			    A_MPS_PORT_STAT_RX_PORT_CRC_ERROR_L);
1413 		}
1414 		pi->fcs_base = 0;
1415 
1416 		/* All VIs on this port share this media. */
1417 		ifmedia_init(&pi->media, IFM_IMASK, cxgbe_media_change,
1418 		    cxgbe_media_status);
1419 
1420 		PORT_LOCK(pi);
1421 		init_link_config(pi);
1422 		fixup_link_config(pi);
1423 		build_medialist(pi);
1424 		if (fixed_ifmedia(pi))
1425 			pi->flags |= FIXED_IFMEDIA;
1426 		PORT_UNLOCK(pi);
1427 
1428 		pi->dev = device_add_child(dev, sc->names->ifnet_name,
1429 		    t4_ifnet_unit(sc, pi));
1430 		if (pi->dev == NULL) {
1431 			device_printf(dev,
1432 			    "failed to add device for port %d.\n", i);
1433 			rc = ENXIO;
1434 			goto done;
1435 		}
1436 		pi->vi[0].dev = pi->dev;
1437 		device_set_softc(pi->dev, pi);
1438 	}
1439 
1440 	/*
1441 	 * Interrupt type, # of interrupts, # of rx/tx queues, etc.
1442 	 */
1443 	nports = sc->params.nports;
1444 	rc = cfg_itype_and_nqueues(sc, &iaq);
1445 	if (rc != 0)
1446 		goto done; /* error message displayed already */
1447 
1448 	num_vis = iaq.num_vis;
1449 	sc->intr_type = iaq.intr_type;
1450 	sc->intr_count = iaq.nirq;
1451 
1452 	s = &sc->sge;
1453 	s->nrxq = nports * iaq.nrxq;
1454 	s->ntxq = nports * iaq.ntxq;
1455 	if (num_vis > 1) {
1456 		s->nrxq += nports * (num_vis - 1) * iaq.nrxq_vi;
1457 		s->ntxq += nports * (num_vis - 1) * iaq.ntxq_vi;
1458 	}
1459 	s->neq = s->ntxq + s->nrxq;	/* the free list in an rxq is an eq */
1460 	s->neq += nports;		/* ctrl queues: 1 per port */
1461 	s->niq = s->nrxq + 1;		/* 1 extra for firmware event queue */
1462 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1463 	if (is_offload(sc) || is_ethoffload(sc)) {
1464 		s->nofldtxq = nports * iaq.nofldtxq;
1465 		if (num_vis > 1)
1466 			s->nofldtxq += nports * (num_vis - 1) * iaq.nofldtxq_vi;
1467 		s->neq += s->nofldtxq;
1468 
1469 		s->ofld_txq = malloc(s->nofldtxq * sizeof(struct sge_ofld_txq),
1470 		    M_CXGBE, M_ZERO | M_WAITOK);
1471 	}
1472 #endif
1473 #ifdef TCP_OFFLOAD
1474 	if (is_offload(sc)) {
1475 		s->nofldrxq = nports * iaq.nofldrxq;
1476 		if (num_vis > 1)
1477 			s->nofldrxq += nports * (num_vis - 1) * iaq.nofldrxq_vi;
1478 		s->neq += s->nofldrxq;	/* free list */
1479 		s->niq += s->nofldrxq;
1480 
1481 		s->ofld_rxq = malloc(s->nofldrxq * sizeof(struct sge_ofld_rxq),
1482 		    M_CXGBE, M_ZERO | M_WAITOK);
1483 	}
1484 #endif
1485 #ifdef DEV_NETMAP
1486 	s->nnmrxq = 0;
1487 	s->nnmtxq = 0;
1488 	if (t4_native_netmap & NN_MAIN_VI) {
1489 		s->nnmrxq += nports * iaq.nnmrxq;
1490 		s->nnmtxq += nports * iaq.nnmtxq;
1491 	}
1492 	if (num_vis > 1 && t4_native_netmap & NN_EXTRA_VI) {
1493 		s->nnmrxq += nports * (num_vis - 1) * iaq.nnmrxq_vi;
1494 		s->nnmtxq += nports * (num_vis - 1) * iaq.nnmtxq_vi;
1495 	}
1496 	s->neq += s->nnmtxq + s->nnmrxq;
1497 	s->niq += s->nnmrxq;
1498 
1499 	s->nm_rxq = malloc(s->nnmrxq * sizeof(struct sge_nm_rxq),
1500 	    M_CXGBE, M_ZERO | M_WAITOK);
1501 	s->nm_txq = malloc(s->nnmtxq * sizeof(struct sge_nm_txq),
1502 	    M_CXGBE, M_ZERO | M_WAITOK);
1503 #endif
1504 	MPASS(s->niq <= s->iqmap_sz);
1505 	MPASS(s->neq <= s->eqmap_sz);
1506 
1507 	s->ctrlq = malloc(nports * sizeof(struct sge_wrq), M_CXGBE,
1508 	    M_ZERO | M_WAITOK);
1509 	s->rxq = malloc(s->nrxq * sizeof(struct sge_rxq), M_CXGBE,
1510 	    M_ZERO | M_WAITOK);
1511 	s->txq = malloc(s->ntxq * sizeof(struct sge_txq), M_CXGBE,
1512 	    M_ZERO | M_WAITOK);
1513 	s->iqmap = malloc(s->iqmap_sz * sizeof(struct sge_iq *), M_CXGBE,
1514 	    M_ZERO | M_WAITOK);
1515 	s->eqmap = malloc(s->eqmap_sz * sizeof(struct sge_eq *), M_CXGBE,
1516 	    M_ZERO | M_WAITOK);
1517 
1518 	sc->irq = malloc(sc->intr_count * sizeof(struct irq), M_CXGBE,
1519 	    M_ZERO | M_WAITOK);
1520 
1521 	t4_init_l2t(sc, M_WAITOK);
1522 	t4_init_smt(sc, M_WAITOK);
1523 	t4_init_tx_sched(sc);
1524 	t4_init_atid_table(sc);
1525 #ifdef RATELIMIT
1526 	t4_init_etid_table(sc);
1527 #endif
1528 #ifdef INET6
1529 	t4_init_clip_table(sc);
1530 #endif
1531 	if (sc->vres.key.size != 0)
1532 		sc->key_map = vmem_create("T4TLS key map", sc->vres.key.start,
1533 		    sc->vres.key.size, 32, 0, M_FIRSTFIT | M_WAITOK);
1534 
1535 	/*
1536 	 * Second pass over the ports.  This time we know the number of rx and
1537 	 * tx queues that each port should get.
1538 	 */
1539 	rqidx = tqidx = 0;
1540 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1541 	ofld_tqidx = 0;
1542 #endif
1543 #ifdef TCP_OFFLOAD
1544 	ofld_rqidx = 0;
1545 #endif
1546 #ifdef DEV_NETMAP
1547 	nm_rqidx = nm_tqidx = 0;
1548 #endif
1549 	for_each_port(sc, i) {
1550 		struct port_info *pi = sc->port[i];
1551 		struct vi_info *vi;
1552 
1553 		if (pi == NULL)
1554 			continue;
1555 
1556 		pi->nvi = num_vis;
1557 		for_each_vi(pi, j, vi) {
1558 			vi->pi = pi;
1559 			vi->adapter = sc;
1560 			vi->first_intr = -1;
1561 			vi->qsize_rxq = t4_qsize_rxq;
1562 			vi->qsize_txq = t4_qsize_txq;
1563 
1564 			vi->first_rxq = rqidx;
1565 			vi->first_txq = tqidx;
1566 			vi->tmr_idx = t4_tmr_idx;
1567 			vi->pktc_idx = t4_pktc_idx;
1568 			vi->nrxq = j == 0 ? iaq.nrxq : iaq.nrxq_vi;
1569 			vi->ntxq = j == 0 ? iaq.ntxq : iaq.ntxq_vi;
1570 
1571 			rqidx += vi->nrxq;
1572 			tqidx += vi->ntxq;
1573 
1574 			if (j == 0 && vi->ntxq > 1)
1575 				vi->rsrv_noflowq = t4_rsrv_noflowq ? 1 : 0;
1576 			else
1577 				vi->rsrv_noflowq = 0;
1578 
1579 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1580 			vi->first_ofld_txq = ofld_tqidx;
1581 			vi->nofldtxq = j == 0 ? iaq.nofldtxq : iaq.nofldtxq_vi;
1582 			ofld_tqidx += vi->nofldtxq;
1583 #endif
1584 #ifdef TCP_OFFLOAD
1585 			vi->ofld_tmr_idx = t4_tmr_idx_ofld;
1586 			vi->ofld_pktc_idx = t4_pktc_idx_ofld;
1587 			vi->first_ofld_rxq = ofld_rqidx;
1588 			vi->nofldrxq = j == 0 ? iaq.nofldrxq : iaq.nofldrxq_vi;
1589 
1590 			ofld_rqidx += vi->nofldrxq;
1591 #endif
1592 #ifdef DEV_NETMAP
1593 			vi->first_nm_rxq = nm_rqidx;
1594 			vi->first_nm_txq = nm_tqidx;
1595 			if (j == 0) {
1596 				vi->nnmrxq = iaq.nnmrxq;
1597 				vi->nnmtxq = iaq.nnmtxq;
1598 			} else {
1599 				vi->nnmrxq = iaq.nnmrxq_vi;
1600 				vi->nnmtxq = iaq.nnmtxq_vi;
1601 			}
1602 			nm_rqidx += vi->nnmrxq;
1603 			nm_tqidx += vi->nnmtxq;
1604 #endif
1605 		}
1606 	}
1607 
1608 	rc = t4_setup_intr_handlers(sc);
1609 	if (rc != 0) {
1610 		device_printf(dev,
1611 		    "failed to setup interrupt handlers: %d\n", rc);
1612 		goto done;
1613 	}
1614 
1615 	rc = bus_generic_probe(dev);
1616 	if (rc != 0) {
1617 		device_printf(dev, "failed to probe child drivers: %d\n", rc);
1618 		goto done;
1619 	}
1620 
1621 	/*
1622 	 * Ensure thread-safe mailbox access (in debug builds).
1623 	 *
1624 	 * So far this was the only thread accessing the mailbox but various
1625 	 * ifnets and sysctls are about to be created and their handlers/ioctls
1626 	 * will access the mailbox from different threads.
1627 	 */
1628 	sc->flags |= CHK_MBOX_ACCESS;
1629 
1630 	rc = bus_generic_attach(dev);
1631 	if (rc != 0) {
1632 		device_printf(dev,
1633 		    "failed to attach all child ports: %d\n", rc);
1634 		goto done;
1635 	}
1636 	t4_calibration_start(sc);
1637 
1638 	device_printf(dev,
1639 	    "PCIe gen%d x%d, %d ports, %d %s interrupt%s, %d eq, %d iq\n",
1640 	    sc->params.pci.speed, sc->params.pci.width, sc->params.nports,
1641 	    sc->intr_count, sc->intr_type == INTR_MSIX ? "MSI-X" :
1642 	    (sc->intr_type == INTR_MSI ? "MSI" : "INTx"),
1643 	    sc->intr_count > 1 ? "s" : "", sc->sge.neq, sc->sge.niq);
1644 
1645 	t4_set_desc(sc);
1646 
1647 	notify_siblings(dev, 0);
1648 
1649 done:
1650 	if (rc != 0 && sc->cdev) {
1651 		/* cdev was created and so cxgbetool works; recover that way. */
1652 		device_printf(dev,
1653 		    "error during attach, adapter is now in recovery mode.\n");
1654 		rc = 0;
1655 	}
1656 
1657 	if (rc != 0)
1658 		t4_detach_common(dev);
1659 	else
1660 		t4_sysctls(sc);
1661 
1662 	return (rc);
1663 }
1664 
1665 static int
1666 t4_child_location(device_t bus, device_t dev, struct sbuf *sb)
1667 {
1668 	struct adapter *sc;
1669 	struct port_info *pi;
1670 	int i;
1671 
1672 	sc = device_get_softc(bus);
1673 	for_each_port(sc, i) {
1674 		pi = sc->port[i];
1675 		if (pi != NULL && pi->dev == dev) {
1676 			sbuf_printf(sb, "port=%d", pi->port_id);
1677 			break;
1678 		}
1679 	}
1680 	return (0);
1681 }
1682 
1683 static int
1684 t4_ready(device_t dev)
1685 {
1686 	struct adapter *sc;
1687 
1688 	sc = device_get_softc(dev);
1689 	if (sc->flags & FW_OK)
1690 		return (0);
1691 	return (ENXIO);
1692 }
1693 
1694 static int
1695 t4_read_port_device(device_t dev, int port, device_t *child)
1696 {
1697 	struct adapter *sc;
1698 	struct port_info *pi;
1699 
1700 	sc = device_get_softc(dev);
1701 	if (port < 0 || port >= MAX_NPORTS)
1702 		return (EINVAL);
1703 	pi = sc->port[port];
1704 	if (pi == NULL || pi->dev == NULL)
1705 		return (ENXIO);
1706 	*child = pi->dev;
1707 	return (0);
1708 }
1709 
1710 static int
1711 notify_siblings(device_t dev, int detaching)
1712 {
1713 	device_t sibling;
1714 	int error, i;
1715 
1716 	error = 0;
1717 	for (i = 0; i < PCI_FUNCMAX; i++) {
1718 		if (i == pci_get_function(dev))
1719 			continue;
1720 		sibling = pci_find_dbsf(pci_get_domain(dev), pci_get_bus(dev),
1721 		    pci_get_slot(dev), i);
1722 		if (sibling == NULL || !device_is_attached(sibling))
1723 			continue;
1724 		if (detaching)
1725 			error = T4_DETACH_CHILD(sibling);
1726 		else
1727 			(void)T4_ATTACH_CHILD(sibling);
1728 		if (error)
1729 			break;
1730 	}
1731 	return (error);
1732 }
1733 
1734 /*
1735  * Idempotent
1736  */
1737 static int
1738 t4_detach(device_t dev)
1739 {
1740 	int rc;
1741 
1742 	rc = notify_siblings(dev, 1);
1743 	if (rc) {
1744 		device_printf(dev,
1745 		    "failed to detach sibling devices: %d\n", rc);
1746 		return (rc);
1747 	}
1748 
1749 	return (t4_detach_common(dev));
1750 }
1751 
1752 int
1753 t4_detach_common(device_t dev)
1754 {
1755 	struct adapter *sc;
1756 	struct port_info *pi;
1757 	int i, rc;
1758 
1759 	sc = device_get_softc(dev);
1760 
1761 #ifdef TCP_OFFLOAD
1762 	rc = t4_deactivate_all_uld(sc);
1763 	if (rc) {
1764 		device_printf(dev,
1765 		    "failed to detach upper layer drivers: %d\n", rc);
1766 		return (rc);
1767 	}
1768 #endif
1769 
1770 	if (sc->cdev) {
1771 		destroy_dev(sc->cdev);
1772 		sc->cdev = NULL;
1773 	}
1774 
1775 	sx_xlock(&t4_list_lock);
1776 	SLIST_REMOVE(&t4_list, sc, adapter, link);
1777 	sx_xunlock(&t4_list_lock);
1778 
1779 	sc->flags &= ~CHK_MBOX_ACCESS;
1780 	if (sc->flags & FULL_INIT_DONE) {
1781 		if (!(sc->flags & IS_VF))
1782 			t4_intr_disable(sc);
1783 	}
1784 
1785 	if (device_is_attached(dev)) {
1786 		rc = bus_generic_detach(dev);
1787 		if (rc) {
1788 			device_printf(dev,
1789 			    "failed to detach child devices: %d\n", rc);
1790 			return (rc);
1791 		}
1792 	}
1793 
1794 	for (i = 0; i < sc->intr_count; i++)
1795 		t4_free_irq(sc, &sc->irq[i]);
1796 
1797 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1798 		t4_free_tx_sched(sc);
1799 
1800 	for (i = 0; i < MAX_NPORTS; i++) {
1801 		pi = sc->port[i];
1802 		if (pi) {
1803 			t4_free_vi(sc, sc->mbox, sc->pf, 0, pi->vi[0].viid);
1804 			if (pi->dev)
1805 				device_delete_child(dev, pi->dev);
1806 
1807 			mtx_destroy(&pi->pi_lock);
1808 			free(pi->vi, M_CXGBE);
1809 			free(pi, M_CXGBE);
1810 		}
1811 	}
1812 	callout_stop(&sc->cal_callout);
1813 	callout_drain(&sc->cal_callout);
1814 	device_delete_children(dev);
1815 	sysctl_ctx_free(&sc->ctx);
1816 	adapter_full_uninit(sc);
1817 
1818 	if ((sc->flags & (IS_VF | FW_OK)) == FW_OK)
1819 		t4_fw_bye(sc, sc->mbox);
1820 
1821 	if (sc->intr_type == INTR_MSI || sc->intr_type == INTR_MSIX)
1822 		pci_release_msi(dev);
1823 
1824 	if (sc->regs_res)
1825 		bus_release_resource(dev, SYS_RES_MEMORY, sc->regs_rid,
1826 		    sc->regs_res);
1827 
1828 	if (sc->udbs_res)
1829 		bus_release_resource(dev, SYS_RES_MEMORY, sc->udbs_rid,
1830 		    sc->udbs_res);
1831 
1832 	if (sc->msix_res)
1833 		bus_release_resource(dev, SYS_RES_MEMORY, sc->msix_rid,
1834 		    sc->msix_res);
1835 
1836 	if (sc->l2t)
1837 		t4_free_l2t(sc->l2t);
1838 	if (sc->smt)
1839 		t4_free_smt(sc->smt);
1840 	t4_free_atid_table(sc);
1841 #ifdef RATELIMIT
1842 	t4_free_etid_table(sc);
1843 #endif
1844 	if (sc->key_map)
1845 		vmem_destroy(sc->key_map);
1846 #ifdef INET6
1847 	t4_destroy_clip_table(sc);
1848 #endif
1849 
1850 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1851 	free(sc->sge.ofld_txq, M_CXGBE);
1852 #endif
1853 #ifdef TCP_OFFLOAD
1854 	free(sc->sge.ofld_rxq, M_CXGBE);
1855 #endif
1856 #ifdef DEV_NETMAP
1857 	free(sc->sge.nm_rxq, M_CXGBE);
1858 	free(sc->sge.nm_txq, M_CXGBE);
1859 #endif
1860 	free(sc->irq, M_CXGBE);
1861 	free(sc->sge.rxq, M_CXGBE);
1862 	free(sc->sge.txq, M_CXGBE);
1863 	free(sc->sge.ctrlq, M_CXGBE);
1864 	free(sc->sge.iqmap, M_CXGBE);
1865 	free(sc->sge.eqmap, M_CXGBE);
1866 	free(sc->tids.ftid_tab, M_CXGBE);
1867 	free(sc->tids.hpftid_tab, M_CXGBE);
1868 	free_hftid_hash(&sc->tids);
1869 	free(sc->tids.tid_tab, M_CXGBE);
1870 	t4_destroy_dma_tag(sc);
1871 
1872 	callout_drain(&sc->ktls_tick);
1873 	callout_drain(&sc->sfl_callout);
1874 	if (mtx_initialized(&sc->tids.ftid_lock)) {
1875 		mtx_destroy(&sc->tids.ftid_lock);
1876 		cv_destroy(&sc->tids.ftid_cv);
1877 	}
1878 	if (mtx_initialized(&sc->tids.atid_lock))
1879 		mtx_destroy(&sc->tids.atid_lock);
1880 	if (mtx_initialized(&sc->ifp_lock))
1881 		mtx_destroy(&sc->ifp_lock);
1882 
1883 	if (rw_initialized(&sc->policy_lock)) {
1884 		rw_destroy(&sc->policy_lock);
1885 #ifdef TCP_OFFLOAD
1886 		if (sc->policy != NULL)
1887 			free_offload_policy(sc->policy);
1888 #endif
1889 	}
1890 
1891 	for (i = 0; i < NUM_MEMWIN; i++) {
1892 		struct memwin *mw = &sc->memwin[i];
1893 
1894 		if (rw_initialized(&mw->mw_lock))
1895 			rw_destroy(&mw->mw_lock);
1896 	}
1897 
1898 	mtx_destroy(&sc->sfl_lock);
1899 	mtx_destroy(&sc->reg_lock);
1900 	mtx_destroy(&sc->sc_lock);
1901 
1902 	bzero(sc, sizeof(*sc));
1903 
1904 	return (0);
1905 }
1906 
1907 static inline bool
1908 ok_to_reset(struct adapter *sc)
1909 {
1910 	struct tid_info *t = &sc->tids;
1911 	struct port_info *pi;
1912 	struct vi_info *vi;
1913 	int i, j;
1914 	int caps = IFCAP_TOE | IFCAP_NETMAP | IFCAP_TXRTLMT;
1915 
1916 	if (is_t6(sc))
1917 		caps |= IFCAP_TXTLS;
1918 
1919 	ASSERT_SYNCHRONIZED_OP(sc);
1920 	MPASS(!(sc->flags & IS_VF));
1921 
1922 	for_each_port(sc, i) {
1923 		pi = sc->port[i];
1924 		for_each_vi(pi, j, vi) {
1925 			if (if_getcapenable(vi->ifp) & caps)
1926 				return (false);
1927 		}
1928 	}
1929 
1930 	if (atomic_load_int(&t->tids_in_use) > 0)
1931 		return (false);
1932 	if (atomic_load_int(&t->stids_in_use) > 0)
1933 		return (false);
1934 	if (atomic_load_int(&t->atids_in_use) > 0)
1935 		return (false);
1936 	if (atomic_load_int(&t->ftids_in_use) > 0)
1937 		return (false);
1938 	if (atomic_load_int(&t->hpftids_in_use) > 0)
1939 		return (false);
1940 	if (atomic_load_int(&t->etids_in_use) > 0)
1941 		return (false);
1942 
1943 	return (true);
1944 }
1945 
1946 static inline int
1947 stop_adapter(struct adapter *sc)
1948 {
1949 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_STOPPED)))
1950 		return (1);		/* Already stopped. */
1951 	return (t4_shutdown_adapter(sc));
1952 }
1953 
1954 static int
1955 t4_suspend(device_t dev)
1956 {
1957 	struct adapter *sc = device_get_softc(dev);
1958 	struct port_info *pi;
1959 	struct vi_info *vi;
1960 	if_t ifp;
1961 	struct sge_rxq *rxq;
1962 	struct sge_txq *txq;
1963 	struct sge_wrq *wrq;
1964 #ifdef TCP_OFFLOAD
1965 	struct sge_ofld_rxq *ofld_rxq;
1966 #endif
1967 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
1968 	struct sge_ofld_txq *ofld_txq;
1969 #endif
1970 	int rc, i, j, k;
1971 
1972 	CH_ALERT(sc, "suspend requested\n");
1973 
1974 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4sus");
1975 	if (rc != 0)
1976 		return (ENXIO);
1977 
1978 	/* XXX: Can the kernel call suspend repeatedly without resume? */
1979 	MPASS(!hw_off_limits(sc));
1980 
1981 	if (!ok_to_reset(sc)) {
1982 		/* XXX: should list what resource is preventing suspend. */
1983 		CH_ERR(sc, "not safe to suspend.\n");
1984 		rc = EBUSY;
1985 		goto done;
1986 	}
1987 
1988 	/* No more DMA or interrupts. */
1989 	stop_adapter(sc);
1990 
1991 	/* Quiesce all activity. */
1992 	for_each_port(sc, i) {
1993 		pi = sc->port[i];
1994 		pi->vxlan_tcam_entry = false;
1995 
1996 		PORT_LOCK(pi);
1997 		if (pi->up_vis > 0) {
1998 			/*
1999 			 * t4_shutdown_adapter has already shut down all the
2000 			 * PHYs but it also disables interrupts and DMA so there
2001 			 * won't be a link interrupt.  So we update the state
2002 			 * manually and inform the kernel.
2003 			 */
2004 			pi->link_cfg.link_ok = false;
2005 			t4_os_link_changed(pi);
2006 		}
2007 		PORT_UNLOCK(pi);
2008 
2009 		for_each_vi(pi, j, vi) {
2010 			vi->xact_addr_filt = -1;
2011 			mtx_lock(&vi->tick_mtx);
2012 			vi->flags |= VI_SKIP_STATS;
2013 			mtx_unlock(&vi->tick_mtx);
2014 			if (!(vi->flags & VI_INIT_DONE))
2015 				continue;
2016 
2017 			ifp = vi->ifp;
2018 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2019 				mtx_lock(&vi->tick_mtx);
2020 				callout_stop(&vi->tick);
2021 				mtx_unlock(&vi->tick_mtx);
2022 				callout_drain(&vi->tick);
2023 			}
2024 
2025 			/*
2026 			 * Note that the HW is not available.
2027 			 */
2028 			for_each_txq(vi, k, txq) {
2029 				TXQ_LOCK(txq);
2030 				txq->eq.flags &= ~(EQ_ENABLED | EQ_HW_ALLOCATED);
2031 				TXQ_UNLOCK(txq);
2032 			}
2033 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2034 			for_each_ofld_txq(vi, k, ofld_txq) {
2035 				ofld_txq->wrq.eq.flags &= ~EQ_HW_ALLOCATED;
2036 			}
2037 #endif
2038 			for_each_rxq(vi, k, rxq) {
2039 				rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2040 			}
2041 #if defined(TCP_OFFLOAD)
2042 			for_each_ofld_rxq(vi, k, ofld_rxq) {
2043 				ofld_rxq->iq.flags &= ~IQ_HW_ALLOCATED;
2044 			}
2045 #endif
2046 
2047 			quiesce_vi(vi);
2048 		}
2049 
2050 		if (sc->flags & FULL_INIT_DONE) {
2051 			/* Control queue */
2052 			wrq = &sc->sge.ctrlq[i];
2053 			wrq->eq.flags &= ~EQ_HW_ALLOCATED;
2054 			quiesce_wrq(wrq);
2055 		}
2056 	}
2057 	if (sc->flags & FULL_INIT_DONE) {
2058 		/* Firmware event queue */
2059 		sc->sge.fwq.flags &= ~IQ_HW_ALLOCATED;
2060 		quiesce_iq_fl(sc, &sc->sge.fwq, NULL);
2061 	}
2062 
2063 	/* Stop calibration */
2064 	callout_stop(&sc->cal_callout);
2065 	callout_drain(&sc->cal_callout);
2066 
2067 	/* Mark the adapter totally off limits. */
2068 	mtx_lock(&sc->reg_lock);
2069 	atomic_set_int(&sc->error_flags, HW_OFF_LIMITS);
2070 	sc->flags &= ~(FW_OK | MASTER_PF);
2071 	sc->reset_thread = NULL;
2072 	mtx_unlock(&sc->reg_lock);
2073 
2074 	if (t4_clock_gate_on_suspend) {
2075 		t4_set_reg_field(sc, A_PMU_PART_CG_PWRMODE, F_MA_PART_CGEN |
2076 		    F_LE_PART_CGEN | F_EDC1_PART_CGEN | F_EDC0_PART_CGEN |
2077 		    F_TP_PART_CGEN | F_PDP_PART_CGEN | F_SGE_PART_CGEN, 0);
2078 	}
2079 
2080 	CH_ALERT(sc, "suspend completed.\n");
2081 done:
2082 	end_synchronized_op(sc, 0);
2083 	return (rc);
2084 }
2085 
2086 struct adapter_pre_reset_state {
2087 	u_int flags;
2088 	uint16_t nbmcaps;
2089 	uint16_t linkcaps;
2090 	uint16_t switchcaps;
2091 	uint16_t niccaps;
2092 	uint16_t toecaps;
2093 	uint16_t rdmacaps;
2094 	uint16_t cryptocaps;
2095 	uint16_t iscsicaps;
2096 	uint16_t fcoecaps;
2097 
2098 	u_int cfcsum;
2099 	char cfg_file[32];
2100 
2101 	struct adapter_params params;
2102 	struct t4_virt_res vres;
2103 	struct tid_info tids;
2104 	struct sge sge;
2105 
2106 	int rawf_base;
2107 	int nrawf;
2108 
2109 };
2110 
2111 static void
2112 save_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2113 {
2114 
2115 	ASSERT_SYNCHRONIZED_OP(sc);
2116 
2117 	o->flags = sc->flags;
2118 
2119 	o->nbmcaps =  sc->nbmcaps;
2120 	o->linkcaps = sc->linkcaps;
2121 	o->switchcaps = sc->switchcaps;
2122 	o->niccaps = sc->niccaps;
2123 	o->toecaps = sc->toecaps;
2124 	o->rdmacaps = sc->rdmacaps;
2125 	o->cryptocaps = sc->cryptocaps;
2126 	o->iscsicaps = sc->iscsicaps;
2127 	o->fcoecaps = sc->fcoecaps;
2128 
2129 	o->cfcsum = sc->cfcsum;
2130 	MPASS(sizeof(o->cfg_file) == sizeof(sc->cfg_file));
2131 	memcpy(o->cfg_file, sc->cfg_file, sizeof(o->cfg_file));
2132 
2133 	o->params = sc->params;
2134 	o->vres = sc->vres;
2135 	o->tids = sc->tids;
2136 	o->sge = sc->sge;
2137 
2138 	o->rawf_base = sc->rawf_base;
2139 	o->nrawf = sc->nrawf;
2140 }
2141 
2142 static int
2143 compare_caps_and_params(struct adapter *sc, struct adapter_pre_reset_state *o)
2144 {
2145 	int rc = 0;
2146 
2147 	ASSERT_SYNCHRONIZED_OP(sc);
2148 
2149 	/* Capabilities */
2150 #define COMPARE_CAPS(c) do { \
2151 	if (o->c##caps != sc->c##caps) { \
2152 		CH_ERR(sc, "%scaps 0x%04x -> 0x%04x.\n", #c, o->c##caps, \
2153 		    sc->c##caps); \
2154 		rc = EINVAL; \
2155 	} \
2156 } while (0)
2157 	COMPARE_CAPS(nbm);
2158 	COMPARE_CAPS(link);
2159 	COMPARE_CAPS(switch);
2160 	COMPARE_CAPS(nic);
2161 	COMPARE_CAPS(toe);
2162 	COMPARE_CAPS(rdma);
2163 	COMPARE_CAPS(crypto);
2164 	COMPARE_CAPS(iscsi);
2165 	COMPARE_CAPS(fcoe);
2166 #undef COMPARE_CAPS
2167 
2168 	/* Firmware config file */
2169 	if (o->cfcsum != sc->cfcsum) {
2170 		CH_ERR(sc, "config file %s (0x%x) -> %s (0x%x)\n", o->cfg_file,
2171 		    o->cfcsum, sc->cfg_file, sc->cfcsum);
2172 		rc = EINVAL;
2173 	}
2174 
2175 #define COMPARE_PARAM(p, name) do { \
2176 	if (o->p != sc->p) { \
2177 		CH_ERR(sc, #name " %d -> %d\n", o->p, sc->p); \
2178 		rc = EINVAL; \
2179 	} \
2180 } while (0)
2181 	COMPARE_PARAM(sge.iq_start, iq_start);
2182 	COMPARE_PARAM(sge.eq_start, eq_start);
2183 	COMPARE_PARAM(tids.ftid_base, ftid_base);
2184 	COMPARE_PARAM(tids.ftid_end, ftid_end);
2185 	COMPARE_PARAM(tids.nftids, nftids);
2186 	COMPARE_PARAM(vres.l2t.start, l2t_start);
2187 	COMPARE_PARAM(vres.l2t.size, l2t_size);
2188 	COMPARE_PARAM(sge.iqmap_sz, iqmap_sz);
2189 	COMPARE_PARAM(sge.eqmap_sz, eqmap_sz);
2190 	COMPARE_PARAM(tids.tid_base, tid_base);
2191 	COMPARE_PARAM(tids.hpftid_base, hpftid_base);
2192 	COMPARE_PARAM(tids.hpftid_end, hpftid_end);
2193 	COMPARE_PARAM(tids.nhpftids, nhpftids);
2194 	COMPARE_PARAM(rawf_base, rawf_base);
2195 	COMPARE_PARAM(nrawf, nrawf);
2196 	COMPARE_PARAM(params.mps_bg_map, mps_bg_map);
2197 	COMPARE_PARAM(params.filter2_wr_support, filter2_wr_support);
2198 	COMPARE_PARAM(params.ulptx_memwrite_dsgl, ulptx_memwrite_dsgl);
2199 	COMPARE_PARAM(params.fr_nsmr_tpte_wr_support, fr_nsmr_tpte_wr_support);
2200 	COMPARE_PARAM(params.max_pkts_per_eth_tx_pkts_wr, max_pkts_per_eth_tx_pkts_wr);
2201 	COMPARE_PARAM(tids.ntids, ntids);
2202 	COMPARE_PARAM(tids.etid_base, etid_base);
2203 	COMPARE_PARAM(tids.etid_end, etid_end);
2204 	COMPARE_PARAM(tids.netids, netids);
2205 	COMPARE_PARAM(params.eo_wr_cred, eo_wr_cred);
2206 	COMPARE_PARAM(params.ethoffload, ethoffload);
2207 	COMPARE_PARAM(tids.natids, natids);
2208 	COMPARE_PARAM(tids.stid_base, stid_base);
2209 	COMPARE_PARAM(vres.ddp.start, ddp_start);
2210 	COMPARE_PARAM(vres.ddp.size, ddp_size);
2211 	COMPARE_PARAM(params.ofldq_wr_cred, ofldq_wr_cred);
2212 	COMPARE_PARAM(vres.stag.start, stag_start);
2213 	COMPARE_PARAM(vres.stag.size, stag_size);
2214 	COMPARE_PARAM(vres.rq.start, rq_start);
2215 	COMPARE_PARAM(vres.rq.size, rq_size);
2216 	COMPARE_PARAM(vres.pbl.start, pbl_start);
2217 	COMPARE_PARAM(vres.pbl.size, pbl_size);
2218 	COMPARE_PARAM(vres.qp.start, qp_start);
2219 	COMPARE_PARAM(vres.qp.size, qp_size);
2220 	COMPARE_PARAM(vres.cq.start, cq_start);
2221 	COMPARE_PARAM(vres.cq.size, cq_size);
2222 	COMPARE_PARAM(vres.ocq.start, ocq_start);
2223 	COMPARE_PARAM(vres.ocq.size, ocq_size);
2224 	COMPARE_PARAM(vres.srq.start, srq_start);
2225 	COMPARE_PARAM(vres.srq.size, srq_size);
2226 	COMPARE_PARAM(params.max_ordird_qp, max_ordird_qp);
2227 	COMPARE_PARAM(params.max_ird_adapter, max_ird_adapter);
2228 	COMPARE_PARAM(vres.iscsi.start, iscsi_start);
2229 	COMPARE_PARAM(vres.iscsi.size, iscsi_size);
2230 	COMPARE_PARAM(vres.key.start, key_start);
2231 	COMPARE_PARAM(vres.key.size, key_size);
2232 #undef COMPARE_PARAM
2233 
2234 	return (rc);
2235 }
2236 
2237 static int
2238 t4_resume(device_t dev)
2239 {
2240 	struct adapter *sc = device_get_softc(dev);
2241 	struct adapter_pre_reset_state *old_state = NULL;
2242 	struct port_info *pi;
2243 	struct vi_info *vi;
2244 	if_t ifp;
2245 	struct sge_txq *txq;
2246 	int rc, i, j, k;
2247 
2248 	CH_ALERT(sc, "resume requested.\n");
2249 
2250 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4res");
2251 	if (rc != 0)
2252 		return (ENXIO);
2253 	MPASS(hw_off_limits(sc));
2254 	MPASS((sc->flags & FW_OK) == 0);
2255 	MPASS((sc->flags & MASTER_PF) == 0);
2256 	MPASS(sc->reset_thread == NULL);
2257 	sc->reset_thread = curthread;
2258 
2259 	/* Register access is expected to work by the time we're here. */
2260 	if (t4_read_reg(sc, A_PL_WHOAMI) == 0xffffffff) {
2261 		CH_ERR(sc, "%s: can't read device registers\n", __func__);
2262 		rc = ENXIO;
2263 		goto done;
2264 	}
2265 
2266 	/* Note that HW_OFF_LIMITS is cleared a bit later. */
2267 	atomic_clear_int(&sc->error_flags, ADAP_FATAL_ERR | ADAP_STOPPED);
2268 
2269 	/* Restore memory window. */
2270 	setup_memwin(sc);
2271 
2272 	/* Go no further if recovery mode has been requested. */
2273 	if (TUNABLE_INT_FETCH("hw.cxgbe.sos", &i) && i != 0) {
2274 		CH_ALERT(sc, "recovery mode on resume.\n");
2275 		rc = 0;
2276 		mtx_lock(&sc->reg_lock);
2277 		atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2278 		mtx_unlock(&sc->reg_lock);
2279 		goto done;
2280 	}
2281 
2282 	old_state = malloc(sizeof(*old_state), M_CXGBE, M_ZERO | M_WAITOK);
2283 	save_caps_and_params(sc, old_state);
2284 
2285 	/* Reestablish contact with firmware and become the primary PF. */
2286 	rc = contact_firmware(sc);
2287 	if (rc != 0)
2288 		goto done; /* error message displayed already */
2289 	MPASS(sc->flags & FW_OK);
2290 
2291 	if (sc->flags & MASTER_PF) {
2292 		rc = partition_resources(sc);
2293 		if (rc != 0)
2294 			goto done; /* error message displayed already */
2295 		t4_intr_clear(sc);
2296 	}
2297 
2298 	rc = get_params__post_init(sc);
2299 	if (rc != 0)
2300 		goto done; /* error message displayed already */
2301 
2302 	rc = set_params__post_init(sc);
2303 	if (rc != 0)
2304 		goto done; /* error message displayed already */
2305 
2306 	rc = compare_caps_and_params(sc, old_state);
2307 	if (rc != 0)
2308 		goto done; /* error message displayed already */
2309 
2310 	for_each_port(sc, i) {
2311 		pi = sc->port[i];
2312 		MPASS(pi != NULL);
2313 		MPASS(pi->vi != NULL);
2314 		MPASS(pi->vi[0].dev == pi->dev);
2315 
2316 		rc = -t4_port_init(sc, sc->mbox, sc->pf, 0, i);
2317 		if (rc != 0) {
2318 			CH_ERR(sc,
2319 			    "failed to re-initialize port %d: %d\n", i, rc);
2320 			goto done;
2321 		}
2322 		MPASS(sc->chan_map[pi->tx_chan] == i);
2323 
2324 		PORT_LOCK(pi);
2325 		fixup_link_config(pi);
2326 		build_medialist(pi);
2327 		PORT_UNLOCK(pi);
2328 		for_each_vi(pi, j, vi) {
2329 			if (IS_MAIN_VI(vi))
2330 				continue;
2331 			rc = alloc_extra_vi(sc, pi, vi);
2332 			if (rc != 0) {
2333 				CH_ERR(vi,
2334 				    "failed to re-allocate extra VI: %d\n", rc);
2335 				goto done;
2336 			}
2337 		}
2338 	}
2339 
2340 	/*
2341 	 * Interrupts and queues are about to be enabled and other threads will
2342 	 * want to access the hardware too.  It is safe to do so.  Note that
2343 	 * this thread is still in the middle of a synchronized_op.
2344 	 */
2345 	mtx_lock(&sc->reg_lock);
2346 	atomic_clear_int(&sc->error_flags, HW_OFF_LIMITS);
2347 	mtx_unlock(&sc->reg_lock);
2348 
2349 	if (sc->flags & FULL_INIT_DONE) {
2350 		rc = adapter_full_init(sc);
2351 		if (rc != 0) {
2352 			CH_ERR(sc, "failed to re-initialize adapter: %d\n", rc);
2353 			goto done;
2354 		}
2355 
2356 		if (sc->vxlan_refcount > 0)
2357 			enable_vxlan_rx(sc);
2358 
2359 		for_each_port(sc, i) {
2360 			pi = sc->port[i];
2361 			for_each_vi(pi, j, vi) {
2362 				mtx_lock(&vi->tick_mtx);
2363 				vi->flags &= ~VI_SKIP_STATS;
2364 				mtx_unlock(&vi->tick_mtx);
2365 				if (!(vi->flags & VI_INIT_DONE))
2366 					continue;
2367 				rc = vi_full_init(vi);
2368 				if (rc != 0) {
2369 					CH_ERR(vi, "failed to re-initialize "
2370 					    "interface: %d\n", rc);
2371 					goto done;
2372 				}
2373 
2374 				ifp = vi->ifp;
2375 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2376 					continue;
2377 				/*
2378 				 * Note that we do not setup multicast addresses
2379 				 * in the first pass.  This ensures that the
2380 				 * unicast DMACs for all VIs on all ports get an
2381 				 * MPS TCAM entry.
2382 				 */
2383 				rc = update_mac_settings(ifp, XGMAC_ALL &
2384 				    ~XGMAC_MCADDRS);
2385 				if (rc != 0) {
2386 					CH_ERR(vi, "failed to re-configure MAC: %d\n", rc);
2387 					goto done;
2388 				}
2389 				rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true,
2390 				    true);
2391 				if (rc != 0) {
2392 					CH_ERR(vi, "failed to re-enable VI: %d\n", rc);
2393 					goto done;
2394 				}
2395 				for_each_txq(vi, k, txq) {
2396 					TXQ_LOCK(txq);
2397 					txq->eq.flags |= EQ_ENABLED;
2398 					TXQ_UNLOCK(txq);
2399 				}
2400 				mtx_lock(&vi->tick_mtx);
2401 				callout_schedule(&vi->tick, hz);
2402 				mtx_unlock(&vi->tick_mtx);
2403 			}
2404 			PORT_LOCK(pi);
2405 			if (pi->up_vis > 0) {
2406 				t4_update_port_info(pi);
2407 				fixup_link_config(pi);
2408 				build_medialist(pi);
2409 				apply_link_config(pi);
2410 				if (pi->link_cfg.link_ok)
2411 					t4_os_link_changed(pi);
2412 			}
2413 			PORT_UNLOCK(pi);
2414 		}
2415 
2416 		/* Now reprogram the L2 multicast addresses. */
2417 		for_each_port(sc, i) {
2418 			pi = sc->port[i];
2419 			for_each_vi(pi, j, vi) {
2420 				if (!(vi->flags & VI_INIT_DONE))
2421 					continue;
2422 				ifp = vi->ifp;
2423 				if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING))
2424 					continue;
2425 				rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2426 				if (rc != 0) {
2427 					CH_ERR(vi, "failed to re-configure MCAST MACs: %d\n", rc);
2428 					rc = 0;	/* carry on */
2429 				}
2430 			}
2431 		}
2432 	}
2433 
2434 	/* Reset all calibration */
2435 	t4_calibration_start(sc);
2436 
2437 done:
2438 	if (rc == 0) {
2439 		sc->incarnation++;
2440 		CH_ALERT(sc, "resume completed.\n");
2441 	}
2442 	end_synchronized_op(sc, 0);
2443 	free(old_state, M_CXGBE);
2444 	return (rc);
2445 }
2446 
2447 static int
2448 t4_reset_prepare(device_t dev, device_t child)
2449 {
2450 	struct adapter *sc = device_get_softc(dev);
2451 
2452 	CH_ALERT(sc, "reset_prepare.\n");
2453 	return (0);
2454 }
2455 
2456 static int
2457 t4_reset_post(device_t dev, device_t child)
2458 {
2459 	struct adapter *sc = device_get_softc(dev);
2460 
2461 	CH_ALERT(sc, "reset_post.\n");
2462 	return (0);
2463 }
2464 
2465 static int
2466 reset_adapter(struct adapter *sc)
2467 {
2468 	int rc, oldinc, error_flags;
2469 
2470 	CH_ALERT(sc, "reset requested.\n");
2471 
2472 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst1");
2473 	if (rc != 0)
2474 		return (EBUSY);
2475 
2476 	if (hw_off_limits(sc)) {
2477 		CH_ERR(sc, "adapter is suspended, use resume (not reset).\n");
2478 		rc = ENXIO;
2479 		goto done;
2480 	}
2481 
2482 	if (!ok_to_reset(sc)) {
2483 		/* XXX: should list what resource is preventing reset. */
2484 		CH_ERR(sc, "not safe to reset.\n");
2485 		rc = EBUSY;
2486 		goto done;
2487 	}
2488 
2489 done:
2490 	oldinc = sc->incarnation;
2491 	end_synchronized_op(sc, 0);
2492 	if (rc != 0)
2493 		return (rc);	/* Error logged already. */
2494 
2495 	atomic_add_int(&sc->num_resets, 1);
2496 	mtx_lock(&Giant);
2497 	rc = BUS_RESET_CHILD(device_get_parent(sc->dev), sc->dev, 0);
2498 	mtx_unlock(&Giant);
2499 	if (rc != 0)
2500 		CH_ERR(sc, "bus_reset_child failed: %d.\n", rc);
2501 	else {
2502 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4rst2");
2503 		if (rc != 0)
2504 			return (EBUSY);
2505 		error_flags = atomic_load_int(&sc->error_flags);
2506 		if (sc->incarnation > oldinc && error_flags == 0) {
2507 			CH_ALERT(sc, "bus_reset_child succeeded.\n");
2508 		} else {
2509 			CH_ERR(sc, "adapter did not reset properly, flags "
2510 			    "0x%08x, error_flags 0x%08x.\n", sc->flags,
2511 			    error_flags);
2512 			rc = ENXIO;
2513 		}
2514 		end_synchronized_op(sc, 0);
2515 	}
2516 
2517 	return (rc);
2518 }
2519 
2520 static void
2521 reset_adapter_task(void *arg, int pending)
2522 {
2523 	/* XXX: t4_async_event here? */
2524 	reset_adapter(arg);
2525 }
2526 
2527 static int
2528 cxgbe_probe(device_t dev)
2529 {
2530 	char buf[128];
2531 	struct port_info *pi = device_get_softc(dev);
2532 
2533 	snprintf(buf, sizeof(buf), "port %d", pi->port_id);
2534 	device_set_desc_copy(dev, buf);
2535 
2536 	return (BUS_PROBE_DEFAULT);
2537 }
2538 
2539 #define T4_CAP (IFCAP_VLAN_HWTAGGING | IFCAP_VLAN_MTU | IFCAP_HWCSUM | \
2540     IFCAP_VLAN_HWCSUM | IFCAP_TSO | IFCAP_JUMBO_MTU | IFCAP_LRO | \
2541     IFCAP_VLAN_HWTSO | IFCAP_LINKSTATE | IFCAP_HWCSUM_IPV6 | IFCAP_HWSTATS | \
2542     IFCAP_HWRXTSTMP | IFCAP_MEXTPG)
2543 #define T4_CAP_ENABLE (T4_CAP)
2544 
2545 static int
2546 cxgbe_vi_attach(device_t dev, struct vi_info *vi)
2547 {
2548 	if_t ifp;
2549 	struct sbuf *sb;
2550 	struct sysctl_ctx_list *ctx = &vi->ctx;
2551 	struct sysctl_oid_list *children;
2552 	struct pfil_head_args pa;
2553 	struct adapter *sc = vi->adapter;
2554 
2555 	sysctl_ctx_init(ctx);
2556 	children = SYSCTL_CHILDREN(device_get_sysctl_tree(vi->dev));
2557 	vi->rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rxq",
2558 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC rx queues");
2559 	vi->txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "txq",
2560 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "NIC tx queues");
2561 #ifdef DEV_NETMAP
2562 	vi->nm_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_rxq",
2563 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap rx queues");
2564 	vi->nm_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "nm_txq",
2565 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "netmap tx queues");
2566 #endif
2567 #ifdef TCP_OFFLOAD
2568 	vi->ofld_rxq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_rxq",
2569 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE rx queues");
2570 #endif
2571 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2572 	vi->ofld_txq_oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "ofld_txq",
2573 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE/ETHOFLD tx queues");
2574 #endif
2575 
2576 	vi->xact_addr_filt = -1;
2577 	mtx_init(&vi->tick_mtx, "vi tick", NULL, MTX_DEF);
2578 	callout_init_mtx(&vi->tick, &vi->tick_mtx, 0);
2579 	if (sc->flags & IS_VF || t4_tx_vm_wr != 0)
2580 		vi->flags |= TX_USES_VM_WR;
2581 
2582 	/* Allocate an ifnet and set it up */
2583 	ifp = if_alloc_dev(IFT_ETHER, dev);
2584 	if (ifp == NULL) {
2585 		device_printf(dev, "Cannot allocate ifnet\n");
2586 		return (ENOMEM);
2587 	}
2588 	vi->ifp = ifp;
2589 	if_setsoftc(ifp, vi);
2590 
2591 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
2592 	if_setflags(ifp, IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST);
2593 
2594 	if_setinitfn(ifp, cxgbe_init);
2595 	if_setioctlfn(ifp, cxgbe_ioctl);
2596 	if_settransmitfn(ifp, cxgbe_transmit);
2597 	if_setqflushfn(ifp, cxgbe_qflush);
2598 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
2599 		if_setgetcounterfn(ifp, vi_get_counter);
2600 	else
2601 		if_setgetcounterfn(ifp, cxgbe_get_counter);
2602 #if defined(KERN_TLS) || defined(RATELIMIT)
2603 	if_setsndtagallocfn(ifp, cxgbe_snd_tag_alloc);
2604 #endif
2605 #ifdef RATELIMIT
2606 	if_setratelimitqueryfn(ifp, cxgbe_ratelimit_query);
2607 #endif
2608 
2609 	if_setcapabilities(ifp, T4_CAP);
2610 	if_setcapenable(ifp, T4_CAP_ENABLE);
2611 	if_sethwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP | CSUM_TSO |
2612 	    CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2613 	if (chip_id(sc) >= CHELSIO_T6) {
2614 		if_setcapabilitiesbit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2615 		if_setcapenablebit(ifp, IFCAP_VXLAN_HWCSUM | IFCAP_VXLAN_HWTSO, 0);
2616 		if_sethwassistbits(ifp, CSUM_INNER_IP6_UDP | CSUM_INNER_IP6_TCP |
2617 		    CSUM_INNER_IP6_TSO | CSUM_INNER_IP | CSUM_INNER_IP_UDP |
2618 		    CSUM_INNER_IP_TCP | CSUM_INNER_IP_TSO | CSUM_ENCAP_VXLAN, 0);
2619 	}
2620 
2621 #ifdef TCP_OFFLOAD
2622 	if (vi->nofldrxq != 0)
2623 		if_setcapabilitiesbit(ifp, IFCAP_TOE, 0);
2624 #endif
2625 #ifdef RATELIMIT
2626 	if (is_ethoffload(sc) && vi->nofldtxq != 0) {
2627 		if_setcapabilitiesbit(ifp, IFCAP_TXRTLMT, 0);
2628 		if_setcapenablebit(ifp, IFCAP_TXRTLMT, 0);
2629 	}
2630 #endif
2631 
2632 	if_sethwtsomax(ifp, IP_MAXPACKET);
2633 	if (vi->flags & TX_USES_VM_WR)
2634 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_VM_TSO);
2635 	else
2636 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_TSO);
2637 #ifdef RATELIMIT
2638 	if (is_ethoffload(sc) && vi->nofldtxq != 0)
2639 		if_sethwtsomaxsegcount(ifp, TX_SGL_SEGS_EO_TSO);
2640 #endif
2641 	if_sethwtsomaxsegsize(ifp, 65536);
2642 #ifdef KERN_TLS
2643 	if (is_ktls(sc)) {
2644 		if_setcapabilitiesbit(ifp, IFCAP_TXTLS, 0);
2645 		if (sc->flags & KERN_TLS_ON || !is_t6(sc))
2646 			if_setcapenablebit(ifp, IFCAP_TXTLS, 0);
2647 	}
2648 #endif
2649 
2650 	ether_ifattach(ifp, vi->hw_addr);
2651 #ifdef DEV_NETMAP
2652 	if (vi->nnmrxq != 0)
2653 		cxgbe_nm_attach(vi);
2654 #endif
2655 	sb = sbuf_new_auto();
2656 	sbuf_printf(sb, "%d txq, %d rxq (NIC)", vi->ntxq, vi->nrxq);
2657 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
2658 	switch (if_getcapabilities(ifp) & (IFCAP_TOE | IFCAP_TXRTLMT)) {
2659 	case IFCAP_TOE:
2660 		sbuf_printf(sb, "; %d txq (TOE)", vi->nofldtxq);
2661 		break;
2662 	case IFCAP_TOE | IFCAP_TXRTLMT:
2663 		sbuf_printf(sb, "; %d txq (TOE/ETHOFLD)", vi->nofldtxq);
2664 		break;
2665 	case IFCAP_TXRTLMT:
2666 		sbuf_printf(sb, "; %d txq (ETHOFLD)", vi->nofldtxq);
2667 		break;
2668 	}
2669 #endif
2670 #ifdef TCP_OFFLOAD
2671 	if (if_getcapabilities(ifp) & IFCAP_TOE)
2672 		sbuf_printf(sb, ", %d rxq (TOE)", vi->nofldrxq);
2673 #endif
2674 #ifdef DEV_NETMAP
2675 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2676 		sbuf_printf(sb, "; %d txq, %d rxq (netmap)",
2677 		    vi->nnmtxq, vi->nnmrxq);
2678 #endif
2679 	sbuf_finish(sb);
2680 	device_printf(dev, "%s\n", sbuf_data(sb));
2681 	sbuf_delete(sb);
2682 
2683 	vi_sysctls(vi);
2684 
2685 	pa.pa_version = PFIL_VERSION;
2686 	pa.pa_flags = PFIL_IN;
2687 	pa.pa_type = PFIL_TYPE_ETHERNET;
2688 	pa.pa_headname = if_name(ifp);
2689 	vi->pfil = pfil_head_register(&pa);
2690 
2691 	return (0);
2692 }
2693 
2694 static int
2695 cxgbe_attach(device_t dev)
2696 {
2697 	struct port_info *pi = device_get_softc(dev);
2698 	struct adapter *sc = pi->adapter;
2699 	struct vi_info *vi;
2700 	int i, rc;
2701 
2702 	sysctl_ctx_init(&pi->ctx);
2703 
2704 	rc = cxgbe_vi_attach(dev, &pi->vi[0]);
2705 	if (rc)
2706 		return (rc);
2707 
2708 	for_each_vi(pi, i, vi) {
2709 		if (i == 0)
2710 			continue;
2711 		vi->dev = device_add_child(dev, sc->names->vi_ifnet_name, -1);
2712 		if (vi->dev == NULL) {
2713 			device_printf(dev, "failed to add VI %d\n", i);
2714 			continue;
2715 		}
2716 		device_set_softc(vi->dev, vi);
2717 	}
2718 
2719 	cxgbe_sysctls(pi);
2720 
2721 	bus_generic_attach(dev);
2722 
2723 	return (0);
2724 }
2725 
2726 static void
2727 cxgbe_vi_detach(struct vi_info *vi)
2728 {
2729 	if_t ifp = vi->ifp;
2730 
2731 	if (vi->pfil != NULL) {
2732 		pfil_head_unregister(vi->pfil);
2733 		vi->pfil = NULL;
2734 	}
2735 
2736 	ether_ifdetach(ifp);
2737 
2738 	/* Let detach proceed even if these fail. */
2739 #ifdef DEV_NETMAP
2740 	if (if_getcapabilities(ifp) & IFCAP_NETMAP)
2741 		cxgbe_nm_detach(vi);
2742 #endif
2743 	cxgbe_uninit_synchronized(vi);
2744 	callout_drain(&vi->tick);
2745 	mtx_destroy(&vi->tick_mtx);
2746 	sysctl_ctx_free(&vi->ctx);
2747 	vi_full_uninit(vi);
2748 
2749 	if_free(vi->ifp);
2750 	vi->ifp = NULL;
2751 }
2752 
2753 static int
2754 cxgbe_detach(device_t dev)
2755 {
2756 	struct port_info *pi = device_get_softc(dev);
2757 	struct adapter *sc = pi->adapter;
2758 	int rc;
2759 
2760 	/* Detach the extra VIs first. */
2761 	rc = bus_generic_detach(dev);
2762 	if (rc)
2763 		return (rc);
2764 	device_delete_children(dev);
2765 
2766 	sysctl_ctx_free(&pi->ctx);
2767 	begin_vi_detach(sc, &pi->vi[0]);
2768 	if (pi->flags & HAS_TRACEQ) {
2769 		sc->traceq = -1;	/* cloner should not create ifnet */
2770 		t4_tracer_port_detach(sc);
2771 	}
2772 	cxgbe_vi_detach(&pi->vi[0]);
2773 	ifmedia_removeall(&pi->media);
2774 	end_vi_detach(sc, &pi->vi[0]);
2775 
2776 	return (0);
2777 }
2778 
2779 static void
2780 cxgbe_init(void *arg)
2781 {
2782 	struct vi_info *vi = arg;
2783 	struct adapter *sc = vi->adapter;
2784 
2785 	if (begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4init") != 0)
2786 		return;
2787 	cxgbe_init_synchronized(vi);
2788 	end_synchronized_op(sc, 0);
2789 }
2790 
2791 static int
2792 cxgbe_ioctl(if_t ifp, unsigned long cmd, caddr_t data)
2793 {
2794 	int rc = 0, mtu, flags;
2795 	struct vi_info *vi = if_getsoftc(ifp);
2796 	struct port_info *pi = vi->pi;
2797 	struct adapter *sc = pi->adapter;
2798 	struct ifreq *ifr = (struct ifreq *)data;
2799 	uint32_t mask;
2800 
2801 	switch (cmd) {
2802 	case SIOCSIFMTU:
2803 		mtu = ifr->ifr_mtu;
2804 		if (mtu < ETHERMIN || mtu > MAX_MTU)
2805 			return (EINVAL);
2806 
2807 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4mtu");
2808 		if (rc)
2809 			return (rc);
2810 		if_setmtu(ifp, mtu);
2811 		if (vi->flags & VI_INIT_DONE) {
2812 			t4_update_fl_bufsize(ifp);
2813 			if (!hw_off_limits(sc) &&
2814 			    if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2815 				rc = update_mac_settings(ifp, XGMAC_MTU);
2816 		}
2817 		end_synchronized_op(sc, 0);
2818 		break;
2819 
2820 	case SIOCSIFFLAGS:
2821 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4flg");
2822 		if (rc)
2823 			return (rc);
2824 
2825 		if (hw_off_limits(sc)) {
2826 			rc = ENXIO;
2827 			goto fail;
2828 		}
2829 
2830 		if (if_getflags(ifp) & IFF_UP) {
2831 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2832 				flags = vi->if_flags;
2833 				if ((if_getflags(ifp) ^ flags) &
2834 				    (IFF_PROMISC | IFF_ALLMULTI)) {
2835 					rc = update_mac_settings(ifp,
2836 					    XGMAC_PROMISC | XGMAC_ALLMULTI);
2837 				}
2838 			} else {
2839 				rc = cxgbe_init_synchronized(vi);
2840 			}
2841 			vi->if_flags = if_getflags(ifp);
2842 		} else if (if_getdrvflags(ifp) & IFF_DRV_RUNNING) {
2843 			rc = cxgbe_uninit_synchronized(vi);
2844 		}
2845 		end_synchronized_op(sc, 0);
2846 		break;
2847 
2848 	case SIOCADDMULTI:
2849 	case SIOCDELMULTI:
2850 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4multi");
2851 		if (rc)
2852 			return (rc);
2853 		if (!hw_off_limits(sc) && if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2854 			rc = update_mac_settings(ifp, XGMAC_MCADDRS);
2855 		end_synchronized_op(sc, 0);
2856 		break;
2857 
2858 	case SIOCSIFCAP:
2859 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4cap");
2860 		if (rc)
2861 			return (rc);
2862 
2863 		mask = ifr->ifr_reqcap ^ if_getcapenable(ifp);
2864 		if (mask & IFCAP_TXCSUM) {
2865 			if_togglecapenable(ifp, IFCAP_TXCSUM);
2866 			if_togglehwassist(ifp, CSUM_TCP | CSUM_UDP | CSUM_IP);
2867 
2868 			if (IFCAP_TSO4 & if_getcapenable(ifp) &&
2869 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2870 				mask &= ~IFCAP_TSO4;
2871 				if_setcapenablebit(ifp, 0, IFCAP_TSO4);
2872 				if_printf(ifp,
2873 				    "tso4 disabled due to -txcsum.\n");
2874 			}
2875 		}
2876 		if (mask & IFCAP_TXCSUM_IPV6) {
2877 			if_togglecapenable(ifp, IFCAP_TXCSUM_IPV6);
2878 			if_togglehwassist(ifp, CSUM_UDP_IPV6 | CSUM_TCP_IPV6);
2879 
2880 			if (IFCAP_TSO6 & if_getcapenable(ifp) &&
2881 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2882 				mask &= ~IFCAP_TSO6;
2883 				if_setcapenablebit(ifp, 0, IFCAP_TSO6);
2884 				if_printf(ifp,
2885 				    "tso6 disabled due to -txcsum6.\n");
2886 			}
2887 		}
2888 		if (mask & IFCAP_RXCSUM)
2889 			if_togglecapenable(ifp, IFCAP_RXCSUM);
2890 		if (mask & IFCAP_RXCSUM_IPV6)
2891 			if_togglecapenable(ifp, IFCAP_RXCSUM_IPV6);
2892 
2893 		/*
2894 		 * Note that we leave CSUM_TSO alone (it is always set).  The
2895 		 * kernel takes both IFCAP_TSOx and CSUM_TSO into account before
2896 		 * sending a TSO request our way, so it's sufficient to toggle
2897 		 * IFCAP_TSOx only.
2898 		 */
2899 		if (mask & IFCAP_TSO4) {
2900 			if (!(IFCAP_TSO4 & if_getcapenable(ifp)) &&
2901 			    !(IFCAP_TXCSUM & if_getcapenable(ifp))) {
2902 				if_printf(ifp, "enable txcsum first.\n");
2903 				rc = EAGAIN;
2904 				goto fail;
2905 			}
2906 			if_togglecapenable(ifp, IFCAP_TSO4);
2907 		}
2908 		if (mask & IFCAP_TSO6) {
2909 			if (!(IFCAP_TSO6 & if_getcapenable(ifp)) &&
2910 			    !(IFCAP_TXCSUM_IPV6 & if_getcapenable(ifp))) {
2911 				if_printf(ifp, "enable txcsum6 first.\n");
2912 				rc = EAGAIN;
2913 				goto fail;
2914 			}
2915 			if_togglecapenable(ifp, IFCAP_TSO6);
2916 		}
2917 		if (mask & IFCAP_LRO) {
2918 #if defined(INET) || defined(INET6)
2919 			int i;
2920 			struct sge_rxq *rxq;
2921 
2922 			if_togglecapenable(ifp, IFCAP_LRO);
2923 			for_each_rxq(vi, i, rxq) {
2924 				if (if_getcapenable(ifp) & IFCAP_LRO)
2925 					rxq->iq.flags |= IQ_LRO_ENABLED;
2926 				else
2927 					rxq->iq.flags &= ~IQ_LRO_ENABLED;
2928 			}
2929 #endif
2930 		}
2931 #ifdef TCP_OFFLOAD
2932 		if (mask & IFCAP_TOE) {
2933 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TOE;
2934 
2935 			rc = toe_capability(vi, enable);
2936 			if (rc != 0)
2937 				goto fail;
2938 
2939 			if_togglecapenable(ifp, mask);
2940 		}
2941 #endif
2942 		if (mask & IFCAP_VLAN_HWTAGGING) {
2943 			if_togglecapenable(ifp, IFCAP_VLAN_HWTAGGING);
2944 			if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
2945 				rc = update_mac_settings(ifp, XGMAC_VLANEX);
2946 		}
2947 		if (mask & IFCAP_VLAN_MTU) {
2948 			if_togglecapenable(ifp, IFCAP_VLAN_MTU);
2949 
2950 			/* Need to find out how to disable auto-mtu-inflation */
2951 		}
2952 		if (mask & IFCAP_VLAN_HWTSO)
2953 			if_togglecapenable(ifp, IFCAP_VLAN_HWTSO);
2954 		if (mask & IFCAP_VLAN_HWCSUM)
2955 			if_togglecapenable(ifp, IFCAP_VLAN_HWCSUM);
2956 #ifdef RATELIMIT
2957 		if (mask & IFCAP_TXRTLMT)
2958 			if_togglecapenable(ifp, IFCAP_TXRTLMT);
2959 #endif
2960 		if (mask & IFCAP_HWRXTSTMP) {
2961 			int i;
2962 			struct sge_rxq *rxq;
2963 
2964 			if_togglecapenable(ifp, IFCAP_HWRXTSTMP);
2965 			for_each_rxq(vi, i, rxq) {
2966 				if (if_getcapenable(ifp) & IFCAP_HWRXTSTMP)
2967 					rxq->iq.flags |= IQ_RX_TIMESTAMP;
2968 				else
2969 					rxq->iq.flags &= ~IQ_RX_TIMESTAMP;
2970 			}
2971 		}
2972 		if (mask & IFCAP_MEXTPG)
2973 			if_togglecapenable(ifp, IFCAP_MEXTPG);
2974 
2975 #ifdef KERN_TLS
2976 		if (mask & IFCAP_TXTLS) {
2977 			int enable = (if_getcapenable(ifp) ^ mask) & IFCAP_TXTLS;
2978 
2979 			rc = ktls_capability(sc, enable);
2980 			if (rc != 0)
2981 				goto fail;
2982 
2983 			if_togglecapenable(ifp, mask & IFCAP_TXTLS);
2984 		}
2985 #endif
2986 		if (mask & IFCAP_VXLAN_HWCSUM) {
2987 			if_togglecapenable(ifp, IFCAP_VXLAN_HWCSUM);
2988 			if_togglehwassist(ifp, CSUM_INNER_IP6_UDP |
2989 			    CSUM_INNER_IP6_TCP | CSUM_INNER_IP |
2990 			    CSUM_INNER_IP_UDP | CSUM_INNER_IP_TCP);
2991 		}
2992 		if (mask & IFCAP_VXLAN_HWTSO) {
2993 			if_togglecapenable(ifp, IFCAP_VXLAN_HWTSO);
2994 			if_togglehwassist(ifp, CSUM_INNER_IP6_TSO |
2995 			    CSUM_INNER_IP_TSO);
2996 		}
2997 
2998 #ifdef VLAN_CAPABILITIES
2999 		VLAN_CAPABILITIES(ifp);
3000 #endif
3001 fail:
3002 		end_synchronized_op(sc, 0);
3003 		break;
3004 
3005 	case SIOCSIFMEDIA:
3006 	case SIOCGIFMEDIA:
3007 	case SIOCGIFXMEDIA:
3008 		rc = ifmedia_ioctl(ifp, ifr, &pi->media, cmd);
3009 		break;
3010 
3011 	case SIOCGI2C: {
3012 		struct ifi2creq i2c;
3013 
3014 		rc = copyin(ifr_data_get_ptr(ifr), &i2c, sizeof(i2c));
3015 		if (rc != 0)
3016 			break;
3017 		if (i2c.dev_addr != 0xA0 && i2c.dev_addr != 0xA2) {
3018 			rc = EPERM;
3019 			break;
3020 		}
3021 		if (i2c.len > sizeof(i2c.data)) {
3022 			rc = EINVAL;
3023 			break;
3024 		}
3025 		rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4i2c");
3026 		if (rc)
3027 			return (rc);
3028 		if (hw_off_limits(sc))
3029 			rc = ENXIO;
3030 		else
3031 			rc = -t4_i2c_rd(sc, sc->mbox, pi->port_id, i2c.dev_addr,
3032 			    i2c.offset, i2c.len, &i2c.data[0]);
3033 		end_synchronized_op(sc, 0);
3034 		if (rc == 0)
3035 			rc = copyout(&i2c, ifr_data_get_ptr(ifr), sizeof(i2c));
3036 		break;
3037 	}
3038 
3039 	default:
3040 		rc = ether_ioctl(ifp, cmd, data);
3041 	}
3042 
3043 	return (rc);
3044 }
3045 
3046 static int
3047 cxgbe_transmit(if_t ifp, struct mbuf *m)
3048 {
3049 	struct vi_info *vi = if_getsoftc(ifp);
3050 	struct port_info *pi = vi->pi;
3051 	struct adapter *sc;
3052 	struct sge_txq *txq;
3053 	void *items[1];
3054 	int rc;
3055 
3056 	M_ASSERTPKTHDR(m);
3057 	MPASS(m->m_nextpkt == NULL);	/* not quite ready for this yet */
3058 #if defined(KERN_TLS) || defined(RATELIMIT)
3059 	if (m->m_pkthdr.csum_flags & CSUM_SND_TAG)
3060 		MPASS(m->m_pkthdr.snd_tag->ifp == ifp);
3061 #endif
3062 
3063 	if (__predict_false(pi->link_cfg.link_ok == false)) {
3064 		m_freem(m);
3065 		return (ENETDOWN);
3066 	}
3067 
3068 	rc = parse_pkt(&m, vi->flags & TX_USES_VM_WR);
3069 	if (__predict_false(rc != 0)) {
3070 		if (__predict_true(rc == EINPROGRESS)) {
3071 			/* queued by parse_pkt */
3072 			MPASS(m != NULL);
3073 			return (0);
3074 		}
3075 
3076 		MPASS(m == NULL);			/* was freed already */
3077 		atomic_add_int(&pi->tx_parse_error, 1);	/* rare, atomic is ok */
3078 		return (rc);
3079 	}
3080 
3081 	/* Select a txq. */
3082 	sc = vi->adapter;
3083 	txq = &sc->sge.txq[vi->first_txq];
3084 	if (M_HASHTYPE_GET(m) != M_HASHTYPE_NONE)
3085 		txq += ((m->m_pkthdr.flowid % (vi->ntxq - vi->rsrv_noflowq)) +
3086 		    vi->rsrv_noflowq);
3087 
3088 	items[0] = m;
3089 	rc = mp_ring_enqueue(txq->r, items, 1, 256);
3090 	if (__predict_false(rc != 0))
3091 		m_freem(m);
3092 
3093 	return (rc);
3094 }
3095 
3096 static void
3097 cxgbe_qflush(if_t ifp)
3098 {
3099 	struct vi_info *vi = if_getsoftc(ifp);
3100 	struct sge_txq *txq;
3101 	int i;
3102 
3103 	/* queues do not exist if !VI_INIT_DONE. */
3104 	if (vi->flags & VI_INIT_DONE) {
3105 		for_each_txq(vi, i, txq) {
3106 			TXQ_LOCK(txq);
3107 			txq->eq.flags |= EQ_QFLUSH;
3108 			TXQ_UNLOCK(txq);
3109 			while (!mp_ring_is_idle(txq->r)) {
3110 				mp_ring_check_drainage(txq->r, 4096);
3111 				pause("qflush", 1);
3112 			}
3113 			TXQ_LOCK(txq);
3114 			txq->eq.flags &= ~EQ_QFLUSH;
3115 			TXQ_UNLOCK(txq);
3116 		}
3117 	}
3118 	if_qflush(ifp);
3119 }
3120 
3121 static uint64_t
3122 vi_get_counter(if_t ifp, ift_counter c)
3123 {
3124 	struct vi_info *vi = if_getsoftc(ifp);
3125 	struct fw_vi_stats_vf *s = &vi->stats;
3126 
3127 	mtx_lock(&vi->tick_mtx);
3128 	vi_refresh_stats(vi);
3129 	mtx_unlock(&vi->tick_mtx);
3130 
3131 	switch (c) {
3132 	case IFCOUNTER_IPACKETS:
3133 		return (s->rx_bcast_frames + s->rx_mcast_frames +
3134 		    s->rx_ucast_frames);
3135 	case IFCOUNTER_IERRORS:
3136 		return (s->rx_err_frames);
3137 	case IFCOUNTER_OPACKETS:
3138 		return (s->tx_bcast_frames + s->tx_mcast_frames +
3139 		    s->tx_ucast_frames + s->tx_offload_frames);
3140 	case IFCOUNTER_OERRORS:
3141 		return (s->tx_drop_frames);
3142 	case IFCOUNTER_IBYTES:
3143 		return (s->rx_bcast_bytes + s->rx_mcast_bytes +
3144 		    s->rx_ucast_bytes);
3145 	case IFCOUNTER_OBYTES:
3146 		return (s->tx_bcast_bytes + s->tx_mcast_bytes +
3147 		    s->tx_ucast_bytes + s->tx_offload_bytes);
3148 	case IFCOUNTER_IMCASTS:
3149 		return (s->rx_mcast_frames);
3150 	case IFCOUNTER_OMCASTS:
3151 		return (s->tx_mcast_frames);
3152 	case IFCOUNTER_OQDROPS: {
3153 		uint64_t drops;
3154 
3155 		drops = 0;
3156 		if (vi->flags & VI_INIT_DONE) {
3157 			int i;
3158 			struct sge_txq *txq;
3159 
3160 			for_each_txq(vi, i, txq)
3161 				drops += counter_u64_fetch(txq->r->dropped);
3162 		}
3163 
3164 		return (drops);
3165 
3166 	}
3167 
3168 	default:
3169 		return (if_get_counter_default(ifp, c));
3170 	}
3171 }
3172 
3173 static uint64_t
3174 cxgbe_get_counter(if_t ifp, ift_counter c)
3175 {
3176 	struct vi_info *vi = if_getsoftc(ifp);
3177 	struct port_info *pi = vi->pi;
3178 	struct port_stats *s = &pi->stats;
3179 
3180 	mtx_lock(&vi->tick_mtx);
3181 	cxgbe_refresh_stats(vi);
3182 	mtx_unlock(&vi->tick_mtx);
3183 
3184 	switch (c) {
3185 	case IFCOUNTER_IPACKETS:
3186 		return (s->rx_frames);
3187 
3188 	case IFCOUNTER_IERRORS:
3189 		return (s->rx_jabber + s->rx_runt + s->rx_too_long +
3190 		    s->rx_fcs_err + s->rx_len_err);
3191 
3192 	case IFCOUNTER_OPACKETS:
3193 		return (s->tx_frames);
3194 
3195 	case IFCOUNTER_OERRORS:
3196 		return (s->tx_error_frames);
3197 
3198 	case IFCOUNTER_IBYTES:
3199 		return (s->rx_octets);
3200 
3201 	case IFCOUNTER_OBYTES:
3202 		return (s->tx_octets);
3203 
3204 	case IFCOUNTER_IMCASTS:
3205 		return (s->rx_mcast_frames);
3206 
3207 	case IFCOUNTER_OMCASTS:
3208 		return (s->tx_mcast_frames);
3209 
3210 	case IFCOUNTER_IQDROPS:
3211 		return (s->rx_ovflow0 + s->rx_ovflow1 + s->rx_ovflow2 +
3212 		    s->rx_ovflow3 + s->rx_trunc0 + s->rx_trunc1 + s->rx_trunc2 +
3213 		    s->rx_trunc3 + pi->tnl_cong_drops);
3214 
3215 	case IFCOUNTER_OQDROPS: {
3216 		uint64_t drops;
3217 
3218 		drops = s->tx_drop;
3219 		if (vi->flags & VI_INIT_DONE) {
3220 			int i;
3221 			struct sge_txq *txq;
3222 
3223 			for_each_txq(vi, i, txq)
3224 				drops += counter_u64_fetch(txq->r->dropped);
3225 		}
3226 
3227 		return (drops);
3228 
3229 	}
3230 
3231 	default:
3232 		return (if_get_counter_default(ifp, c));
3233 	}
3234 }
3235 
3236 #if defined(KERN_TLS) || defined(RATELIMIT)
3237 static int
3238 cxgbe_snd_tag_alloc(if_t ifp, union if_snd_tag_alloc_params *params,
3239     struct m_snd_tag **pt)
3240 {
3241 	int error;
3242 
3243 	switch (params->hdr.type) {
3244 #ifdef RATELIMIT
3245 	case IF_SND_TAG_TYPE_RATE_LIMIT:
3246 		error = cxgbe_rate_tag_alloc(ifp, params, pt);
3247 		break;
3248 #endif
3249 #ifdef KERN_TLS
3250 	case IF_SND_TAG_TYPE_TLS:
3251 	{
3252 		struct vi_info *vi = if_getsoftc(ifp);
3253 
3254 		if (is_t6(vi->pi->adapter))
3255 			error = t6_tls_tag_alloc(ifp, params, pt);
3256 		else
3257 			error = EOPNOTSUPP;
3258 		break;
3259 	}
3260 #endif
3261 	default:
3262 		error = EOPNOTSUPP;
3263 	}
3264 	return (error);
3265 }
3266 #endif
3267 
3268 /*
3269  * The kernel picks a media from the list we had provided but we still validate
3270  * the requeste.
3271  */
3272 int
3273 cxgbe_media_change(if_t ifp)
3274 {
3275 	struct vi_info *vi = if_getsoftc(ifp);
3276 	struct port_info *pi = vi->pi;
3277 	struct ifmedia *ifm = &pi->media;
3278 	struct link_config *lc = &pi->link_cfg;
3279 	struct adapter *sc = pi->adapter;
3280 	int rc;
3281 
3282 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mec");
3283 	if (rc != 0)
3284 		return (rc);
3285 	PORT_LOCK(pi);
3286 	if (IFM_SUBTYPE(ifm->ifm_media) == IFM_AUTO) {
3287 		/* ifconfig .. media autoselect */
3288 		if (!(lc->pcaps & FW_PORT_CAP32_ANEG)) {
3289 			rc = ENOTSUP; /* AN not supported by transceiver */
3290 			goto done;
3291 		}
3292 		lc->requested_aneg = AUTONEG_ENABLE;
3293 		lc->requested_speed = 0;
3294 		lc->requested_fc |= PAUSE_AUTONEG;
3295 	} else {
3296 		lc->requested_aneg = AUTONEG_DISABLE;
3297 		lc->requested_speed =
3298 		    ifmedia_baudrate(ifm->ifm_media) / 1000000;
3299 		lc->requested_fc = 0;
3300 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_RXPAUSE)
3301 			lc->requested_fc |= PAUSE_RX;
3302 		if (IFM_OPTIONS(ifm->ifm_media) & IFM_ETH_TXPAUSE)
3303 			lc->requested_fc |= PAUSE_TX;
3304 	}
3305 	if (pi->up_vis > 0 && !hw_off_limits(sc)) {
3306 		fixup_link_config(pi);
3307 		rc = apply_link_config(pi);
3308 	}
3309 done:
3310 	PORT_UNLOCK(pi);
3311 	end_synchronized_op(sc, 0);
3312 	return (rc);
3313 }
3314 
3315 /*
3316  * Base media word (without ETHER, pause, link active, etc.) for the port at the
3317  * given speed.
3318  */
3319 static int
3320 port_mword(struct port_info *pi, uint32_t speed)
3321 {
3322 
3323 	MPASS(speed & M_FW_PORT_CAP32_SPEED);
3324 	MPASS(powerof2(speed));
3325 
3326 	switch(pi->port_type) {
3327 	case FW_PORT_TYPE_BT_SGMII:
3328 	case FW_PORT_TYPE_BT_XFI:
3329 	case FW_PORT_TYPE_BT_XAUI:
3330 		/* BaseT */
3331 		switch (speed) {
3332 		case FW_PORT_CAP32_SPEED_100M:
3333 			return (IFM_100_T);
3334 		case FW_PORT_CAP32_SPEED_1G:
3335 			return (IFM_1000_T);
3336 		case FW_PORT_CAP32_SPEED_10G:
3337 			return (IFM_10G_T);
3338 		}
3339 		break;
3340 	case FW_PORT_TYPE_KX4:
3341 		if (speed == FW_PORT_CAP32_SPEED_10G)
3342 			return (IFM_10G_KX4);
3343 		break;
3344 	case FW_PORT_TYPE_CX4:
3345 		if (speed == FW_PORT_CAP32_SPEED_10G)
3346 			return (IFM_10G_CX4);
3347 		break;
3348 	case FW_PORT_TYPE_KX:
3349 		if (speed == FW_PORT_CAP32_SPEED_1G)
3350 			return (IFM_1000_KX);
3351 		break;
3352 	case FW_PORT_TYPE_KR:
3353 	case FW_PORT_TYPE_BP_AP:
3354 	case FW_PORT_TYPE_BP4_AP:
3355 	case FW_PORT_TYPE_BP40_BA:
3356 	case FW_PORT_TYPE_KR4_100G:
3357 	case FW_PORT_TYPE_KR_SFP28:
3358 	case FW_PORT_TYPE_KR_XLAUI:
3359 		switch (speed) {
3360 		case FW_PORT_CAP32_SPEED_1G:
3361 			return (IFM_1000_KX);
3362 		case FW_PORT_CAP32_SPEED_10G:
3363 			return (IFM_10G_KR);
3364 		case FW_PORT_CAP32_SPEED_25G:
3365 			return (IFM_25G_KR);
3366 		case FW_PORT_CAP32_SPEED_40G:
3367 			return (IFM_40G_KR4);
3368 		case FW_PORT_CAP32_SPEED_50G:
3369 			return (IFM_50G_KR2);
3370 		case FW_PORT_CAP32_SPEED_100G:
3371 			return (IFM_100G_KR4);
3372 		}
3373 		break;
3374 	case FW_PORT_TYPE_FIBER_XFI:
3375 	case FW_PORT_TYPE_FIBER_XAUI:
3376 	case FW_PORT_TYPE_SFP:
3377 	case FW_PORT_TYPE_QSFP_10G:
3378 	case FW_PORT_TYPE_QSA:
3379 	case FW_PORT_TYPE_QSFP:
3380 	case FW_PORT_TYPE_CR4_QSFP:
3381 	case FW_PORT_TYPE_CR_QSFP:
3382 	case FW_PORT_TYPE_CR2_QSFP:
3383 	case FW_PORT_TYPE_SFP28:
3384 		/* Pluggable transceiver */
3385 		switch (pi->mod_type) {
3386 		case FW_PORT_MOD_TYPE_LR:
3387 			switch (speed) {
3388 			case FW_PORT_CAP32_SPEED_1G:
3389 				return (IFM_1000_LX);
3390 			case FW_PORT_CAP32_SPEED_10G:
3391 				return (IFM_10G_LR);
3392 			case FW_PORT_CAP32_SPEED_25G:
3393 				return (IFM_25G_LR);
3394 			case FW_PORT_CAP32_SPEED_40G:
3395 				return (IFM_40G_LR4);
3396 			case FW_PORT_CAP32_SPEED_50G:
3397 				return (IFM_50G_LR2);
3398 			case FW_PORT_CAP32_SPEED_100G:
3399 				return (IFM_100G_LR4);
3400 			}
3401 			break;
3402 		case FW_PORT_MOD_TYPE_SR:
3403 			switch (speed) {
3404 			case FW_PORT_CAP32_SPEED_1G:
3405 				return (IFM_1000_SX);
3406 			case FW_PORT_CAP32_SPEED_10G:
3407 				return (IFM_10G_SR);
3408 			case FW_PORT_CAP32_SPEED_25G:
3409 				return (IFM_25G_SR);
3410 			case FW_PORT_CAP32_SPEED_40G:
3411 				return (IFM_40G_SR4);
3412 			case FW_PORT_CAP32_SPEED_50G:
3413 				return (IFM_50G_SR2);
3414 			case FW_PORT_CAP32_SPEED_100G:
3415 				return (IFM_100G_SR4);
3416 			}
3417 			break;
3418 		case FW_PORT_MOD_TYPE_ER:
3419 			if (speed == FW_PORT_CAP32_SPEED_10G)
3420 				return (IFM_10G_ER);
3421 			break;
3422 		case FW_PORT_MOD_TYPE_TWINAX_PASSIVE:
3423 		case FW_PORT_MOD_TYPE_TWINAX_ACTIVE:
3424 			switch (speed) {
3425 			case FW_PORT_CAP32_SPEED_1G:
3426 				return (IFM_1000_CX);
3427 			case FW_PORT_CAP32_SPEED_10G:
3428 				return (IFM_10G_TWINAX);
3429 			case FW_PORT_CAP32_SPEED_25G:
3430 				return (IFM_25G_CR);
3431 			case FW_PORT_CAP32_SPEED_40G:
3432 				return (IFM_40G_CR4);
3433 			case FW_PORT_CAP32_SPEED_50G:
3434 				return (IFM_50G_CR2);
3435 			case FW_PORT_CAP32_SPEED_100G:
3436 				return (IFM_100G_CR4);
3437 			}
3438 			break;
3439 		case FW_PORT_MOD_TYPE_LRM:
3440 			if (speed == FW_PORT_CAP32_SPEED_10G)
3441 				return (IFM_10G_LRM);
3442 			break;
3443 		case FW_PORT_MOD_TYPE_NA:
3444 			MPASS(0);	/* Not pluggable? */
3445 			/* fall throough */
3446 		case FW_PORT_MOD_TYPE_ERROR:
3447 		case FW_PORT_MOD_TYPE_UNKNOWN:
3448 		case FW_PORT_MOD_TYPE_NOTSUPPORTED:
3449 			break;
3450 		case FW_PORT_MOD_TYPE_NONE:
3451 			return (IFM_NONE);
3452 		}
3453 		break;
3454 	case FW_PORT_TYPE_NONE:
3455 		return (IFM_NONE);
3456 	}
3457 
3458 	return (IFM_UNKNOWN);
3459 }
3460 
3461 void
3462 cxgbe_media_status(if_t ifp, struct ifmediareq *ifmr)
3463 {
3464 	struct vi_info *vi = if_getsoftc(ifp);
3465 	struct port_info *pi = vi->pi;
3466 	struct adapter *sc = pi->adapter;
3467 	struct link_config *lc = &pi->link_cfg;
3468 
3469 	if (begin_synchronized_op(sc, vi , SLEEP_OK | INTR_OK, "t4med") != 0)
3470 		return;
3471 	PORT_LOCK(pi);
3472 
3473 	if (pi->up_vis == 0 && !hw_off_limits(sc)) {
3474 		/*
3475 		 * If all the interfaces are administratively down the firmware
3476 		 * does not report transceiver changes.  Refresh port info here
3477 		 * so that ifconfig displays accurate ifmedia at all times.
3478 		 * This is the only reason we have a synchronized op in this
3479 		 * function.  Just PORT_LOCK would have been enough otherwise.
3480 		 */
3481 		t4_update_port_info(pi);
3482 		build_medialist(pi);
3483 	}
3484 
3485 	/* ifm_status */
3486 	ifmr->ifm_status = IFM_AVALID;
3487 	if (lc->link_ok == false)
3488 		goto done;
3489 	ifmr->ifm_status |= IFM_ACTIVE;
3490 
3491 	/* ifm_active */
3492 	ifmr->ifm_active = IFM_ETHER | IFM_FDX;
3493 	ifmr->ifm_active &= ~(IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE);
3494 	if (lc->fc & PAUSE_RX)
3495 		ifmr->ifm_active |= IFM_ETH_RXPAUSE;
3496 	if (lc->fc & PAUSE_TX)
3497 		ifmr->ifm_active |= IFM_ETH_TXPAUSE;
3498 	ifmr->ifm_active |= port_mword(pi, speed_to_fwcap(lc->speed));
3499 done:
3500 	PORT_UNLOCK(pi);
3501 	end_synchronized_op(sc, 0);
3502 }
3503 
3504 static int
3505 vcxgbe_probe(device_t dev)
3506 {
3507 	char buf[128];
3508 	struct vi_info *vi = device_get_softc(dev);
3509 
3510 	snprintf(buf, sizeof(buf), "port %d vi %td", vi->pi->port_id,
3511 	    vi - vi->pi->vi);
3512 	device_set_desc_copy(dev, buf);
3513 
3514 	return (BUS_PROBE_DEFAULT);
3515 }
3516 
3517 static int
3518 alloc_extra_vi(struct adapter *sc, struct port_info *pi, struct vi_info *vi)
3519 {
3520 	int func, index, rc;
3521 	uint32_t param, val;
3522 
3523 	ASSERT_SYNCHRONIZED_OP(sc);
3524 
3525 	index = vi - pi->vi;
3526 	MPASS(index > 0);	/* This function deals with _extra_ VIs only */
3527 	KASSERT(index < nitems(vi_mac_funcs),
3528 	    ("%s: VI %s doesn't have a MAC func", __func__,
3529 	    device_get_nameunit(vi->dev)));
3530 	func = vi_mac_funcs[index];
3531 	rc = t4_alloc_vi_func(sc, sc->mbox, pi->tx_chan, sc->pf, 0, 1,
3532 	    vi->hw_addr, &vi->rss_size, &vi->vfvld, &vi->vin, func, 0);
3533 	if (rc < 0) {
3534 		CH_ERR(vi, "failed to allocate virtual interface %d"
3535 		    "for port %d: %d\n", index, pi->port_id, -rc);
3536 		return (-rc);
3537 	}
3538 	vi->viid = rc;
3539 
3540 	if (vi->rss_size == 1) {
3541 		/*
3542 		 * This VI didn't get a slice of the RSS table.  Reduce the
3543 		 * number of VIs being created (hw.cxgbe.num_vis) or modify the
3544 		 * configuration file (nvi, rssnvi for this PF) if this is a
3545 		 * problem.
3546 		 */
3547 		device_printf(vi->dev, "RSS table not available.\n");
3548 		vi->rss_base = 0xffff;
3549 
3550 		return (0);
3551 	}
3552 
3553 	param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
3554 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_RSSINFO) |
3555 	    V_FW_PARAMS_PARAM_YZ(vi->viid);
3556 	rc = t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
3557 	if (rc)
3558 		vi->rss_base = 0xffff;
3559 	else {
3560 		MPASS((val >> 16) == vi->rss_size);
3561 		vi->rss_base = val & 0xffff;
3562 	}
3563 
3564 	return (0);
3565 }
3566 
3567 static int
3568 vcxgbe_attach(device_t dev)
3569 {
3570 	struct vi_info *vi;
3571 	struct port_info *pi;
3572 	struct adapter *sc;
3573 	int rc;
3574 
3575 	vi = device_get_softc(dev);
3576 	pi = vi->pi;
3577 	sc = pi->adapter;
3578 
3579 	rc = begin_synchronized_op(sc, vi, SLEEP_OK | INTR_OK, "t4via");
3580 	if (rc)
3581 		return (rc);
3582 	rc = alloc_extra_vi(sc, pi, vi);
3583 	end_synchronized_op(sc, 0);
3584 	if (rc)
3585 		return (rc);
3586 
3587 	rc = cxgbe_vi_attach(dev, vi);
3588 	if (rc) {
3589 		t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3590 		return (rc);
3591 	}
3592 	return (0);
3593 }
3594 
3595 static int
3596 vcxgbe_detach(device_t dev)
3597 {
3598 	struct vi_info *vi;
3599 	struct adapter *sc;
3600 
3601 	vi = device_get_softc(dev);
3602 	sc = vi->adapter;
3603 
3604 	begin_vi_detach(sc, vi);
3605 	cxgbe_vi_detach(vi);
3606 	t4_free_vi(sc, sc->mbox, sc->pf, 0, vi->viid);
3607 	end_vi_detach(sc, vi);
3608 
3609 	return (0);
3610 }
3611 
3612 static struct callout fatal_callout;
3613 static struct taskqueue *reset_tq;
3614 
3615 static void
3616 delayed_panic(void *arg)
3617 {
3618 	struct adapter *sc = arg;
3619 
3620 	panic("%s: panic on fatal error", device_get_nameunit(sc->dev));
3621 }
3622 
3623 static void
3624 fatal_error_task(void *arg, int pending)
3625 {
3626 	struct adapter *sc = arg;
3627 	int rc;
3628 
3629 #ifdef TCP_OFFLOAD
3630 	t4_async_event(sc);
3631 #endif
3632 	if (atomic_testandclear_int(&sc->error_flags, ilog2(ADAP_CIM_ERR))) {
3633 		dump_cim_regs(sc);
3634 		dump_cimla(sc);
3635 		dump_devlog(sc);
3636 	}
3637 
3638 	if (t4_reset_on_fatal_err) {
3639 		CH_ALERT(sc, "resetting on fatal error.\n");
3640 		rc = reset_adapter(sc);
3641 		if (rc == 0 && t4_panic_on_fatal_err) {
3642 			CH_ALERT(sc, "reset was successful, "
3643 			    "system will NOT panic.\n");
3644 			return;
3645 		}
3646 	}
3647 
3648 	if (t4_panic_on_fatal_err) {
3649 		CH_ALERT(sc, "panicking on fatal error (after 30s).\n");
3650 		callout_reset(&fatal_callout, hz * 30, delayed_panic, sc);
3651 	}
3652 }
3653 
3654 void
3655 t4_fatal_err(struct adapter *sc, bool fw_error)
3656 {
3657 	const bool verbose = (sc->debug_flags & DF_VERBOSE_SLOWINTR) != 0;
3658 
3659 	stop_adapter(sc);
3660 	if (atomic_testandset_int(&sc->error_flags, ilog2(ADAP_FATAL_ERR)))
3661 		return;
3662 	if (fw_error) {
3663 		/*
3664 		 * We are here because of a firmware error/timeout and not
3665 		 * because of a hardware interrupt.  It is possible (although
3666 		 * not very likely) that an error interrupt was also raised but
3667 		 * this thread ran first and inhibited t4_intr_err.  We walk the
3668 		 * main INT_CAUSE registers here to make sure we haven't missed
3669 		 * anything interesting.
3670 		 */
3671 		t4_slow_intr_handler(sc, verbose);
3672 		atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
3673 	}
3674 	t4_report_fw_error(sc);
3675 	log(LOG_ALERT, "%s: encountered fatal error, adapter stopped (%d).\n",
3676 	    device_get_nameunit(sc->dev), fw_error);
3677 	taskqueue_enqueue(reset_tq, &sc->fatal_error_task);
3678 }
3679 
3680 void
3681 t4_add_adapter(struct adapter *sc)
3682 {
3683 	sx_xlock(&t4_list_lock);
3684 	SLIST_INSERT_HEAD(&t4_list, sc, link);
3685 	sx_xunlock(&t4_list_lock);
3686 }
3687 
3688 int
3689 t4_map_bars_0_and_4(struct adapter *sc)
3690 {
3691 	sc->regs_rid = PCIR_BAR(0);
3692 	sc->regs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3693 	    &sc->regs_rid, RF_ACTIVE);
3694 	if (sc->regs_res == NULL) {
3695 		device_printf(sc->dev, "cannot map registers.\n");
3696 		return (ENXIO);
3697 	}
3698 	sc->bt = rman_get_bustag(sc->regs_res);
3699 	sc->bh = rman_get_bushandle(sc->regs_res);
3700 	sc->mmio_len = rman_get_size(sc->regs_res);
3701 	setbit(&sc->doorbells, DOORBELL_KDB);
3702 
3703 	sc->msix_rid = PCIR_BAR(4);
3704 	sc->msix_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3705 	    &sc->msix_rid, RF_ACTIVE);
3706 	if (sc->msix_res == NULL) {
3707 		device_printf(sc->dev, "cannot map MSI-X BAR.\n");
3708 		return (ENXIO);
3709 	}
3710 
3711 	return (0);
3712 }
3713 
3714 int
3715 t4_map_bar_2(struct adapter *sc)
3716 {
3717 
3718 	/*
3719 	 * T4: only iWARP driver uses the userspace doorbells.  There is no need
3720 	 * to map it if RDMA is disabled.
3721 	 */
3722 	if (is_t4(sc) && sc->rdmacaps == 0)
3723 		return (0);
3724 
3725 	sc->udbs_rid = PCIR_BAR(2);
3726 	sc->udbs_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
3727 	    &sc->udbs_rid, RF_ACTIVE);
3728 	if (sc->udbs_res == NULL) {
3729 		device_printf(sc->dev, "cannot map doorbell BAR.\n");
3730 		return (ENXIO);
3731 	}
3732 	sc->udbs_base = rman_get_virtual(sc->udbs_res);
3733 
3734 	if (chip_id(sc) >= CHELSIO_T5) {
3735 		setbit(&sc->doorbells, DOORBELL_UDB);
3736 #if defined(__i386__) || defined(__amd64__)
3737 		if (t5_write_combine) {
3738 			int rc, mode;
3739 
3740 			/*
3741 			 * Enable write combining on BAR2.  This is the
3742 			 * userspace doorbell BAR and is split into 128B
3743 			 * (UDBS_SEG_SIZE) doorbell regions, each associated
3744 			 * with an egress queue.  The first 64B has the doorbell
3745 			 * and the second 64B can be used to submit a tx work
3746 			 * request with an implicit doorbell.
3747 			 */
3748 
3749 			rc = pmap_change_attr((vm_offset_t)sc->udbs_base,
3750 			    rman_get_size(sc->udbs_res), PAT_WRITE_COMBINING);
3751 			if (rc == 0) {
3752 				clrbit(&sc->doorbells, DOORBELL_UDB);
3753 				setbit(&sc->doorbells, DOORBELL_WCWR);
3754 				setbit(&sc->doorbells, DOORBELL_UDBWC);
3755 			} else {
3756 				device_printf(sc->dev,
3757 				    "couldn't enable write combining: %d\n",
3758 				    rc);
3759 			}
3760 
3761 			mode = is_t5(sc) ? V_STATMODE(0) : V_T6_STATMODE(0);
3762 			t4_write_reg(sc, A_SGE_STAT_CFG,
3763 			    V_STATSOURCE_T5(7) | mode);
3764 		}
3765 #endif
3766 	}
3767 	sc->iwt.wc_en = isset(&sc->doorbells, DOORBELL_UDBWC) ? 1 : 0;
3768 
3769 	return (0);
3770 }
3771 
3772 struct memwin_init {
3773 	uint32_t base;
3774 	uint32_t aperture;
3775 };
3776 
3777 static const struct memwin_init t4_memwin[NUM_MEMWIN] = {
3778 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3779 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3780 	{ MEMWIN2_BASE_T4, MEMWIN2_APERTURE_T4 }
3781 };
3782 
3783 static const struct memwin_init t5_memwin[NUM_MEMWIN] = {
3784 	{ MEMWIN0_BASE, MEMWIN0_APERTURE },
3785 	{ MEMWIN1_BASE, MEMWIN1_APERTURE },
3786 	{ MEMWIN2_BASE_T5, MEMWIN2_APERTURE_T5 },
3787 };
3788 
3789 static void
3790 setup_memwin(struct adapter *sc)
3791 {
3792 	const struct memwin_init *mw_init;
3793 	struct memwin *mw;
3794 	int i;
3795 	uint32_t bar0;
3796 
3797 	if (is_t4(sc)) {
3798 		/*
3799 		 * Read low 32b of bar0 indirectly via the hardware backdoor
3800 		 * mechanism.  Works from within PCI passthrough environments
3801 		 * too, where rman_get_start() can return a different value.  We
3802 		 * need to program the T4 memory window decoders with the actual
3803 		 * addresses that will be coming across the PCIe link.
3804 		 */
3805 		bar0 = t4_hw_pci_read_cfg4(sc, PCIR_BAR(0));
3806 		bar0 &= (uint32_t) PCIM_BAR_MEM_BASE;
3807 
3808 		mw_init = &t4_memwin[0];
3809 	} else {
3810 		/* T5+ use the relative offset inside the PCIe BAR */
3811 		bar0 = 0;
3812 
3813 		mw_init = &t5_memwin[0];
3814 	}
3815 
3816 	for (i = 0, mw = &sc->memwin[0]; i < NUM_MEMWIN; i++, mw_init++, mw++) {
3817 		if (!rw_initialized(&mw->mw_lock)) {
3818 			rw_init(&mw->mw_lock, "memory window access");
3819 			mw->mw_base = mw_init->base;
3820 			mw->mw_aperture = mw_init->aperture;
3821 			mw->mw_curpos = 0;
3822 		}
3823 		t4_write_reg(sc,
3824 		    PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, i),
3825 		    (mw->mw_base + bar0) | V_BIR(0) |
3826 		    V_WINDOW(ilog2(mw->mw_aperture) - 10));
3827 		rw_wlock(&mw->mw_lock);
3828 		position_memwin(sc, i, mw->mw_curpos);
3829 		rw_wunlock(&mw->mw_lock);
3830 	}
3831 
3832 	/* flush */
3833 	t4_read_reg(sc, PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_BASE_WIN, 2));
3834 }
3835 
3836 /*
3837  * Positions the memory window at the given address in the card's address space.
3838  * There are some alignment requirements and the actual position may be at an
3839  * address prior to the requested address.  mw->mw_curpos always has the actual
3840  * position of the window.
3841  */
3842 static void
3843 position_memwin(struct adapter *sc, int idx, uint32_t addr)
3844 {
3845 	struct memwin *mw;
3846 	uint32_t pf;
3847 	uint32_t reg;
3848 
3849 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3850 	mw = &sc->memwin[idx];
3851 	rw_assert(&mw->mw_lock, RA_WLOCKED);
3852 
3853 	if (is_t4(sc)) {
3854 		pf = 0;
3855 		mw->mw_curpos = addr & ~0xf;	/* start must be 16B aligned */
3856 	} else {
3857 		pf = V_PFNUM(sc->pf);
3858 		mw->mw_curpos = addr & ~0x7f;	/* start must be 128B aligned */
3859 	}
3860 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, idx);
3861 	t4_write_reg(sc, reg, mw->mw_curpos | pf);
3862 	t4_read_reg(sc, reg);	/* flush */
3863 }
3864 
3865 int
3866 rw_via_memwin(struct adapter *sc, int idx, uint32_t addr, uint32_t *val,
3867     int len, int rw)
3868 {
3869 	struct memwin *mw;
3870 	uint32_t mw_end, v;
3871 
3872 	MPASS(idx >= 0 && idx < NUM_MEMWIN);
3873 
3874 	/* Memory can only be accessed in naturally aligned 4 byte units */
3875 	if (addr & 3 || len & 3 || len <= 0)
3876 		return (EINVAL);
3877 
3878 	mw = &sc->memwin[idx];
3879 	while (len > 0) {
3880 		rw_rlock(&mw->mw_lock);
3881 		mw_end = mw->mw_curpos + mw->mw_aperture;
3882 		if (addr >= mw_end || addr < mw->mw_curpos) {
3883 			/* Will need to reposition the window */
3884 			if (!rw_try_upgrade(&mw->mw_lock)) {
3885 				rw_runlock(&mw->mw_lock);
3886 				rw_wlock(&mw->mw_lock);
3887 			}
3888 			rw_assert(&mw->mw_lock, RA_WLOCKED);
3889 			position_memwin(sc, idx, addr);
3890 			rw_downgrade(&mw->mw_lock);
3891 			mw_end = mw->mw_curpos + mw->mw_aperture;
3892 		}
3893 		rw_assert(&mw->mw_lock, RA_RLOCKED);
3894 		while (addr < mw_end && len > 0) {
3895 			if (rw == 0) {
3896 				v = t4_read_reg(sc, mw->mw_base + addr -
3897 				    mw->mw_curpos);
3898 				*val++ = le32toh(v);
3899 			} else {
3900 				v = *val++;
3901 				t4_write_reg(sc, mw->mw_base + addr -
3902 				    mw->mw_curpos, htole32(v));
3903 			}
3904 			addr += 4;
3905 			len -= 4;
3906 		}
3907 		rw_runlock(&mw->mw_lock);
3908 	}
3909 
3910 	return (0);
3911 }
3912 
3913 static void
3914 t4_init_atid_table(struct adapter *sc)
3915 {
3916 	struct tid_info *t;
3917 	int i;
3918 
3919 	t = &sc->tids;
3920 	if (t->natids == 0)
3921 		return;
3922 
3923 	MPASS(t->atid_tab == NULL);
3924 
3925 	t->atid_tab = malloc(t->natids * sizeof(*t->atid_tab), M_CXGBE,
3926 	    M_ZERO | M_WAITOK);
3927 	mtx_init(&t->atid_lock, "atid lock", NULL, MTX_DEF);
3928 	t->afree = t->atid_tab;
3929 	t->atids_in_use = 0;
3930 	for (i = 1; i < t->natids; i++)
3931 		t->atid_tab[i - 1].next = &t->atid_tab[i];
3932 	t->atid_tab[t->natids - 1].next = NULL;
3933 }
3934 
3935 static void
3936 t4_free_atid_table(struct adapter *sc)
3937 {
3938 	struct tid_info *t;
3939 
3940 	t = &sc->tids;
3941 
3942 	KASSERT(t->atids_in_use == 0,
3943 	    ("%s: %d atids still in use.", __func__, t->atids_in_use));
3944 
3945 	if (mtx_initialized(&t->atid_lock))
3946 		mtx_destroy(&t->atid_lock);
3947 	free(t->atid_tab, M_CXGBE);
3948 	t->atid_tab = NULL;
3949 }
3950 
3951 int
3952 alloc_atid(struct adapter *sc, void *ctx)
3953 {
3954 	struct tid_info *t = &sc->tids;
3955 	int atid = -1;
3956 
3957 	mtx_lock(&t->atid_lock);
3958 	if (t->afree) {
3959 		union aopen_entry *p = t->afree;
3960 
3961 		atid = p - t->atid_tab;
3962 		MPASS(atid <= M_TID_TID);
3963 		t->afree = p->next;
3964 		p->data = ctx;
3965 		t->atids_in_use++;
3966 	}
3967 	mtx_unlock(&t->atid_lock);
3968 	return (atid);
3969 }
3970 
3971 void *
3972 lookup_atid(struct adapter *sc, int atid)
3973 {
3974 	struct tid_info *t = &sc->tids;
3975 
3976 	return (t->atid_tab[atid].data);
3977 }
3978 
3979 void
3980 free_atid(struct adapter *sc, int atid)
3981 {
3982 	struct tid_info *t = &sc->tids;
3983 	union aopen_entry *p = &t->atid_tab[atid];
3984 
3985 	mtx_lock(&t->atid_lock);
3986 	p->next = t->afree;
3987 	t->afree = p;
3988 	t->atids_in_use--;
3989 	mtx_unlock(&t->atid_lock);
3990 }
3991 
3992 static void
3993 queue_tid_release(struct adapter *sc, int tid)
3994 {
3995 
3996 	CXGBE_UNIMPLEMENTED("deferred tid release");
3997 }
3998 
3999 void
4000 release_tid(struct adapter *sc, int tid, struct sge_wrq *ctrlq)
4001 {
4002 	struct wrqe *wr;
4003 	struct cpl_tid_release *req;
4004 
4005 	wr = alloc_wrqe(sizeof(*req), ctrlq);
4006 	if (wr == NULL) {
4007 		queue_tid_release(sc, tid);	/* defer */
4008 		return;
4009 	}
4010 	req = wrtod(wr);
4011 
4012 	INIT_TP_WR_MIT_CPL(req, CPL_TID_RELEASE, tid);
4013 
4014 	t4_wrq_tx(sc, wr);
4015 }
4016 
4017 static int
4018 t4_range_cmp(const void *a, const void *b)
4019 {
4020 	return ((const struct t4_range *)a)->start -
4021 	       ((const struct t4_range *)b)->start;
4022 }
4023 
4024 /*
4025  * Verify that the memory range specified by the addr/len pair is valid within
4026  * the card's address space.
4027  */
4028 static int
4029 validate_mem_range(struct adapter *sc, uint32_t addr, uint32_t len)
4030 {
4031 	struct t4_range mem_ranges[4], *r, *next;
4032 	uint32_t em, addr_len;
4033 	int i, n, remaining;
4034 
4035 	/* Memory can only be accessed in naturally aligned 4 byte units */
4036 	if (addr & 3 || len & 3 || len == 0)
4037 		return (EINVAL);
4038 
4039 	/* Enabled memories */
4040 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4041 
4042 	r = &mem_ranges[0];
4043 	n = 0;
4044 	bzero(r, sizeof(mem_ranges));
4045 	if (em & F_EDRAM0_ENABLE) {
4046 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4047 		r->size = G_EDRAM0_SIZE(addr_len) << 20;
4048 		if (r->size > 0) {
4049 			r->start = G_EDRAM0_BASE(addr_len) << 20;
4050 			if (addr >= r->start &&
4051 			    addr + len <= r->start + r->size)
4052 				return (0);
4053 			r++;
4054 			n++;
4055 		}
4056 	}
4057 	if (em & F_EDRAM1_ENABLE) {
4058 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4059 		r->size = G_EDRAM1_SIZE(addr_len) << 20;
4060 		if (r->size > 0) {
4061 			r->start = G_EDRAM1_BASE(addr_len) << 20;
4062 			if (addr >= r->start &&
4063 			    addr + len <= r->start + r->size)
4064 				return (0);
4065 			r++;
4066 			n++;
4067 		}
4068 	}
4069 	if (em & F_EXT_MEM_ENABLE) {
4070 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4071 		r->size = G_EXT_MEM_SIZE(addr_len) << 20;
4072 		if (r->size > 0) {
4073 			r->start = G_EXT_MEM_BASE(addr_len) << 20;
4074 			if (addr >= r->start &&
4075 			    addr + len <= r->start + r->size)
4076 				return (0);
4077 			r++;
4078 			n++;
4079 		}
4080 	}
4081 	if (is_t5(sc) && em & F_EXT_MEM1_ENABLE) {
4082 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4083 		r->size = G_EXT_MEM1_SIZE(addr_len) << 20;
4084 		if (r->size > 0) {
4085 			r->start = G_EXT_MEM1_BASE(addr_len) << 20;
4086 			if (addr >= r->start &&
4087 			    addr + len <= r->start + r->size)
4088 				return (0);
4089 			r++;
4090 			n++;
4091 		}
4092 	}
4093 	MPASS(n <= nitems(mem_ranges));
4094 
4095 	if (n > 1) {
4096 		/* Sort and merge the ranges. */
4097 		qsort(mem_ranges, n, sizeof(struct t4_range), t4_range_cmp);
4098 
4099 		/* Start from index 0 and examine the next n - 1 entries. */
4100 		r = &mem_ranges[0];
4101 		for (remaining = n - 1; remaining > 0; remaining--, r++) {
4102 
4103 			MPASS(r->size > 0);	/* r is a valid entry. */
4104 			next = r + 1;
4105 			MPASS(next->size > 0);	/* and so is the next one. */
4106 
4107 			while (r->start + r->size >= next->start) {
4108 				/* Merge the next one into the current entry. */
4109 				r->size = max(r->start + r->size,
4110 				    next->start + next->size) - r->start;
4111 				n--;	/* One fewer entry in total. */
4112 				if (--remaining == 0)
4113 					goto done;	/* short circuit */
4114 				next++;
4115 			}
4116 			if (next != r + 1) {
4117 				/*
4118 				 * Some entries were merged into r and next
4119 				 * points to the first valid entry that couldn't
4120 				 * be merged.
4121 				 */
4122 				MPASS(next->size > 0);	/* must be valid */
4123 				memcpy(r + 1, next, remaining * sizeof(*r));
4124 #ifdef INVARIANTS
4125 				/*
4126 				 * This so that the foo->size assertion in the
4127 				 * next iteration of the loop do the right
4128 				 * thing for entries that were pulled up and are
4129 				 * no longer valid.
4130 				 */
4131 				MPASS(n < nitems(mem_ranges));
4132 				bzero(&mem_ranges[n], (nitems(mem_ranges) - n) *
4133 				    sizeof(struct t4_range));
4134 #endif
4135 			}
4136 		}
4137 done:
4138 		/* Done merging the ranges. */
4139 		MPASS(n > 0);
4140 		r = &mem_ranges[0];
4141 		for (i = 0; i < n; i++, r++) {
4142 			if (addr >= r->start &&
4143 			    addr + len <= r->start + r->size)
4144 				return (0);
4145 		}
4146 	}
4147 
4148 	return (EFAULT);
4149 }
4150 
4151 static int
4152 fwmtype_to_hwmtype(int mtype)
4153 {
4154 
4155 	switch (mtype) {
4156 	case FW_MEMTYPE_EDC0:
4157 		return (MEM_EDC0);
4158 	case FW_MEMTYPE_EDC1:
4159 		return (MEM_EDC1);
4160 	case FW_MEMTYPE_EXTMEM:
4161 		return (MEM_MC0);
4162 	case FW_MEMTYPE_EXTMEM1:
4163 		return (MEM_MC1);
4164 	default:
4165 		panic("%s: cannot translate fw mtype %d.", __func__, mtype);
4166 	}
4167 }
4168 
4169 /*
4170  * Verify that the memory range specified by the memtype/offset/len pair is
4171  * valid and lies entirely within the memtype specified.  The global address of
4172  * the start of the range is returned in addr.
4173  */
4174 static int
4175 validate_mt_off_len(struct adapter *sc, int mtype, uint32_t off, uint32_t len,
4176     uint32_t *addr)
4177 {
4178 	uint32_t em, addr_len, maddr;
4179 
4180 	/* Memory can only be accessed in naturally aligned 4 byte units */
4181 	if (off & 3 || len & 3 || len == 0)
4182 		return (EINVAL);
4183 
4184 	em = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
4185 	switch (fwmtype_to_hwmtype(mtype)) {
4186 	case MEM_EDC0:
4187 		if (!(em & F_EDRAM0_ENABLE))
4188 			return (EINVAL);
4189 		addr_len = t4_read_reg(sc, A_MA_EDRAM0_BAR);
4190 		maddr = G_EDRAM0_BASE(addr_len) << 20;
4191 		break;
4192 	case MEM_EDC1:
4193 		if (!(em & F_EDRAM1_ENABLE))
4194 			return (EINVAL);
4195 		addr_len = t4_read_reg(sc, A_MA_EDRAM1_BAR);
4196 		maddr = G_EDRAM1_BASE(addr_len) << 20;
4197 		break;
4198 	case MEM_MC:
4199 		if (!(em & F_EXT_MEM_ENABLE))
4200 			return (EINVAL);
4201 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
4202 		maddr = G_EXT_MEM_BASE(addr_len) << 20;
4203 		break;
4204 	case MEM_MC1:
4205 		if (!is_t5(sc) || !(em & F_EXT_MEM1_ENABLE))
4206 			return (EINVAL);
4207 		addr_len = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
4208 		maddr = G_EXT_MEM1_BASE(addr_len) << 20;
4209 		break;
4210 	default:
4211 		return (EINVAL);
4212 	}
4213 
4214 	*addr = maddr + off;	/* global address */
4215 	return (validate_mem_range(sc, *addr, len));
4216 }
4217 
4218 static int
4219 fixup_devlog_params(struct adapter *sc)
4220 {
4221 	struct devlog_params *dparams = &sc->params.devlog;
4222 	int rc;
4223 
4224 	rc = validate_mt_off_len(sc, dparams->memtype, dparams->start,
4225 	    dparams->size, &dparams->addr);
4226 
4227 	return (rc);
4228 }
4229 
4230 static void
4231 update_nirq(struct intrs_and_queues *iaq, int nports)
4232 {
4233 
4234 	iaq->nirq = T4_EXTRA_INTR;
4235 	iaq->nirq += nports * max(iaq->nrxq, iaq->nnmrxq);
4236 	iaq->nirq += nports * iaq->nofldrxq;
4237 	iaq->nirq += nports * (iaq->num_vis - 1) *
4238 	    max(iaq->nrxq_vi, iaq->nnmrxq_vi);
4239 	iaq->nirq += nports * (iaq->num_vis - 1) * iaq->nofldrxq_vi;
4240 }
4241 
4242 /*
4243  * Adjust requirements to fit the number of interrupts available.
4244  */
4245 static void
4246 calculate_iaq(struct adapter *sc, struct intrs_and_queues *iaq, int itype,
4247     int navail)
4248 {
4249 	int old_nirq;
4250 	const int nports = sc->params.nports;
4251 
4252 	MPASS(nports > 0);
4253 	MPASS(navail > 0);
4254 
4255 	bzero(iaq, sizeof(*iaq));
4256 	iaq->intr_type = itype;
4257 	iaq->num_vis = t4_num_vis;
4258 	iaq->ntxq = t4_ntxq;
4259 	iaq->ntxq_vi = t4_ntxq_vi;
4260 	iaq->nrxq = t4_nrxq;
4261 	iaq->nrxq_vi = t4_nrxq_vi;
4262 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
4263 	if (is_offload(sc) || is_ethoffload(sc)) {
4264 		iaq->nofldtxq = t4_nofldtxq;
4265 		iaq->nofldtxq_vi = t4_nofldtxq_vi;
4266 	}
4267 #endif
4268 #ifdef TCP_OFFLOAD
4269 	if (is_offload(sc)) {
4270 		iaq->nofldrxq = t4_nofldrxq;
4271 		iaq->nofldrxq_vi = t4_nofldrxq_vi;
4272 	}
4273 #endif
4274 #ifdef DEV_NETMAP
4275 	if (t4_native_netmap & NN_MAIN_VI) {
4276 		iaq->nnmtxq = t4_nnmtxq;
4277 		iaq->nnmrxq = t4_nnmrxq;
4278 	}
4279 	if (t4_native_netmap & NN_EXTRA_VI) {
4280 		iaq->nnmtxq_vi = t4_nnmtxq_vi;
4281 		iaq->nnmrxq_vi = t4_nnmrxq_vi;
4282 	}
4283 #endif
4284 
4285 	update_nirq(iaq, nports);
4286 	if (iaq->nirq <= navail &&
4287 	    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4288 		/*
4289 		 * This is the normal case -- there are enough interrupts for
4290 		 * everything.
4291 		 */
4292 		goto done;
4293 	}
4294 
4295 	/*
4296 	 * If extra VIs have been configured try reducing their count and see if
4297 	 * that works.
4298 	 */
4299 	while (iaq->num_vis > 1) {
4300 		iaq->num_vis--;
4301 		update_nirq(iaq, nports);
4302 		if (iaq->nirq <= navail &&
4303 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4304 			device_printf(sc->dev, "virtual interfaces per port "
4305 			    "reduced to %d from %d.  nrxq=%u, nofldrxq=%u, "
4306 			    "nrxq_vi=%u nofldrxq_vi=%u, nnmrxq_vi=%u.  "
4307 			    "itype %d, navail %u, nirq %d.\n",
4308 			    iaq->num_vis, t4_num_vis, iaq->nrxq, iaq->nofldrxq,
4309 			    iaq->nrxq_vi, iaq->nofldrxq_vi, iaq->nnmrxq_vi,
4310 			    itype, navail, iaq->nirq);
4311 			goto done;
4312 		}
4313 	}
4314 
4315 	/*
4316 	 * Extra VIs will not be created.  Log a message if they were requested.
4317 	 */
4318 	MPASS(iaq->num_vis == 1);
4319 	iaq->ntxq_vi = iaq->nrxq_vi = 0;
4320 	iaq->nofldtxq_vi = iaq->nofldrxq_vi = 0;
4321 	iaq->nnmtxq_vi = iaq->nnmrxq_vi = 0;
4322 	if (iaq->num_vis != t4_num_vis) {
4323 		device_printf(sc->dev, "extra virtual interfaces disabled.  "
4324 		    "nrxq=%u, nofldrxq=%u, nrxq_vi=%u nofldrxq_vi=%u, "
4325 		    "nnmrxq_vi=%u.  itype %d, navail %u, nirq %d.\n",
4326 		    iaq->nrxq, iaq->nofldrxq, iaq->nrxq_vi, iaq->nofldrxq_vi,
4327 		    iaq->nnmrxq_vi, itype, navail, iaq->nirq);
4328 	}
4329 
4330 	/*
4331 	 * Keep reducing the number of NIC rx queues to the next lower power of
4332 	 * 2 (for even RSS distribution) and halving the TOE rx queues and see
4333 	 * if that works.
4334 	 */
4335 	do {
4336 		if (iaq->nrxq > 1) {
4337 			do {
4338 				iaq->nrxq--;
4339 			} while (!powerof2(iaq->nrxq));
4340 			if (iaq->nnmrxq > iaq->nrxq)
4341 				iaq->nnmrxq = iaq->nrxq;
4342 		}
4343 		if (iaq->nofldrxq > 1)
4344 			iaq->nofldrxq >>= 1;
4345 
4346 		old_nirq = iaq->nirq;
4347 		update_nirq(iaq, nports);
4348 		if (iaq->nirq <= navail &&
4349 		    (itype != INTR_MSI || powerof2(iaq->nirq))) {
4350 			device_printf(sc->dev, "running with reduced number of "
4351 			    "rx queues because of shortage of interrupts.  "
4352 			    "nrxq=%u, nofldrxq=%u.  "
4353 			    "itype %d, navail %u, nirq %d.\n", iaq->nrxq,
4354 			    iaq->nofldrxq, itype, navail, iaq->nirq);
4355 			goto done;
4356 		}
4357 	} while (old_nirq != iaq->nirq);
4358 
4359 	/* One interrupt for everything.  Ugh. */
4360 	device_printf(sc->dev, "running with minimal number of queues.  "
4361 	    "itype %d, navail %u.\n", itype, navail);
4362 	iaq->nirq = 1;
4363 	iaq->nrxq = 1;
4364 	iaq->ntxq = 1;
4365 	if (iaq->nofldrxq > 0) {
4366 		iaq->nofldrxq = 1;
4367 		iaq->nofldtxq = 1;
4368 	}
4369 	iaq->nnmtxq = 0;
4370 	iaq->nnmrxq = 0;
4371 done:
4372 	MPASS(iaq->num_vis > 0);
4373 	if (iaq->num_vis > 1) {
4374 		MPASS(iaq->nrxq_vi > 0);
4375 		MPASS(iaq->ntxq_vi > 0);
4376 	}
4377 	MPASS(iaq->nirq > 0);
4378 	MPASS(iaq->nrxq > 0);
4379 	MPASS(iaq->ntxq > 0);
4380 	if (itype == INTR_MSI) {
4381 		MPASS(powerof2(iaq->nirq));
4382 	}
4383 }
4384 
4385 static int
4386 cfg_itype_and_nqueues(struct adapter *sc, struct intrs_and_queues *iaq)
4387 {
4388 	int rc, itype, navail, nalloc;
4389 
4390 	for (itype = INTR_MSIX; itype; itype >>= 1) {
4391 
4392 		if ((itype & t4_intr_types) == 0)
4393 			continue;	/* not allowed */
4394 
4395 		if (itype == INTR_MSIX)
4396 			navail = pci_msix_count(sc->dev);
4397 		else if (itype == INTR_MSI)
4398 			navail = pci_msi_count(sc->dev);
4399 		else
4400 			navail = 1;
4401 restart:
4402 		if (navail == 0)
4403 			continue;
4404 
4405 		calculate_iaq(sc, iaq, itype, navail);
4406 		nalloc = iaq->nirq;
4407 		rc = 0;
4408 		if (itype == INTR_MSIX)
4409 			rc = pci_alloc_msix(sc->dev, &nalloc);
4410 		else if (itype == INTR_MSI)
4411 			rc = pci_alloc_msi(sc->dev, &nalloc);
4412 
4413 		if (rc == 0 && nalloc > 0) {
4414 			if (nalloc == iaq->nirq)
4415 				return (0);
4416 
4417 			/*
4418 			 * Didn't get the number requested.  Use whatever number
4419 			 * the kernel is willing to allocate.
4420 			 */
4421 			device_printf(sc->dev, "fewer vectors than requested, "
4422 			    "type=%d, req=%d, rcvd=%d; will downshift req.\n",
4423 			    itype, iaq->nirq, nalloc);
4424 			pci_release_msi(sc->dev);
4425 			navail = nalloc;
4426 			goto restart;
4427 		}
4428 
4429 		device_printf(sc->dev,
4430 		    "failed to allocate vectors:%d, type=%d, req=%d, rcvd=%d\n",
4431 		    itype, rc, iaq->nirq, nalloc);
4432 	}
4433 
4434 	device_printf(sc->dev,
4435 	    "failed to find a usable interrupt type.  "
4436 	    "allowed=%d, msi-x=%d, msi=%d, intx=1", t4_intr_types,
4437 	    pci_msix_count(sc->dev), pci_msi_count(sc->dev));
4438 
4439 	return (ENXIO);
4440 }
4441 
4442 #define FW_VERSION(chip) ( \
4443     V_FW_HDR_FW_VER_MAJOR(chip##FW_VERSION_MAJOR) | \
4444     V_FW_HDR_FW_VER_MINOR(chip##FW_VERSION_MINOR) | \
4445     V_FW_HDR_FW_VER_MICRO(chip##FW_VERSION_MICRO) | \
4446     V_FW_HDR_FW_VER_BUILD(chip##FW_VERSION_BUILD))
4447 #define FW_INTFVER(chip, intf) (chip##FW_HDR_INTFVER_##intf)
4448 
4449 /* Just enough of fw_hdr to cover all version info. */
4450 struct fw_h {
4451 	__u8	ver;
4452 	__u8	chip;
4453 	__be16	len512;
4454 	__be32	fw_ver;
4455 	__be32	tp_microcode_ver;
4456 	__u8	intfver_nic;
4457 	__u8	intfver_vnic;
4458 	__u8	intfver_ofld;
4459 	__u8	intfver_ri;
4460 	__u8	intfver_iscsipdu;
4461 	__u8	intfver_iscsi;
4462 	__u8	intfver_fcoepdu;
4463 	__u8	intfver_fcoe;
4464 };
4465 /* Spot check a couple of fields. */
4466 CTASSERT(offsetof(struct fw_h, fw_ver) == offsetof(struct fw_hdr, fw_ver));
4467 CTASSERT(offsetof(struct fw_h, intfver_nic) == offsetof(struct fw_hdr, intfver_nic));
4468 CTASSERT(offsetof(struct fw_h, intfver_fcoe) == offsetof(struct fw_hdr, intfver_fcoe));
4469 
4470 struct fw_info {
4471 	uint8_t chip;
4472 	char *kld_name;
4473 	char *fw_mod_name;
4474 	struct fw_h fw_h;
4475 } fw_info[] = {
4476 	{
4477 		.chip = CHELSIO_T4,
4478 		.kld_name = "t4fw_cfg",
4479 		.fw_mod_name = "t4fw",
4480 		.fw_h = {
4481 			.chip = FW_HDR_CHIP_T4,
4482 			.fw_ver = htobe32(FW_VERSION(T4)),
4483 			.intfver_nic = FW_INTFVER(T4, NIC),
4484 			.intfver_vnic = FW_INTFVER(T4, VNIC),
4485 			.intfver_ofld = FW_INTFVER(T4, OFLD),
4486 			.intfver_ri = FW_INTFVER(T4, RI),
4487 			.intfver_iscsipdu = FW_INTFVER(T4, ISCSIPDU),
4488 			.intfver_iscsi = FW_INTFVER(T4, ISCSI),
4489 			.intfver_fcoepdu = FW_INTFVER(T4, FCOEPDU),
4490 			.intfver_fcoe = FW_INTFVER(T4, FCOE),
4491 		},
4492 	}, {
4493 		.chip = CHELSIO_T5,
4494 		.kld_name = "t5fw_cfg",
4495 		.fw_mod_name = "t5fw",
4496 		.fw_h = {
4497 			.chip = FW_HDR_CHIP_T5,
4498 			.fw_ver = htobe32(FW_VERSION(T5)),
4499 			.intfver_nic = FW_INTFVER(T5, NIC),
4500 			.intfver_vnic = FW_INTFVER(T5, VNIC),
4501 			.intfver_ofld = FW_INTFVER(T5, OFLD),
4502 			.intfver_ri = FW_INTFVER(T5, RI),
4503 			.intfver_iscsipdu = FW_INTFVER(T5, ISCSIPDU),
4504 			.intfver_iscsi = FW_INTFVER(T5, ISCSI),
4505 			.intfver_fcoepdu = FW_INTFVER(T5, FCOEPDU),
4506 			.intfver_fcoe = FW_INTFVER(T5, FCOE),
4507 		},
4508 	}, {
4509 		.chip = CHELSIO_T6,
4510 		.kld_name = "t6fw_cfg",
4511 		.fw_mod_name = "t6fw",
4512 		.fw_h = {
4513 			.chip = FW_HDR_CHIP_T6,
4514 			.fw_ver = htobe32(FW_VERSION(T6)),
4515 			.intfver_nic = FW_INTFVER(T6, NIC),
4516 			.intfver_vnic = FW_INTFVER(T6, VNIC),
4517 			.intfver_ofld = FW_INTFVER(T6, OFLD),
4518 			.intfver_ri = FW_INTFVER(T6, RI),
4519 			.intfver_iscsipdu = FW_INTFVER(T6, ISCSIPDU),
4520 			.intfver_iscsi = FW_INTFVER(T6, ISCSI),
4521 			.intfver_fcoepdu = FW_INTFVER(T6, FCOEPDU),
4522 			.intfver_fcoe = FW_INTFVER(T6, FCOE),
4523 		},
4524 	}
4525 };
4526 
4527 static struct fw_info *
4528 find_fw_info(int chip)
4529 {
4530 	int i;
4531 
4532 	for (i = 0; i < nitems(fw_info); i++) {
4533 		if (fw_info[i].chip == chip)
4534 			return (&fw_info[i]);
4535 	}
4536 	return (NULL);
4537 }
4538 
4539 /*
4540  * Is the given firmware API compatible with the one the driver was compiled
4541  * with?
4542  */
4543 static int
4544 fw_compatible(const struct fw_h *hdr1, const struct fw_h *hdr2)
4545 {
4546 
4547 	/* short circuit if it's the exact same firmware version */
4548 	if (hdr1->chip == hdr2->chip && hdr1->fw_ver == hdr2->fw_ver)
4549 		return (1);
4550 
4551 	/*
4552 	 * XXX: Is this too conservative?  Perhaps I should limit this to the
4553 	 * features that are supported in the driver.
4554 	 */
4555 #define SAME_INTF(x) (hdr1->intfver_##x == hdr2->intfver_##x)
4556 	if (hdr1->chip == hdr2->chip && SAME_INTF(nic) && SAME_INTF(vnic) &&
4557 	    SAME_INTF(ofld) && SAME_INTF(ri) && SAME_INTF(iscsipdu) &&
4558 	    SAME_INTF(iscsi) && SAME_INTF(fcoepdu) && SAME_INTF(fcoe))
4559 		return (1);
4560 #undef SAME_INTF
4561 
4562 	return (0);
4563 }
4564 
4565 static int
4566 load_fw_module(struct adapter *sc, const struct firmware **dcfg,
4567     const struct firmware **fw)
4568 {
4569 	struct fw_info *fw_info;
4570 
4571 	*dcfg = NULL;
4572 	if (fw != NULL)
4573 		*fw = NULL;
4574 
4575 	fw_info = find_fw_info(chip_id(sc));
4576 	if (fw_info == NULL) {
4577 		device_printf(sc->dev,
4578 		    "unable to look up firmware information for chip %d.\n",
4579 		    chip_id(sc));
4580 		return (EINVAL);
4581 	}
4582 
4583 	*dcfg = firmware_get(fw_info->kld_name);
4584 	if (*dcfg != NULL) {
4585 		if (fw != NULL)
4586 			*fw = firmware_get(fw_info->fw_mod_name);
4587 		return (0);
4588 	}
4589 
4590 	return (ENOENT);
4591 }
4592 
4593 static void
4594 unload_fw_module(struct adapter *sc, const struct firmware *dcfg,
4595     const struct firmware *fw)
4596 {
4597 
4598 	if (fw != NULL)
4599 		firmware_put(fw, FIRMWARE_UNLOAD);
4600 	if (dcfg != NULL)
4601 		firmware_put(dcfg, FIRMWARE_UNLOAD);
4602 }
4603 
4604 /*
4605  * Return values:
4606  * 0 means no firmware install attempted.
4607  * ERESTART means a firmware install was attempted and was successful.
4608  * +ve errno means a firmware install was attempted but failed.
4609  */
4610 static int
4611 install_kld_firmware(struct adapter *sc, struct fw_h *card_fw,
4612     const struct fw_h *drv_fw, const char *reason, int *already)
4613 {
4614 	const struct firmware *cfg, *fw;
4615 	const uint32_t c = be32toh(card_fw->fw_ver);
4616 	uint32_t d, k;
4617 	int rc, fw_install;
4618 	struct fw_h bundled_fw;
4619 	bool load_attempted;
4620 
4621 	cfg = fw = NULL;
4622 	load_attempted = false;
4623 	fw_install = t4_fw_install < 0 ? -t4_fw_install : t4_fw_install;
4624 
4625 	memcpy(&bundled_fw, drv_fw, sizeof(bundled_fw));
4626 	if (t4_fw_install < 0) {
4627 		rc = load_fw_module(sc, &cfg, &fw);
4628 		if (rc != 0 || fw == NULL) {
4629 			device_printf(sc->dev,
4630 			    "failed to load firmware module: %d. cfg %p, fw %p;"
4631 			    " will use compiled-in firmware version for"
4632 			    "hw.cxgbe.fw_install checks.\n",
4633 			    rc, cfg, fw);
4634 		} else {
4635 			memcpy(&bundled_fw, fw->data, sizeof(bundled_fw));
4636 		}
4637 		load_attempted = true;
4638 	}
4639 	d = be32toh(bundled_fw.fw_ver);
4640 
4641 	if (reason != NULL)
4642 		goto install;
4643 
4644 	if ((sc->flags & FW_OK) == 0) {
4645 
4646 		if (c == 0xffffffff) {
4647 			reason = "missing";
4648 			goto install;
4649 		}
4650 
4651 		rc = 0;
4652 		goto done;
4653 	}
4654 
4655 	if (!fw_compatible(card_fw, &bundled_fw)) {
4656 		reason = "incompatible or unusable";
4657 		goto install;
4658 	}
4659 
4660 	if (d > c) {
4661 		reason = "older than the version bundled with this driver";
4662 		goto install;
4663 	}
4664 
4665 	if (fw_install == 2 && d != c) {
4666 		reason = "different than the version bundled with this driver";
4667 		goto install;
4668 	}
4669 
4670 	/* No reason to do anything to the firmware already on the card. */
4671 	rc = 0;
4672 	goto done;
4673 
4674 install:
4675 	rc = 0;
4676 	if ((*already)++)
4677 		goto done;
4678 
4679 	if (fw_install == 0) {
4680 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4681 		    "but the driver is prohibited from installing a firmware "
4682 		    "on the card.\n",
4683 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4684 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4685 
4686 		goto done;
4687 	}
4688 
4689 	/*
4690 	 * We'll attempt to install a firmware.  Load the module first (if it
4691 	 * hasn't been loaded already).
4692 	 */
4693 	if (!load_attempted) {
4694 		rc = load_fw_module(sc, &cfg, &fw);
4695 		if (rc != 0 || fw == NULL) {
4696 			device_printf(sc->dev,
4697 			    "failed to load firmware module: %d. cfg %p, fw %p\n",
4698 			    rc, cfg, fw);
4699 			/* carry on */
4700 		}
4701 	}
4702 	if (fw == NULL) {
4703 		device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4704 		    "but the driver cannot take corrective action because it "
4705 		    "is unable to load the firmware module.\n",
4706 		    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4707 		    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason);
4708 		rc = sc->flags & FW_OK ? 0 : ENOENT;
4709 		goto done;
4710 	}
4711 	k = be32toh(((const struct fw_hdr *)fw->data)->fw_ver);
4712 	if (k != d) {
4713 		MPASS(t4_fw_install > 0);
4714 		device_printf(sc->dev,
4715 		    "firmware in KLD (%u.%u.%u.%u) is not what the driver was "
4716 		    "expecting (%u.%u.%u.%u) and will not be used.\n",
4717 		    G_FW_HDR_FW_VER_MAJOR(k), G_FW_HDR_FW_VER_MINOR(k),
4718 		    G_FW_HDR_FW_VER_MICRO(k), G_FW_HDR_FW_VER_BUILD(k),
4719 		    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4720 		    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4721 		rc = sc->flags & FW_OK ? 0 : EINVAL;
4722 		goto done;
4723 	}
4724 
4725 	device_printf(sc->dev, "firmware on card (%u.%u.%u.%u) is %s, "
4726 	    "installing firmware %u.%u.%u.%u on card.\n",
4727 	    G_FW_HDR_FW_VER_MAJOR(c), G_FW_HDR_FW_VER_MINOR(c),
4728 	    G_FW_HDR_FW_VER_MICRO(c), G_FW_HDR_FW_VER_BUILD(c), reason,
4729 	    G_FW_HDR_FW_VER_MAJOR(d), G_FW_HDR_FW_VER_MINOR(d),
4730 	    G_FW_HDR_FW_VER_MICRO(d), G_FW_HDR_FW_VER_BUILD(d));
4731 
4732 	rc = -t4_fw_upgrade(sc, sc->mbox, fw->data, fw->datasize, 0);
4733 	if (rc != 0) {
4734 		device_printf(sc->dev, "failed to install firmware: %d\n", rc);
4735 	} else {
4736 		/* Installed successfully, update the cached header too. */
4737 		rc = ERESTART;
4738 		memcpy(card_fw, fw->data, sizeof(*card_fw));
4739 	}
4740 done:
4741 	unload_fw_module(sc, cfg, fw);
4742 
4743 	return (rc);
4744 }
4745 
4746 /*
4747  * Establish contact with the firmware and attempt to become the master driver.
4748  *
4749  * A firmware will be installed to the card if needed (if the driver is allowed
4750  * to do so).
4751  */
4752 static int
4753 contact_firmware(struct adapter *sc)
4754 {
4755 	int rc, already = 0;
4756 	enum dev_state state;
4757 	struct fw_info *fw_info;
4758 	struct fw_hdr *card_fw;		/* fw on the card */
4759 	const struct fw_h *drv_fw;
4760 
4761 	fw_info = find_fw_info(chip_id(sc));
4762 	if (fw_info == NULL) {
4763 		device_printf(sc->dev,
4764 		    "unable to look up firmware information for chip %d.\n",
4765 		    chip_id(sc));
4766 		return (EINVAL);
4767 	}
4768 	drv_fw = &fw_info->fw_h;
4769 
4770 	/* Read the header of the firmware on the card */
4771 	card_fw = malloc(sizeof(*card_fw), M_CXGBE, M_ZERO | M_WAITOK);
4772 restart:
4773 	rc = -t4_get_fw_hdr(sc, card_fw);
4774 	if (rc != 0) {
4775 		device_printf(sc->dev,
4776 		    "unable to read firmware header from card's flash: %d\n",
4777 		    rc);
4778 		goto done;
4779 	}
4780 
4781 	rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw, NULL,
4782 	    &already);
4783 	if (rc == ERESTART)
4784 		goto restart;
4785 	if (rc != 0)
4786 		goto done;
4787 
4788 	rc = t4_fw_hello(sc, sc->mbox, sc->mbox, MASTER_MAY, &state);
4789 	if (rc < 0 || state == DEV_STATE_ERR) {
4790 		rc = -rc;
4791 		device_printf(sc->dev,
4792 		    "failed to connect to the firmware: %d, %d.  "
4793 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4794 #if 0
4795 		if (install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4796 		    "not responding properly to HELLO", &already) == ERESTART)
4797 			goto restart;
4798 #endif
4799 		goto done;
4800 	}
4801 	MPASS(be32toh(card_fw->flags) & FW_HDR_FLAGS_RESET_HALT);
4802 	sc->flags |= FW_OK;	/* The firmware responded to the FW_HELLO. */
4803 
4804 	if (rc == sc->pf) {
4805 		sc->flags |= MASTER_PF;
4806 		rc = install_kld_firmware(sc, (struct fw_h *)card_fw, drv_fw,
4807 		    NULL, &already);
4808 		if (rc == ERESTART)
4809 			rc = 0;
4810 		else if (rc != 0)
4811 			goto done;
4812 	} else if (state == DEV_STATE_UNINIT) {
4813 		/*
4814 		 * We didn't get to be the master so we definitely won't be
4815 		 * configuring the chip.  It's a bug if someone else hasn't
4816 		 * configured it already.
4817 		 */
4818 		device_printf(sc->dev, "couldn't be master(%d), "
4819 		    "device not already initialized either(%d).  "
4820 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4821 		rc = EPROTO;
4822 		goto done;
4823 	} else {
4824 		/*
4825 		 * Some other PF is the master and has configured the chip.
4826 		 * This is allowed but untested.
4827 		 */
4828 		device_printf(sc->dev, "PF%d is master, device state %d.  "
4829 		    "PCIE_FW 0x%08x\n", rc, state, t4_read_reg(sc, A_PCIE_FW));
4830 		snprintf(sc->cfg_file, sizeof(sc->cfg_file), "pf%d", rc);
4831 		sc->cfcsum = 0;
4832 		rc = 0;
4833 	}
4834 done:
4835 	if (rc != 0 && sc->flags & FW_OK) {
4836 		t4_fw_bye(sc, sc->mbox);
4837 		sc->flags &= ~FW_OK;
4838 	}
4839 	free(card_fw, M_CXGBE);
4840 	return (rc);
4841 }
4842 
4843 static int
4844 copy_cfg_file_to_card(struct adapter *sc, char *cfg_file,
4845     uint32_t mtype, uint32_t moff)
4846 {
4847 	struct fw_info *fw_info;
4848 	const struct firmware *dcfg, *rcfg = NULL;
4849 	const uint32_t *cfdata;
4850 	uint32_t cflen, addr;
4851 	int rc;
4852 
4853 	load_fw_module(sc, &dcfg, NULL);
4854 
4855 	/* Card specific interpretation of "default". */
4856 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4857 		if (pci_get_device(sc->dev) == 0x440a)
4858 			snprintf(cfg_file, sizeof(t4_cfg_file), UWIRE_CF);
4859 		if (is_fpga(sc))
4860 			snprintf(cfg_file, sizeof(t4_cfg_file), FPGA_CF);
4861 	}
4862 
4863 	if (strncmp(cfg_file, DEFAULT_CF, sizeof(t4_cfg_file)) == 0) {
4864 		if (dcfg == NULL) {
4865 			device_printf(sc->dev,
4866 			    "KLD with default config is not available.\n");
4867 			rc = ENOENT;
4868 			goto done;
4869 		}
4870 		cfdata = dcfg->data;
4871 		cflen = dcfg->datasize & ~3;
4872 	} else {
4873 		char s[32];
4874 
4875 		fw_info = find_fw_info(chip_id(sc));
4876 		if (fw_info == NULL) {
4877 			device_printf(sc->dev,
4878 			    "unable to look up firmware information for chip %d.\n",
4879 			    chip_id(sc));
4880 			rc = EINVAL;
4881 			goto done;
4882 		}
4883 		snprintf(s, sizeof(s), "%s_%s", fw_info->kld_name, cfg_file);
4884 
4885 		rcfg = firmware_get(s);
4886 		if (rcfg == NULL) {
4887 			device_printf(sc->dev,
4888 			    "unable to load module \"%s\" for configuration "
4889 			    "profile \"%s\".\n", s, cfg_file);
4890 			rc = ENOENT;
4891 			goto done;
4892 		}
4893 		cfdata = rcfg->data;
4894 		cflen = rcfg->datasize & ~3;
4895 	}
4896 
4897 	if (cflen > FLASH_CFG_MAX_SIZE) {
4898 		device_printf(sc->dev,
4899 		    "config file too long (%d, max allowed is %d).\n",
4900 		    cflen, FLASH_CFG_MAX_SIZE);
4901 		rc = EINVAL;
4902 		goto done;
4903 	}
4904 
4905 	rc = validate_mt_off_len(sc, mtype, moff, cflen, &addr);
4906 	if (rc != 0) {
4907 		device_printf(sc->dev,
4908 		    "%s: addr (%d/0x%x) or len %d is not valid: %d.\n",
4909 		    __func__, mtype, moff, cflen, rc);
4910 		rc = EINVAL;
4911 		goto done;
4912 	}
4913 	write_via_memwin(sc, 2, addr, cfdata, cflen);
4914 done:
4915 	if (rcfg != NULL)
4916 		firmware_put(rcfg, FIRMWARE_UNLOAD);
4917 	unload_fw_module(sc, dcfg, NULL);
4918 	return (rc);
4919 }
4920 
4921 struct caps_allowed {
4922 	uint16_t nbmcaps;
4923 	uint16_t linkcaps;
4924 	uint16_t switchcaps;
4925 	uint16_t niccaps;
4926 	uint16_t toecaps;
4927 	uint16_t rdmacaps;
4928 	uint16_t cryptocaps;
4929 	uint16_t iscsicaps;
4930 	uint16_t fcoecaps;
4931 };
4932 
4933 #define FW_PARAM_DEV(param) \
4934 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) | \
4935 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_##param))
4936 #define FW_PARAM_PFVF(param) \
4937 	(V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_PFVF) | \
4938 	 V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_PFVF_##param))
4939 
4940 /*
4941  * Provide a configuration profile to the firmware and have it initialize the
4942  * chip accordingly.  This may involve uploading a configuration file to the
4943  * card.
4944  */
4945 static int
4946 apply_cfg_and_initialize(struct adapter *sc, char *cfg_file,
4947     const struct caps_allowed *caps_allowed)
4948 {
4949 	int rc;
4950 	struct fw_caps_config_cmd caps;
4951 	uint32_t mtype, moff, finicsum, cfcsum, param, val;
4952 
4953 	rc = -t4_fw_reset(sc, sc->mbox, F_PIORSTMODE | F_PIORST);
4954 	if (rc != 0) {
4955 		device_printf(sc->dev, "firmware reset failed: %d.\n", rc);
4956 		return (rc);
4957 	}
4958 
4959 	bzero(&caps, sizeof(caps));
4960 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
4961 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
4962 	if (strncmp(cfg_file, BUILTIN_CF, sizeof(t4_cfg_file)) == 0) {
4963 		mtype = 0;
4964 		moff = 0;
4965 		caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
4966 	} else if (strncmp(cfg_file, FLASH_CF, sizeof(t4_cfg_file)) == 0) {
4967 		mtype = FW_MEMTYPE_FLASH;
4968 		moff = t4_flash_cfg_addr(sc);
4969 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4970 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4971 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4972 		    FW_LEN16(caps));
4973 	} else {
4974 		/*
4975 		 * Ask the firmware where it wants us to upload the config file.
4976 		 */
4977 		param = FW_PARAM_DEV(CF);
4978 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
4979 		if (rc != 0) {
4980 			/* No support for config file?  Shouldn't happen. */
4981 			device_printf(sc->dev,
4982 			    "failed to query config file location: %d.\n", rc);
4983 			goto done;
4984 		}
4985 		mtype = G_FW_PARAMS_PARAM_Y(val);
4986 		moff = G_FW_PARAMS_PARAM_Z(val) << 16;
4987 		caps.cfvalid_to_len16 = htobe32(F_FW_CAPS_CONFIG_CMD_CFVALID |
4988 		    V_FW_CAPS_CONFIG_CMD_MEMTYPE_CF(mtype) |
4989 		    V_FW_CAPS_CONFIG_CMD_MEMADDR64K_CF(moff >> 16) |
4990 		    FW_LEN16(caps));
4991 
4992 		rc = copy_cfg_file_to_card(sc, cfg_file, mtype, moff);
4993 		if (rc != 0) {
4994 			device_printf(sc->dev,
4995 			    "failed to upload config file to card: %d.\n", rc);
4996 			goto done;
4997 		}
4998 	}
4999 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5000 	if (rc != 0) {
5001 		device_printf(sc->dev, "failed to pre-process config file: %d "
5002 		    "(mtype %d, moff 0x%x).\n", rc, mtype, moff);
5003 		goto done;
5004 	}
5005 
5006 	finicsum = be32toh(caps.finicsum);
5007 	cfcsum = be32toh(caps.cfcsum);	/* actual */
5008 	if (finicsum != cfcsum) {
5009 		device_printf(sc->dev,
5010 		    "WARNING: config file checksum mismatch: %08x %08x\n",
5011 		    finicsum, cfcsum);
5012 	}
5013 	sc->cfcsum = cfcsum;
5014 	snprintf(sc->cfg_file, sizeof(sc->cfg_file), "%s", cfg_file);
5015 
5016 	/*
5017 	 * Let the firmware know what features will (not) be used so it can tune
5018 	 * things accordingly.
5019 	 */
5020 #define LIMIT_CAPS(x) do { \
5021 	caps.x##caps &= htobe16(caps_allowed->x##caps); \
5022 } while (0)
5023 	LIMIT_CAPS(nbm);
5024 	LIMIT_CAPS(link);
5025 	LIMIT_CAPS(switch);
5026 	LIMIT_CAPS(nic);
5027 	LIMIT_CAPS(toe);
5028 	LIMIT_CAPS(rdma);
5029 	LIMIT_CAPS(crypto);
5030 	LIMIT_CAPS(iscsi);
5031 	LIMIT_CAPS(fcoe);
5032 #undef LIMIT_CAPS
5033 	if (caps.niccaps & htobe16(FW_CAPS_CONFIG_NIC_HASHFILTER)) {
5034 		/*
5035 		 * TOE and hashfilters are mutually exclusive.  It is a config
5036 		 * file or firmware bug if both are reported as available.  Try
5037 		 * to cope with the situation in non-debug builds by disabling
5038 		 * TOE.
5039 		 */
5040 		MPASS(caps.toecaps == 0);
5041 
5042 		caps.toecaps = 0;
5043 		caps.rdmacaps = 0;
5044 		caps.iscsicaps = 0;
5045 	}
5046 
5047 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5048 	    F_FW_CMD_REQUEST | F_FW_CMD_WRITE);
5049 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5050 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), NULL);
5051 	if (rc != 0) {
5052 		device_printf(sc->dev,
5053 		    "failed to process config file: %d.\n", rc);
5054 		goto done;
5055 	}
5056 
5057 	t4_tweak_chip_settings(sc);
5058 	set_params__pre_init(sc);
5059 
5060 	/* get basic stuff going */
5061 	rc = -t4_fw_initialize(sc, sc->mbox);
5062 	if (rc != 0) {
5063 		device_printf(sc->dev, "fw_initialize failed: %d.\n", rc);
5064 		goto done;
5065 	}
5066 done:
5067 	return (rc);
5068 }
5069 
5070 /*
5071  * Partition chip resources for use between various PFs, VFs, etc.
5072  */
5073 static int
5074 partition_resources(struct adapter *sc)
5075 {
5076 	char cfg_file[sizeof(t4_cfg_file)];
5077 	struct caps_allowed caps_allowed;
5078 	int rc;
5079 	bool fallback;
5080 
5081 	/* Only the master driver gets to configure the chip resources. */
5082 	MPASS(sc->flags & MASTER_PF);
5083 
5084 #define COPY_CAPS(x) do { \
5085 	caps_allowed.x##caps = t4_##x##caps_allowed; \
5086 } while (0)
5087 	bzero(&caps_allowed, sizeof(caps_allowed));
5088 	COPY_CAPS(nbm);
5089 	COPY_CAPS(link);
5090 	COPY_CAPS(switch);
5091 	COPY_CAPS(nic);
5092 	COPY_CAPS(toe);
5093 	COPY_CAPS(rdma);
5094 	COPY_CAPS(crypto);
5095 	COPY_CAPS(iscsi);
5096 	COPY_CAPS(fcoe);
5097 	fallback = sc->debug_flags & DF_DISABLE_CFG_RETRY ? false : true;
5098 	snprintf(cfg_file, sizeof(cfg_file), "%s", t4_cfg_file);
5099 retry:
5100 	rc = apply_cfg_and_initialize(sc, cfg_file, &caps_allowed);
5101 	if (rc != 0 && fallback) {
5102 		dump_devlog(sc);
5103 		device_printf(sc->dev,
5104 		    "failed (%d) to configure card with \"%s\" profile, "
5105 		    "will fall back to a basic configuration and retry.\n",
5106 		    rc, cfg_file);
5107 		snprintf(cfg_file, sizeof(cfg_file), "%s", BUILTIN_CF);
5108 		bzero(&caps_allowed, sizeof(caps_allowed));
5109 		COPY_CAPS(switch);
5110 		caps_allowed.niccaps = FW_CAPS_CONFIG_NIC;
5111 		fallback = false;
5112 		goto retry;
5113 	}
5114 #undef COPY_CAPS
5115 	return (rc);
5116 }
5117 
5118 /*
5119  * Retrieve parameters that are needed (or nice to have) very early.
5120  */
5121 static int
5122 get_params__pre_init(struct adapter *sc)
5123 {
5124 	int rc;
5125 	uint32_t param[2], val[2];
5126 
5127 	t4_get_version_info(sc);
5128 
5129 	snprintf(sc->fw_version, sizeof(sc->fw_version), "%u.%u.%u.%u",
5130 	    G_FW_HDR_FW_VER_MAJOR(sc->params.fw_vers),
5131 	    G_FW_HDR_FW_VER_MINOR(sc->params.fw_vers),
5132 	    G_FW_HDR_FW_VER_MICRO(sc->params.fw_vers),
5133 	    G_FW_HDR_FW_VER_BUILD(sc->params.fw_vers));
5134 
5135 	snprintf(sc->bs_version, sizeof(sc->bs_version), "%u.%u.%u.%u",
5136 	    G_FW_HDR_FW_VER_MAJOR(sc->params.bs_vers),
5137 	    G_FW_HDR_FW_VER_MINOR(sc->params.bs_vers),
5138 	    G_FW_HDR_FW_VER_MICRO(sc->params.bs_vers),
5139 	    G_FW_HDR_FW_VER_BUILD(sc->params.bs_vers));
5140 
5141 	snprintf(sc->tp_version, sizeof(sc->tp_version), "%u.%u.%u.%u",
5142 	    G_FW_HDR_FW_VER_MAJOR(sc->params.tp_vers),
5143 	    G_FW_HDR_FW_VER_MINOR(sc->params.tp_vers),
5144 	    G_FW_HDR_FW_VER_MICRO(sc->params.tp_vers),
5145 	    G_FW_HDR_FW_VER_BUILD(sc->params.tp_vers));
5146 
5147 	snprintf(sc->er_version, sizeof(sc->er_version), "%u.%u.%u.%u",
5148 	    G_FW_HDR_FW_VER_MAJOR(sc->params.er_vers),
5149 	    G_FW_HDR_FW_VER_MINOR(sc->params.er_vers),
5150 	    G_FW_HDR_FW_VER_MICRO(sc->params.er_vers),
5151 	    G_FW_HDR_FW_VER_BUILD(sc->params.er_vers));
5152 
5153 	param[0] = FW_PARAM_DEV(PORTVEC);
5154 	param[1] = FW_PARAM_DEV(CCLK);
5155 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5156 	if (rc != 0) {
5157 		device_printf(sc->dev,
5158 		    "failed to query parameters (pre_init): %d.\n", rc);
5159 		return (rc);
5160 	}
5161 
5162 	sc->params.portvec = val[0];
5163 	sc->params.nports = bitcount32(val[0]);
5164 	sc->params.vpd.cclk = val[1];
5165 
5166 	/* Read device log parameters. */
5167 	rc = -t4_init_devlog_params(sc, 1);
5168 	if (rc == 0)
5169 		fixup_devlog_params(sc);
5170 	else {
5171 		device_printf(sc->dev,
5172 		    "failed to get devlog parameters: %d.\n", rc);
5173 		rc = 0;	/* devlog isn't critical for device operation */
5174 	}
5175 
5176 	return (rc);
5177 }
5178 
5179 /*
5180  * Any params that need to be set before FW_INITIALIZE.
5181  */
5182 static int
5183 set_params__pre_init(struct adapter *sc)
5184 {
5185 	int rc = 0;
5186 	uint32_t param, val;
5187 
5188 	if (chip_id(sc) >= CHELSIO_T6) {
5189 		param = FW_PARAM_DEV(HPFILTER_REGION_SUPPORT);
5190 		val = 1;
5191 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5192 		/* firmwares < 1.20.1.0 do not have this param. */
5193 		if (rc == FW_EINVAL &&
5194 		    sc->params.fw_vers < FW_VERSION32(1, 20, 1, 0)) {
5195 			rc = 0;
5196 		}
5197 		if (rc != 0) {
5198 			device_printf(sc->dev,
5199 			    "failed to enable high priority filters :%d.\n",
5200 			    rc);
5201 		}
5202 
5203 		param = FW_PARAM_DEV(PPOD_EDRAM);
5204 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5205 		if (rc == 0 && val == 1) {
5206 			rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param,
5207 			    &val);
5208 			if (rc != 0) {
5209 				device_printf(sc->dev,
5210 				    "failed to set PPOD_EDRAM: %d.\n", rc);
5211 			}
5212 		}
5213 	}
5214 
5215 	/* Enable opaque VIIDs with firmwares that support it. */
5216 	param = FW_PARAM_DEV(OPAQUE_VIID_SMT_EXTN);
5217 	val = 1;
5218 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5219 	if (rc == 0 && val == 1)
5220 		sc->params.viid_smt_extn_support = true;
5221 	else
5222 		sc->params.viid_smt_extn_support = false;
5223 
5224 	return (rc);
5225 }
5226 
5227 /*
5228  * Retrieve various parameters that are of interest to the driver.  The device
5229  * has been initialized by the firmware at this point.
5230  */
5231 static int
5232 get_params__post_init(struct adapter *sc)
5233 {
5234 	int rc;
5235 	uint32_t param[7], val[7];
5236 	struct fw_caps_config_cmd caps;
5237 
5238 	param[0] = FW_PARAM_PFVF(IQFLINT_START);
5239 	param[1] = FW_PARAM_PFVF(EQ_START);
5240 	param[2] = FW_PARAM_PFVF(FILTER_START);
5241 	param[3] = FW_PARAM_PFVF(FILTER_END);
5242 	param[4] = FW_PARAM_PFVF(L2T_START);
5243 	param[5] = FW_PARAM_PFVF(L2T_END);
5244 	param[6] = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5245 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
5246 	    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
5247 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 7, param, val);
5248 	if (rc != 0) {
5249 		device_printf(sc->dev,
5250 		    "failed to query parameters (post_init): %d.\n", rc);
5251 		return (rc);
5252 	}
5253 
5254 	sc->sge.iq_start = val[0];
5255 	sc->sge.eq_start = val[1];
5256 	if ((int)val[3] > (int)val[2]) {
5257 		sc->tids.ftid_base = val[2];
5258 		sc->tids.ftid_end = val[3];
5259 		sc->tids.nftids = val[3] - val[2] + 1;
5260 	}
5261 	sc->vres.l2t.start = val[4];
5262 	sc->vres.l2t.size = val[5] - val[4] + 1;
5263 	KASSERT(sc->vres.l2t.size <= L2T_SIZE,
5264 	    ("%s: L2 table size (%u) larger than expected (%u)",
5265 	    __func__, sc->vres.l2t.size, L2T_SIZE));
5266 	sc->params.core_vdd = val[6];
5267 
5268 	param[0] = FW_PARAM_PFVF(IQFLINT_END);
5269 	param[1] = FW_PARAM_PFVF(EQ_END);
5270 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5271 	if (rc != 0) {
5272 		device_printf(sc->dev,
5273 		    "failed to query parameters (post_init2): %d.\n", rc);
5274 		return (rc);
5275 	}
5276 	MPASS((int)val[0] >= sc->sge.iq_start);
5277 	sc->sge.iqmap_sz = val[0] - sc->sge.iq_start + 1;
5278 	MPASS((int)val[1] >= sc->sge.eq_start);
5279 	sc->sge.eqmap_sz = val[1] - sc->sge.eq_start + 1;
5280 
5281 	if (chip_id(sc) >= CHELSIO_T6) {
5282 
5283 		sc->tids.tid_base = t4_read_reg(sc,
5284 		    A_LE_DB_ACTIVE_TABLE_START_INDEX);
5285 
5286 		param[0] = FW_PARAM_PFVF(HPFILTER_START);
5287 		param[1] = FW_PARAM_PFVF(HPFILTER_END);
5288 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5289 		if (rc != 0) {
5290 			device_printf(sc->dev,
5291 			   "failed to query hpfilter parameters: %d.\n", rc);
5292 			return (rc);
5293 		}
5294 		if ((int)val[1] > (int)val[0]) {
5295 			sc->tids.hpftid_base = val[0];
5296 			sc->tids.hpftid_end = val[1];
5297 			sc->tids.nhpftids = val[1] - val[0] + 1;
5298 
5299 			/*
5300 			 * These should go off if the layout changes and the
5301 			 * driver needs to catch up.
5302 			 */
5303 			MPASS(sc->tids.hpftid_base == 0);
5304 			MPASS(sc->tids.tid_base == sc->tids.nhpftids);
5305 		}
5306 
5307 		param[0] = FW_PARAM_PFVF(RAWF_START);
5308 		param[1] = FW_PARAM_PFVF(RAWF_END);
5309 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5310 		if (rc != 0) {
5311 			device_printf(sc->dev,
5312 			   "failed to query rawf parameters: %d.\n", rc);
5313 			return (rc);
5314 		}
5315 		if ((int)val[1] > (int)val[0]) {
5316 			sc->rawf_base = val[0];
5317 			sc->nrawf = val[1] - val[0] + 1;
5318 		}
5319 	}
5320 
5321 	/*
5322 	 * MPSBGMAP is queried separately because only recent firmwares support
5323 	 * it as a parameter and we don't want the compound query above to fail
5324 	 * on older firmwares.
5325 	 */
5326 	param[0] = FW_PARAM_DEV(MPSBGMAP);
5327 	val[0] = 0;
5328 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5329 	if (rc == 0)
5330 		sc->params.mps_bg_map = val[0];
5331 	else
5332 		sc->params.mps_bg_map = 0;
5333 
5334 	/*
5335 	 * Determine whether the firmware supports the filter2 work request.
5336 	 * This is queried separately for the same reason as MPSBGMAP above.
5337 	 */
5338 	param[0] = FW_PARAM_DEV(FILTER2_WR);
5339 	val[0] = 0;
5340 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5341 	if (rc == 0)
5342 		sc->params.filter2_wr_support = val[0] != 0;
5343 	else
5344 		sc->params.filter2_wr_support = 0;
5345 
5346 	/*
5347 	 * Find out whether we're allowed to use the ULPTX MEMWRITE DSGL.
5348 	 * This is queried separately for the same reason as other params above.
5349 	 */
5350 	param[0] = FW_PARAM_DEV(ULPTX_MEMWRITE_DSGL);
5351 	val[0] = 0;
5352 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5353 	if (rc == 0)
5354 		sc->params.ulptx_memwrite_dsgl = val[0] != 0;
5355 	else
5356 		sc->params.ulptx_memwrite_dsgl = false;
5357 
5358 	/* FW_RI_FR_NSMR_TPTE_WR support */
5359 	param[0] = FW_PARAM_DEV(RI_FR_NSMR_TPTE_WR);
5360 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5361 	if (rc == 0)
5362 		sc->params.fr_nsmr_tpte_wr_support = val[0] != 0;
5363 	else
5364 		sc->params.fr_nsmr_tpte_wr_support = false;
5365 
5366 	/* Support for 512 SGL entries per FR MR. */
5367 	param[0] = FW_PARAM_DEV(DEV_512SGL_MR);
5368 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5369 	if (rc == 0)
5370 		sc->params.dev_512sgl_mr = val[0] != 0;
5371 	else
5372 		sc->params.dev_512sgl_mr = false;
5373 
5374 	param[0] = FW_PARAM_PFVF(MAX_PKTS_PER_ETH_TX_PKTS_WR);
5375 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5376 	if (rc == 0)
5377 		sc->params.max_pkts_per_eth_tx_pkts_wr = val[0];
5378 	else
5379 		sc->params.max_pkts_per_eth_tx_pkts_wr = 15;
5380 
5381 	param[0] = FW_PARAM_DEV(NUM_TM_CLASS);
5382 	rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5383 	if (rc == 0) {
5384 		MPASS(val[0] > 0 && val[0] < 256);	/* nsched_cls is 8b */
5385 		sc->params.nsched_cls = val[0];
5386 	} else
5387 		sc->params.nsched_cls = sc->chip_params->nsched_cls;
5388 
5389 	/* get capabilites */
5390 	bzero(&caps, sizeof(caps));
5391 	caps.op_to_write = htobe32(V_FW_CMD_OP(FW_CAPS_CONFIG_CMD) |
5392 	    F_FW_CMD_REQUEST | F_FW_CMD_READ);
5393 	caps.cfvalid_to_len16 = htobe32(FW_LEN16(caps));
5394 	rc = -t4_wr_mbox(sc, sc->mbox, &caps, sizeof(caps), &caps);
5395 	if (rc != 0) {
5396 		device_printf(sc->dev,
5397 		    "failed to get card capabilities: %d.\n", rc);
5398 		return (rc);
5399 	}
5400 
5401 #define READ_CAPS(x) do { \
5402 	sc->x = htobe16(caps.x); \
5403 } while (0)
5404 	READ_CAPS(nbmcaps);
5405 	READ_CAPS(linkcaps);
5406 	READ_CAPS(switchcaps);
5407 	READ_CAPS(niccaps);
5408 	READ_CAPS(toecaps);
5409 	READ_CAPS(rdmacaps);
5410 	READ_CAPS(cryptocaps);
5411 	READ_CAPS(iscsicaps);
5412 	READ_CAPS(fcoecaps);
5413 
5414 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_HASHFILTER) {
5415 		MPASS(chip_id(sc) > CHELSIO_T4);
5416 		MPASS(sc->toecaps == 0);
5417 		sc->toecaps = 0;
5418 
5419 		param[0] = FW_PARAM_DEV(NTID);
5420 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, param, val);
5421 		if (rc != 0) {
5422 			device_printf(sc->dev,
5423 			    "failed to query HASHFILTER parameters: %d.\n", rc);
5424 			return (rc);
5425 		}
5426 		sc->tids.ntids = val[0];
5427 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5428 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5429 			sc->tids.ntids -= sc->tids.nhpftids;
5430 		}
5431 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5432 		sc->params.hash_filter = 1;
5433 	}
5434 	if (sc->niccaps & FW_CAPS_CONFIG_NIC_ETHOFLD) {
5435 		param[0] = FW_PARAM_PFVF(ETHOFLD_START);
5436 		param[1] = FW_PARAM_PFVF(ETHOFLD_END);
5437 		param[2] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5438 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 3, param, val);
5439 		if (rc != 0) {
5440 			device_printf(sc->dev,
5441 			    "failed to query NIC parameters: %d.\n", rc);
5442 			return (rc);
5443 		}
5444 		if ((int)val[1] > (int)val[0]) {
5445 			sc->tids.etid_base = val[0];
5446 			sc->tids.etid_end = val[1];
5447 			sc->tids.netids = val[1] - val[0] + 1;
5448 			sc->params.eo_wr_cred = val[2];
5449 			sc->params.ethoffload = 1;
5450 		}
5451 	}
5452 	if (sc->toecaps) {
5453 		/* query offload-related parameters */
5454 		param[0] = FW_PARAM_DEV(NTID);
5455 		param[1] = FW_PARAM_PFVF(SERVER_START);
5456 		param[2] = FW_PARAM_PFVF(SERVER_END);
5457 		param[3] = FW_PARAM_PFVF(TDDP_START);
5458 		param[4] = FW_PARAM_PFVF(TDDP_END);
5459 		param[5] = FW_PARAM_DEV(FLOWC_BUFFIFO_SZ);
5460 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5461 		if (rc != 0) {
5462 			device_printf(sc->dev,
5463 			    "failed to query TOE parameters: %d.\n", rc);
5464 			return (rc);
5465 		}
5466 		sc->tids.ntids = val[0];
5467 		if (sc->params.fw_vers < FW_VERSION32(1, 20, 5, 0)) {
5468 			MPASS(sc->tids.ntids >= sc->tids.nhpftids);
5469 			sc->tids.ntids -= sc->tids.nhpftids;
5470 		}
5471 		sc->tids.natids = min(sc->tids.ntids / 2, MAX_ATIDS);
5472 		if ((int)val[2] > (int)val[1]) {
5473 			sc->tids.stid_base = val[1];
5474 			sc->tids.nstids = val[2] - val[1] + 1;
5475 		}
5476 		sc->vres.ddp.start = val[3];
5477 		sc->vres.ddp.size = val[4] - val[3] + 1;
5478 		sc->params.ofldq_wr_cred = val[5];
5479 		sc->params.offload = 1;
5480 	} else {
5481 		/*
5482 		 * The firmware attempts memfree TOE configuration for -SO cards
5483 		 * and will report toecaps=0 if it runs out of resources (this
5484 		 * depends on the config file).  It may not report 0 for other
5485 		 * capabilities dependent on the TOE in this case.  Set them to
5486 		 * 0 here so that the driver doesn't bother tracking resources
5487 		 * that will never be used.
5488 		 */
5489 		sc->iscsicaps = 0;
5490 		sc->rdmacaps = 0;
5491 	}
5492 	if (sc->rdmacaps) {
5493 		param[0] = FW_PARAM_PFVF(STAG_START);
5494 		param[1] = FW_PARAM_PFVF(STAG_END);
5495 		param[2] = FW_PARAM_PFVF(RQ_START);
5496 		param[3] = FW_PARAM_PFVF(RQ_END);
5497 		param[4] = FW_PARAM_PFVF(PBL_START);
5498 		param[5] = FW_PARAM_PFVF(PBL_END);
5499 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5500 		if (rc != 0) {
5501 			device_printf(sc->dev,
5502 			    "failed to query RDMA parameters(1): %d.\n", rc);
5503 			return (rc);
5504 		}
5505 		sc->vres.stag.start = val[0];
5506 		sc->vres.stag.size = val[1] - val[0] + 1;
5507 		sc->vres.rq.start = val[2];
5508 		sc->vres.rq.size = val[3] - val[2] + 1;
5509 		sc->vres.pbl.start = val[4];
5510 		sc->vres.pbl.size = val[5] - val[4] + 1;
5511 
5512 		param[0] = FW_PARAM_PFVF(SQRQ_START);
5513 		param[1] = FW_PARAM_PFVF(SQRQ_END);
5514 		param[2] = FW_PARAM_PFVF(CQ_START);
5515 		param[3] = FW_PARAM_PFVF(CQ_END);
5516 		param[4] = FW_PARAM_PFVF(OCQ_START);
5517 		param[5] = FW_PARAM_PFVF(OCQ_END);
5518 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 6, param, val);
5519 		if (rc != 0) {
5520 			device_printf(sc->dev,
5521 			    "failed to query RDMA parameters(2): %d.\n", rc);
5522 			return (rc);
5523 		}
5524 		sc->vres.qp.start = val[0];
5525 		sc->vres.qp.size = val[1] - val[0] + 1;
5526 		sc->vres.cq.start = val[2];
5527 		sc->vres.cq.size = val[3] - val[2] + 1;
5528 		sc->vres.ocq.start = val[4];
5529 		sc->vres.ocq.size = val[5] - val[4] + 1;
5530 
5531 		param[0] = FW_PARAM_PFVF(SRQ_START);
5532 		param[1] = FW_PARAM_PFVF(SRQ_END);
5533 		param[2] = FW_PARAM_DEV(MAXORDIRD_QP);
5534 		param[3] = FW_PARAM_DEV(MAXIRD_ADAPTER);
5535 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 4, param, val);
5536 		if (rc != 0) {
5537 			device_printf(sc->dev,
5538 			    "failed to query RDMA parameters(3): %d.\n", rc);
5539 			return (rc);
5540 		}
5541 		sc->vres.srq.start = val[0];
5542 		sc->vres.srq.size = val[1] - val[0] + 1;
5543 		sc->params.max_ordird_qp = val[2];
5544 		sc->params.max_ird_adapter = val[3];
5545 	}
5546 	if (sc->iscsicaps) {
5547 		param[0] = FW_PARAM_PFVF(ISCSI_START);
5548 		param[1] = FW_PARAM_PFVF(ISCSI_END);
5549 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5550 		if (rc != 0) {
5551 			device_printf(sc->dev,
5552 			    "failed to query iSCSI parameters: %d.\n", rc);
5553 			return (rc);
5554 		}
5555 		sc->vres.iscsi.start = val[0];
5556 		sc->vres.iscsi.size = val[1] - val[0] + 1;
5557 	}
5558 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
5559 		param[0] = FW_PARAM_PFVF(TLS_START);
5560 		param[1] = FW_PARAM_PFVF(TLS_END);
5561 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 2, param, val);
5562 		if (rc != 0) {
5563 			device_printf(sc->dev,
5564 			    "failed to query TLS parameters: %d.\n", rc);
5565 			return (rc);
5566 		}
5567 		sc->vres.key.start = val[0];
5568 		sc->vres.key.size = val[1] - val[0] + 1;
5569 	}
5570 
5571 	/*
5572 	 * We've got the params we wanted to query directly from the firmware.
5573 	 * Grab some others via other means.
5574 	 */
5575 	t4_init_sge_params(sc);
5576 	t4_init_tp_params(sc);
5577 	t4_read_mtu_tbl(sc, sc->params.mtus, NULL);
5578 	t4_load_mtus(sc, sc->params.mtus, sc->params.a_wnd, sc->params.b_wnd);
5579 
5580 	rc = t4_verify_chip_settings(sc);
5581 	if (rc != 0)
5582 		return (rc);
5583 	t4_init_rx_buf_info(sc);
5584 
5585 	return (rc);
5586 }
5587 
5588 #ifdef KERN_TLS
5589 static void
5590 ktls_tick(void *arg)
5591 {
5592 	struct adapter *sc;
5593 	uint32_t tstamp;
5594 
5595 	sc = arg;
5596 	tstamp = tcp_ts_getticks();
5597 	t4_write_reg(sc, A_TP_SYNC_TIME_HI, tstamp >> 1);
5598 	t4_write_reg(sc, A_TP_SYNC_TIME_LO, tstamp << 31);
5599 	callout_schedule_sbt(&sc->ktls_tick, SBT_1MS, 0, C_HARDCLOCK);
5600 }
5601 
5602 static int
5603 t6_config_kern_tls(struct adapter *sc, bool enable)
5604 {
5605 	int rc;
5606 	uint32_t param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
5607 	    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_KTLS_HW) |
5608 	    V_FW_PARAMS_PARAM_Y(enable ? 1 : 0) |
5609 	    V_FW_PARAMS_PARAM_Z(FW_PARAMS_PARAM_DEV_KTLS_HW_USER_ENABLE);
5610 
5611 	rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &param);
5612 	if (rc != 0) {
5613 		CH_ERR(sc, "failed to %s NIC TLS: %d\n",
5614 		    enable ?  "enable" : "disable", rc);
5615 		return (rc);
5616 	}
5617 
5618 	if (enable) {
5619 		sc->flags |= KERN_TLS_ON;
5620 		callout_reset_sbt(&sc->ktls_tick, SBT_1MS, 0, ktls_tick, sc,
5621 		    C_HARDCLOCK);
5622 	} else {
5623 		sc->flags &= ~KERN_TLS_ON;
5624 		callout_stop(&sc->ktls_tick);
5625 	}
5626 
5627 	return (rc);
5628 }
5629 #endif
5630 
5631 static int
5632 set_params__post_init(struct adapter *sc)
5633 {
5634 	uint32_t mask, param, val;
5635 #ifdef TCP_OFFLOAD
5636 	int i, v, shift;
5637 #endif
5638 
5639 	/* ask for encapsulated CPLs */
5640 	param = FW_PARAM_PFVF(CPLFW4MSG_ENCAP);
5641 	val = 1;
5642 	(void)t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
5643 
5644 	/* Enable 32b port caps if the firmware supports it. */
5645 	param = FW_PARAM_PFVF(PORT_CAPS32);
5646 	val = 1;
5647 	if (t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val) == 0)
5648 		sc->params.port_caps32 = 1;
5649 
5650 	/* Let filter + maskhash steer to a part of the VI's RSS region. */
5651 	val = 1 << (G_MASKSIZE(t4_read_reg(sc, A_TP_RSS_CONFIG_TNL)) - 1);
5652 	t4_set_reg_field(sc, A_TP_RSS_CONFIG_TNL, V_MASKFILTER(M_MASKFILTER),
5653 	    V_MASKFILTER(val - 1));
5654 
5655 	mask = F_DROPERRORANY | F_DROPERRORMAC | F_DROPERRORIPVER |
5656 	    F_DROPERRORFRAG | F_DROPERRORATTACK | F_DROPERRORETHHDRLEN |
5657 	    F_DROPERRORIPHDRLEN | F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5658 	    F_DROPERRORTCPOPT | F_DROPERRORCSUMIP | F_DROPERRORCSUM;
5659 	val = 0;
5660 	if (chip_id(sc) < CHELSIO_T6 && t4_attack_filter != 0) {
5661 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_ATTACKFILTERENABLE,
5662 		    F_ATTACKFILTERENABLE);
5663 		val |= F_DROPERRORATTACK;
5664 	}
5665 	if (t4_drop_ip_fragments != 0) {
5666 		t4_set_reg_field(sc, A_TP_GLOBAL_CONFIG, F_FRAGMENTDROP,
5667 		    F_FRAGMENTDROP);
5668 		val |= F_DROPERRORFRAG;
5669 	}
5670 	if (t4_drop_pkts_with_l2_errors != 0)
5671 		val |= F_DROPERRORMAC | F_DROPERRORETHHDRLEN;
5672 	if (t4_drop_pkts_with_l3_errors != 0) {
5673 		val |= F_DROPERRORIPVER | F_DROPERRORIPHDRLEN |
5674 		    F_DROPERRORCSUMIP;
5675 	}
5676 	if (t4_drop_pkts_with_l4_errors != 0) {
5677 		val |= F_DROPERRORTCPHDRLEN | F_DROPERRORPKTLEN |
5678 		    F_DROPERRORTCPOPT | F_DROPERRORCSUM;
5679 	}
5680 	t4_set_reg_field(sc, A_TP_ERR_CONFIG, mask, val);
5681 
5682 #ifdef TCP_OFFLOAD
5683 	/*
5684 	 * Override the TOE timers with user provided tunables.  This is not the
5685 	 * recommended way to change the timers (the firmware config file is) so
5686 	 * these tunables are not documented.
5687 	 *
5688 	 * All the timer tunables are in microseconds.
5689 	 */
5690 	if (t4_toe_keepalive_idle != 0) {
5691 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_idle);
5692 		v &= M_KEEPALIVEIDLE;
5693 		t4_set_reg_field(sc, A_TP_KEEP_IDLE,
5694 		    V_KEEPALIVEIDLE(M_KEEPALIVEIDLE), V_KEEPALIVEIDLE(v));
5695 	}
5696 	if (t4_toe_keepalive_interval != 0) {
5697 		v = us_to_tcp_ticks(sc, t4_toe_keepalive_interval);
5698 		v &= M_KEEPALIVEINTVL;
5699 		t4_set_reg_field(sc, A_TP_KEEP_INTVL,
5700 		    V_KEEPALIVEINTVL(M_KEEPALIVEINTVL), V_KEEPALIVEINTVL(v));
5701 	}
5702 	if (t4_toe_keepalive_count != 0) {
5703 		v = t4_toe_keepalive_count & M_KEEPALIVEMAXR2;
5704 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5705 		    V_KEEPALIVEMAXR1(M_KEEPALIVEMAXR1) |
5706 		    V_KEEPALIVEMAXR2(M_KEEPALIVEMAXR2),
5707 		    V_KEEPALIVEMAXR1(1) | V_KEEPALIVEMAXR2(v));
5708 	}
5709 	if (t4_toe_rexmt_min != 0) {
5710 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_min);
5711 		v &= M_RXTMIN;
5712 		t4_set_reg_field(sc, A_TP_RXT_MIN,
5713 		    V_RXTMIN(M_RXTMIN), V_RXTMIN(v));
5714 	}
5715 	if (t4_toe_rexmt_max != 0) {
5716 		v = us_to_tcp_ticks(sc, t4_toe_rexmt_max);
5717 		v &= M_RXTMAX;
5718 		t4_set_reg_field(sc, A_TP_RXT_MAX,
5719 		    V_RXTMAX(M_RXTMAX), V_RXTMAX(v));
5720 	}
5721 	if (t4_toe_rexmt_count != 0) {
5722 		v = t4_toe_rexmt_count & M_RXTSHIFTMAXR2;
5723 		t4_set_reg_field(sc, A_TP_SHIFT_CNT,
5724 		    V_RXTSHIFTMAXR1(M_RXTSHIFTMAXR1) |
5725 		    V_RXTSHIFTMAXR2(M_RXTSHIFTMAXR2),
5726 		    V_RXTSHIFTMAXR1(1) | V_RXTSHIFTMAXR2(v));
5727 	}
5728 	for (i = 0; i < nitems(t4_toe_rexmt_backoff); i++) {
5729 		if (t4_toe_rexmt_backoff[i] != -1) {
5730 			v = t4_toe_rexmt_backoff[i] & M_TIMERBACKOFFINDEX0;
5731 			shift = (i & 3) << 3;
5732 			t4_set_reg_field(sc, A_TP_TCP_BACKOFF_REG0 + (i & ~3),
5733 			    M_TIMERBACKOFFINDEX0 << shift, v << shift);
5734 		}
5735 	}
5736 #endif
5737 
5738 	/*
5739 	 * Limit TOE connections to 2 reassembly "islands".  This is
5740 	 * required to permit migrating TOE connections to either
5741 	 * ULP_MODE_TCPDDP or UPL_MODE_TLS.
5742 	 */
5743 	t4_tp_wr_bits_indirect(sc, A_TP_FRAG_CONFIG, V_PASSMODE(M_PASSMODE),
5744 	    V_PASSMODE(2));
5745 
5746 #ifdef KERN_TLS
5747 	if (is_ktls(sc)) {
5748 		sc->tlst.inline_keys = t4_tls_inline_keys;
5749 		sc->tlst.combo_wrs = t4_tls_combo_wrs;
5750 		if (t4_kern_tls != 0 && is_t6(sc))
5751 			t6_config_kern_tls(sc, true);
5752 	}
5753 #endif
5754 	return (0);
5755 }
5756 
5757 #undef FW_PARAM_PFVF
5758 #undef FW_PARAM_DEV
5759 
5760 static void
5761 t4_set_desc(struct adapter *sc)
5762 {
5763 	char buf[128];
5764 	struct adapter_params *p = &sc->params;
5765 
5766 	snprintf(buf, sizeof(buf), "Chelsio %s", p->vpd.id);
5767 
5768 	device_set_desc_copy(sc->dev, buf);
5769 }
5770 
5771 static inline void
5772 ifmedia_add4(struct ifmedia *ifm, int m)
5773 {
5774 
5775 	ifmedia_add(ifm, m, 0, NULL);
5776 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE, 0, NULL);
5777 	ifmedia_add(ifm, m | IFM_ETH_RXPAUSE, 0, NULL);
5778 	ifmedia_add(ifm, m | IFM_ETH_TXPAUSE | IFM_ETH_RXPAUSE, 0, NULL);
5779 }
5780 
5781 /*
5782  * This is the selected media, which is not quite the same as the active media.
5783  * The media line in ifconfig is "media: Ethernet selected (active)" if selected
5784  * and active are not the same, and "media: Ethernet selected" otherwise.
5785  */
5786 static void
5787 set_current_media(struct port_info *pi)
5788 {
5789 	struct link_config *lc;
5790 	struct ifmedia *ifm;
5791 	int mword;
5792 	u_int speed;
5793 
5794 	PORT_LOCK_ASSERT_OWNED(pi);
5795 
5796 	/* Leave current media alone if it's already set to IFM_NONE. */
5797 	ifm = &pi->media;
5798 	if (ifm->ifm_cur != NULL &&
5799 	    IFM_SUBTYPE(ifm->ifm_cur->ifm_media) == IFM_NONE)
5800 		return;
5801 
5802 	lc = &pi->link_cfg;
5803 	if (lc->requested_aneg != AUTONEG_DISABLE &&
5804 	    lc->pcaps & FW_PORT_CAP32_ANEG) {
5805 		ifmedia_set(ifm, IFM_ETHER | IFM_AUTO);
5806 		return;
5807 	}
5808 	mword = IFM_ETHER | IFM_FDX;
5809 	if (lc->requested_fc & PAUSE_TX)
5810 		mword |= IFM_ETH_TXPAUSE;
5811 	if (lc->requested_fc & PAUSE_RX)
5812 		mword |= IFM_ETH_RXPAUSE;
5813 	if (lc->requested_speed == 0)
5814 		speed = port_top_speed(pi) * 1000;	/* Gbps -> Mbps */
5815 	else
5816 		speed = lc->requested_speed;
5817 	mword |= port_mword(pi, speed_to_fwcap(speed));
5818 	ifmedia_set(ifm, mword);
5819 }
5820 
5821 /*
5822  * Returns true if the ifmedia list for the port cannot change.
5823  */
5824 static bool
5825 fixed_ifmedia(struct port_info *pi)
5826 {
5827 
5828 	return (pi->port_type == FW_PORT_TYPE_BT_SGMII ||
5829 	    pi->port_type == FW_PORT_TYPE_BT_XFI ||
5830 	    pi->port_type == FW_PORT_TYPE_BT_XAUI ||
5831 	    pi->port_type == FW_PORT_TYPE_KX4 ||
5832 	    pi->port_type == FW_PORT_TYPE_KX ||
5833 	    pi->port_type == FW_PORT_TYPE_KR ||
5834 	    pi->port_type == FW_PORT_TYPE_BP_AP ||
5835 	    pi->port_type == FW_PORT_TYPE_BP4_AP ||
5836 	    pi->port_type == FW_PORT_TYPE_BP40_BA ||
5837 	    pi->port_type == FW_PORT_TYPE_KR4_100G ||
5838 	    pi->port_type == FW_PORT_TYPE_KR_SFP28 ||
5839 	    pi->port_type == FW_PORT_TYPE_KR_XLAUI);
5840 }
5841 
5842 static void
5843 build_medialist(struct port_info *pi)
5844 {
5845 	uint32_t ss, speed;
5846 	int unknown, mword, bit;
5847 	struct link_config *lc;
5848 	struct ifmedia *ifm;
5849 
5850 	PORT_LOCK_ASSERT_OWNED(pi);
5851 
5852 	if (pi->flags & FIXED_IFMEDIA)
5853 		return;
5854 
5855 	/*
5856 	 * Rebuild the ifmedia list.
5857 	 */
5858 	ifm = &pi->media;
5859 	ifmedia_removeall(ifm);
5860 	lc = &pi->link_cfg;
5861 	ss = G_FW_PORT_CAP32_SPEED(lc->pcaps); /* Supported Speeds */
5862 	if (__predict_false(ss == 0)) {	/* not supposed to happen. */
5863 		MPASS(ss != 0);
5864 no_media:
5865 		MPASS(LIST_EMPTY(&ifm->ifm_list));
5866 		ifmedia_add(ifm, IFM_ETHER | IFM_NONE, 0, NULL);
5867 		ifmedia_set(ifm, IFM_ETHER | IFM_NONE);
5868 		return;
5869 	}
5870 
5871 	unknown = 0;
5872 	for (bit = S_FW_PORT_CAP32_SPEED; bit < fls(ss); bit++) {
5873 		speed = 1 << bit;
5874 		MPASS(speed & M_FW_PORT_CAP32_SPEED);
5875 		if (ss & speed) {
5876 			mword = port_mword(pi, speed);
5877 			if (mword == IFM_NONE) {
5878 				goto no_media;
5879 			} else if (mword == IFM_UNKNOWN)
5880 				unknown++;
5881 			else
5882 				ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | mword);
5883 		}
5884 	}
5885 	if (unknown > 0) /* Add one unknown for all unknown media types. */
5886 		ifmedia_add4(ifm, IFM_ETHER | IFM_FDX | IFM_UNKNOWN);
5887 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
5888 		ifmedia_add(ifm, IFM_ETHER | IFM_AUTO, 0, NULL);
5889 
5890 	set_current_media(pi);
5891 }
5892 
5893 /*
5894  * Initialize the requested fields in the link config based on driver tunables.
5895  */
5896 static void
5897 init_link_config(struct port_info *pi)
5898 {
5899 	struct link_config *lc = &pi->link_cfg;
5900 
5901 	PORT_LOCK_ASSERT_OWNED(pi);
5902 
5903 	lc->requested_caps = 0;
5904 	lc->requested_speed = 0;
5905 
5906 	if (t4_autoneg == 0)
5907 		lc->requested_aneg = AUTONEG_DISABLE;
5908 	else if (t4_autoneg == 1)
5909 		lc->requested_aneg = AUTONEG_ENABLE;
5910 	else
5911 		lc->requested_aneg = AUTONEG_AUTO;
5912 
5913 	lc->requested_fc = t4_pause_settings & (PAUSE_TX | PAUSE_RX |
5914 	    PAUSE_AUTONEG);
5915 
5916 	if (t4_fec & FEC_AUTO)
5917 		lc->requested_fec = FEC_AUTO;
5918 	else if (t4_fec == 0)
5919 		lc->requested_fec = FEC_NONE;
5920 	else {
5921 		/* -1 is handled by the FEC_AUTO block above and not here. */
5922 		lc->requested_fec = t4_fec &
5923 		    (FEC_RS | FEC_BASER_RS | FEC_NONE | FEC_MODULE);
5924 		if (lc->requested_fec == 0)
5925 			lc->requested_fec = FEC_AUTO;
5926 	}
5927 	if (t4_force_fec < 0)
5928 		lc->force_fec = -1;
5929 	else if (t4_force_fec > 0)
5930 		lc->force_fec = 1;
5931 	else
5932 		lc->force_fec = 0;
5933 }
5934 
5935 /*
5936  * Makes sure that all requested settings comply with what's supported by the
5937  * port.  Returns the number of settings that were invalid and had to be fixed.
5938  */
5939 static int
5940 fixup_link_config(struct port_info *pi)
5941 {
5942 	int n = 0;
5943 	struct link_config *lc = &pi->link_cfg;
5944 	uint32_t fwspeed;
5945 
5946 	PORT_LOCK_ASSERT_OWNED(pi);
5947 
5948 	/* Speed (when not autonegotiating) */
5949 	if (lc->requested_speed != 0) {
5950 		fwspeed = speed_to_fwcap(lc->requested_speed);
5951 		if ((fwspeed & lc->pcaps) == 0) {
5952 			n++;
5953 			lc->requested_speed = 0;
5954 		}
5955 	}
5956 
5957 	/* Link autonegotiation */
5958 	MPASS(lc->requested_aneg == AUTONEG_ENABLE ||
5959 	    lc->requested_aneg == AUTONEG_DISABLE ||
5960 	    lc->requested_aneg == AUTONEG_AUTO);
5961 	if (lc->requested_aneg == AUTONEG_ENABLE &&
5962 	    !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
5963 		n++;
5964 		lc->requested_aneg = AUTONEG_AUTO;
5965 	}
5966 
5967 	/* Flow control */
5968 	MPASS((lc->requested_fc & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG)) == 0);
5969 	if (lc->requested_fc & PAUSE_TX &&
5970 	    !(lc->pcaps & FW_PORT_CAP32_FC_TX)) {
5971 		n++;
5972 		lc->requested_fc &= ~PAUSE_TX;
5973 	}
5974 	if (lc->requested_fc & PAUSE_RX &&
5975 	    !(lc->pcaps & FW_PORT_CAP32_FC_RX)) {
5976 		n++;
5977 		lc->requested_fc &= ~PAUSE_RX;
5978 	}
5979 	if (!(lc->requested_fc & PAUSE_AUTONEG) &&
5980 	    !(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE)) {
5981 		n++;
5982 		lc->requested_fc |= PAUSE_AUTONEG;
5983 	}
5984 
5985 	/* FEC */
5986 	if ((lc->requested_fec & FEC_RS &&
5987 	    !(lc->pcaps & FW_PORT_CAP32_FEC_RS)) ||
5988 	    (lc->requested_fec & FEC_BASER_RS &&
5989 	    !(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS))) {
5990 		n++;
5991 		lc->requested_fec = FEC_AUTO;
5992 	}
5993 
5994 	return (n);
5995 }
5996 
5997 /*
5998  * Apply the requested L1 settings, which are expected to be valid, to the
5999  * hardware.
6000  */
6001 static int
6002 apply_link_config(struct port_info *pi)
6003 {
6004 	struct adapter *sc = pi->adapter;
6005 	struct link_config *lc = &pi->link_cfg;
6006 	int rc;
6007 
6008 #ifdef INVARIANTS
6009 	ASSERT_SYNCHRONIZED_OP(sc);
6010 	PORT_LOCK_ASSERT_OWNED(pi);
6011 
6012 	if (lc->requested_aneg == AUTONEG_ENABLE)
6013 		MPASS(lc->pcaps & FW_PORT_CAP32_ANEG);
6014 	if (!(lc->requested_fc & PAUSE_AUTONEG))
6015 		MPASS(lc->pcaps & FW_PORT_CAP32_FORCE_PAUSE);
6016 	if (lc->requested_fc & PAUSE_TX)
6017 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_TX);
6018 	if (lc->requested_fc & PAUSE_RX)
6019 		MPASS(lc->pcaps & FW_PORT_CAP32_FC_RX);
6020 	if (lc->requested_fec & FEC_RS)
6021 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_RS);
6022 	if (lc->requested_fec & FEC_BASER_RS)
6023 		MPASS(lc->pcaps & FW_PORT_CAP32_FEC_BASER_RS);
6024 #endif
6025 	rc = -t4_link_l1cfg(sc, sc->mbox, pi->tx_chan, lc);
6026 	if (rc != 0) {
6027 		/* Don't complain if the VF driver gets back an EPERM. */
6028 		if (!(sc->flags & IS_VF) || rc != FW_EPERM)
6029 			device_printf(pi->dev, "l1cfg failed: %d\n", rc);
6030 	} else {
6031 		/*
6032 		 * An L1_CFG will almost always result in a link-change event if
6033 		 * the link is up, and the driver will refresh the actual
6034 		 * fec/fc/etc. when the notification is processed.  If the link
6035 		 * is down then the actual settings are meaningless.
6036 		 *
6037 		 * This takes care of the case where a change in the L1 settings
6038 		 * may not result in a notification.
6039 		 */
6040 		if (lc->link_ok && !(lc->requested_fc & PAUSE_AUTONEG))
6041 			lc->fc = lc->requested_fc & (PAUSE_TX | PAUSE_RX);
6042 	}
6043 	return (rc);
6044 }
6045 
6046 #define FW_MAC_EXACT_CHUNK	7
6047 struct mcaddr_ctx {
6048 	if_t ifp;
6049 	const uint8_t *mcaddr[FW_MAC_EXACT_CHUNK];
6050 	uint64_t hash;
6051 	int i;
6052 	int del;
6053 	int rc;
6054 };
6055 
6056 static u_int
6057 add_maddr(void *arg, struct sockaddr_dl *sdl, u_int cnt)
6058 {
6059 	struct mcaddr_ctx *ctx = arg;
6060 	struct vi_info *vi = if_getsoftc(ctx->ifp);
6061 	struct port_info *pi = vi->pi;
6062 	struct adapter *sc = pi->adapter;
6063 
6064 	if (ctx->rc < 0)
6065 		return (0);
6066 
6067 	ctx->mcaddr[ctx->i] = LLADDR(sdl);
6068 	MPASS(ETHER_IS_MULTICAST(ctx->mcaddr[ctx->i]));
6069 	ctx->i++;
6070 
6071 	if (ctx->i == FW_MAC_EXACT_CHUNK) {
6072 		ctx->rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid, ctx->del,
6073 		    ctx->i, ctx->mcaddr, NULL, &ctx->hash, 0);
6074 		if (ctx->rc < 0) {
6075 			int j;
6076 
6077 			for (j = 0; j < ctx->i; j++) {
6078 				if_printf(ctx->ifp,
6079 				    "failed to add mc address"
6080 				    " %02x:%02x:%02x:"
6081 				    "%02x:%02x:%02x rc=%d\n",
6082 				    ctx->mcaddr[j][0], ctx->mcaddr[j][1],
6083 				    ctx->mcaddr[j][2], ctx->mcaddr[j][3],
6084 				    ctx->mcaddr[j][4], ctx->mcaddr[j][5],
6085 				    -ctx->rc);
6086 			}
6087 			return (0);
6088 		}
6089 		ctx->del = 0;
6090 		ctx->i = 0;
6091 	}
6092 
6093 	return (1);
6094 }
6095 
6096 /*
6097  * Program the port's XGMAC based on parameters in ifnet.  The caller also
6098  * indicates which parameters should be programmed (the rest are left alone).
6099  */
6100 int
6101 update_mac_settings(if_t ifp, int flags)
6102 {
6103 	int rc = 0;
6104 	struct vi_info *vi = if_getsoftc(ifp);
6105 	struct port_info *pi = vi->pi;
6106 	struct adapter *sc = pi->adapter;
6107 	int mtu = -1, promisc = -1, allmulti = -1, vlanex = -1;
6108 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
6109 
6110 	ASSERT_SYNCHRONIZED_OP(sc);
6111 	KASSERT(flags, ("%s: not told what to update.", __func__));
6112 
6113 	if (flags & XGMAC_MTU)
6114 		mtu = if_getmtu(ifp);
6115 
6116 	if (flags & XGMAC_PROMISC)
6117 		promisc = if_getflags(ifp) & IFF_PROMISC ? 1 : 0;
6118 
6119 	if (flags & XGMAC_ALLMULTI)
6120 		allmulti = if_getflags(ifp) & IFF_ALLMULTI ? 1 : 0;
6121 
6122 	if (flags & XGMAC_VLANEX)
6123 		vlanex = if_getcapenable(ifp) & IFCAP_VLAN_HWTAGGING ? 1 : 0;
6124 
6125 	if (flags & (XGMAC_MTU|XGMAC_PROMISC|XGMAC_ALLMULTI|XGMAC_VLANEX)) {
6126 		rc = -t4_set_rxmode(sc, sc->mbox, vi->viid, mtu, promisc,
6127 		    allmulti, 1, vlanex, false);
6128 		if (rc) {
6129 			if_printf(ifp, "set_rxmode (%x) failed: %d\n", flags,
6130 			    rc);
6131 			return (rc);
6132 		}
6133 	}
6134 
6135 	if (flags & XGMAC_UCADDR) {
6136 		uint8_t ucaddr[ETHER_ADDR_LEN];
6137 
6138 		bcopy(if_getlladdr(ifp), ucaddr, sizeof(ucaddr));
6139 		rc = t4_change_mac(sc, sc->mbox, vi->viid, vi->xact_addr_filt,
6140 		    ucaddr, true, &vi->smt_idx);
6141 		if (rc < 0) {
6142 			rc = -rc;
6143 			if_printf(ifp, "change_mac failed: %d\n", rc);
6144 			return (rc);
6145 		} else {
6146 			vi->xact_addr_filt = rc;
6147 			rc = 0;
6148 		}
6149 	}
6150 
6151 	if (flags & XGMAC_MCADDRS) {
6152 		struct epoch_tracker et;
6153 		struct mcaddr_ctx ctx;
6154 		int j;
6155 
6156 		ctx.ifp = ifp;
6157 		ctx.hash = 0;
6158 		ctx.i = 0;
6159 		ctx.del = 1;
6160 		ctx.rc = 0;
6161 		/*
6162 		 * Unlike other drivers, we accumulate list of pointers into
6163 		 * interface address lists and we need to keep it safe even
6164 		 * after if_foreach_llmaddr() returns, thus we must enter the
6165 		 * network epoch.
6166 		 */
6167 		NET_EPOCH_ENTER(et);
6168 		if_foreach_llmaddr(ifp, add_maddr, &ctx);
6169 		if (ctx.rc < 0) {
6170 			NET_EPOCH_EXIT(et);
6171 			rc = -ctx.rc;
6172 			return (rc);
6173 		}
6174 		if (ctx.i > 0) {
6175 			rc = t4_alloc_mac_filt(sc, sc->mbox, vi->viid,
6176 			    ctx.del, ctx.i, ctx.mcaddr, NULL, &ctx.hash, 0);
6177 			NET_EPOCH_EXIT(et);
6178 			if (rc < 0) {
6179 				rc = -rc;
6180 				for (j = 0; j < ctx.i; j++) {
6181 					if_printf(ifp,
6182 					    "failed to add mcast address"
6183 					    " %02x:%02x:%02x:"
6184 					    "%02x:%02x:%02x rc=%d\n",
6185 					    ctx.mcaddr[j][0], ctx.mcaddr[j][1],
6186 					    ctx.mcaddr[j][2], ctx.mcaddr[j][3],
6187 					    ctx.mcaddr[j][4], ctx.mcaddr[j][5],
6188 					    rc);
6189 				}
6190 				return (rc);
6191 			}
6192 			ctx.del = 0;
6193 		} else
6194 			NET_EPOCH_EXIT(et);
6195 
6196 		rc = -t4_set_addr_hash(sc, sc->mbox, vi->viid, 0, ctx.hash, 0);
6197 		if (rc != 0)
6198 			if_printf(ifp, "failed to set mcast address hash: %d\n",
6199 			    rc);
6200 		if (ctx.del == 0) {
6201 			/* We clobbered the VXLAN entry if there was one. */
6202 			pi->vxlan_tcam_entry = false;
6203 		}
6204 	}
6205 
6206 	if (IS_MAIN_VI(vi) && sc->vxlan_refcount > 0 &&
6207 	    pi->vxlan_tcam_entry == false) {
6208 		rc = t4_alloc_raw_mac_filt(sc, vi->viid, match_all_mac,
6209 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
6210 		    true);
6211 		if (rc < 0) {
6212 			rc = -rc;
6213 			if_printf(ifp, "failed to add VXLAN TCAM entry: %d.\n",
6214 			    rc);
6215 		} else {
6216 			MPASS(rc == sc->rawf_base + pi->port_id);
6217 			rc = 0;
6218 			pi->vxlan_tcam_entry = true;
6219 		}
6220 	}
6221 
6222 	return (rc);
6223 }
6224 
6225 /*
6226  * {begin|end}_synchronized_op must be called from the same thread.
6227  */
6228 int
6229 begin_synchronized_op(struct adapter *sc, struct vi_info *vi, int flags,
6230     char *wmesg)
6231 {
6232 	int rc, pri;
6233 
6234 #ifdef WITNESS
6235 	/* the caller thinks it's ok to sleep, but is it really? */
6236 	if (flags & SLEEP_OK)
6237 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
6238 		    "begin_synchronized_op");
6239 #endif
6240 
6241 	if (INTR_OK)
6242 		pri = PCATCH;
6243 	else
6244 		pri = 0;
6245 
6246 	ADAPTER_LOCK(sc);
6247 	for (;;) {
6248 
6249 		if (vi && IS_DETACHING(vi)) {
6250 			rc = ENXIO;
6251 			goto done;
6252 		}
6253 
6254 		if (!IS_BUSY(sc)) {
6255 			rc = 0;
6256 			break;
6257 		}
6258 
6259 		if (!(flags & SLEEP_OK)) {
6260 			rc = EBUSY;
6261 			goto done;
6262 		}
6263 
6264 		if (mtx_sleep(&sc->flags, &sc->sc_lock, pri, wmesg, 0)) {
6265 			rc = EINTR;
6266 			goto done;
6267 		}
6268 	}
6269 
6270 	KASSERT(!IS_BUSY(sc), ("%s: controller busy.", __func__));
6271 	SET_BUSY(sc);
6272 #ifdef INVARIANTS
6273 	sc->last_op = wmesg;
6274 	sc->last_op_thr = curthread;
6275 	sc->last_op_flags = flags;
6276 #endif
6277 
6278 done:
6279 	if (!(flags & HOLD_LOCK) || rc)
6280 		ADAPTER_UNLOCK(sc);
6281 
6282 	return (rc);
6283 }
6284 
6285 /*
6286  * Tell if_ioctl and if_init that the VI is going away.  This is
6287  * special variant of begin_synchronized_op and must be paired with a
6288  * call to end_vi_detach.
6289  */
6290 void
6291 begin_vi_detach(struct adapter *sc, struct vi_info *vi)
6292 {
6293 	ADAPTER_LOCK(sc);
6294 	SET_DETACHING(vi);
6295 	wakeup(&sc->flags);
6296 	while (IS_BUSY(sc))
6297 		mtx_sleep(&sc->flags, &sc->sc_lock, 0, "t4detach", 0);
6298 	SET_BUSY(sc);
6299 #ifdef INVARIANTS
6300 	sc->last_op = "t4detach";
6301 	sc->last_op_thr = curthread;
6302 	sc->last_op_flags = 0;
6303 #endif
6304 	ADAPTER_UNLOCK(sc);
6305 }
6306 
6307 void
6308 end_vi_detach(struct adapter *sc, struct vi_info *vi)
6309 {
6310 	ADAPTER_LOCK(sc);
6311 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6312 	CLR_BUSY(sc);
6313 	CLR_DETACHING(vi);
6314 	wakeup(&sc->flags);
6315 	ADAPTER_UNLOCK(sc);
6316 }
6317 
6318 /*
6319  * {begin|end}_synchronized_op must be called from the same thread.
6320  */
6321 void
6322 end_synchronized_op(struct adapter *sc, int flags)
6323 {
6324 
6325 	if (flags & LOCK_HELD)
6326 		ADAPTER_LOCK_ASSERT_OWNED(sc);
6327 	else
6328 		ADAPTER_LOCK(sc);
6329 
6330 	KASSERT(IS_BUSY(sc), ("%s: controller not busy.", __func__));
6331 	CLR_BUSY(sc);
6332 	wakeup(&sc->flags);
6333 	ADAPTER_UNLOCK(sc);
6334 }
6335 
6336 static int
6337 cxgbe_init_synchronized(struct vi_info *vi)
6338 {
6339 	struct port_info *pi = vi->pi;
6340 	struct adapter *sc = pi->adapter;
6341 	if_t ifp = vi->ifp;
6342 	int rc = 0, i;
6343 	struct sge_txq *txq;
6344 
6345 	ASSERT_SYNCHRONIZED_OP(sc);
6346 
6347 	if (if_getdrvflags(ifp) & IFF_DRV_RUNNING)
6348 		return (0);	/* already running */
6349 
6350 	if (!(sc->flags & FULL_INIT_DONE) && ((rc = adapter_init(sc)) != 0))
6351 		return (rc);	/* error message displayed already */
6352 
6353 	if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
6354 		return (rc); /* error message displayed already */
6355 
6356 	rc = update_mac_settings(ifp, XGMAC_ALL);
6357 	if (rc)
6358 		goto done;	/* error message displayed already */
6359 
6360 	PORT_LOCK(pi);
6361 	if (pi->up_vis == 0) {
6362 		t4_update_port_info(pi);
6363 		fixup_link_config(pi);
6364 		build_medialist(pi);
6365 		apply_link_config(pi);
6366 	}
6367 
6368 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, true, true);
6369 	if (rc != 0) {
6370 		if_printf(ifp, "enable_vi failed: %d\n", rc);
6371 		PORT_UNLOCK(pi);
6372 		goto done;
6373 	}
6374 
6375 	/*
6376 	 * Can't fail from this point onwards.  Review cxgbe_uninit_synchronized
6377 	 * if this changes.
6378 	 */
6379 
6380 	for_each_txq(vi, i, txq) {
6381 		TXQ_LOCK(txq);
6382 		txq->eq.flags |= EQ_ENABLED;
6383 		TXQ_UNLOCK(txq);
6384 	}
6385 
6386 	/*
6387 	 * The first iq of the first port to come up is used for tracing.
6388 	 */
6389 	if (sc->traceq < 0 && IS_MAIN_VI(vi)) {
6390 		sc->traceq = sc->sge.rxq[vi->first_rxq].iq.abs_id;
6391 		t4_write_reg(sc, is_t4(sc) ?  A_MPS_TRC_RSS_CONTROL :
6392 		    A_MPS_T5_TRC_RSS_CONTROL, V_RSSCONTROL(pi->tx_chan) |
6393 		    V_QUEUENUMBER(sc->traceq));
6394 		pi->flags |= HAS_TRACEQ;
6395 	}
6396 
6397 	/* all ok */
6398 	pi->up_vis++;
6399 	if_setdrvflagbits(ifp, IFF_DRV_RUNNING, 0);
6400 	if (pi->link_cfg.link_ok)
6401 		t4_os_link_changed(pi);
6402 	PORT_UNLOCK(pi);
6403 
6404 	mtx_lock(&vi->tick_mtx);
6405 	if (vi->pi->nvi > 1 || sc->flags & IS_VF)
6406 		callout_reset(&vi->tick, hz, vi_tick, vi);
6407 	else
6408 		callout_reset(&vi->tick, hz, cxgbe_tick, vi);
6409 	mtx_unlock(&vi->tick_mtx);
6410 done:
6411 	if (rc != 0)
6412 		cxgbe_uninit_synchronized(vi);
6413 
6414 	return (rc);
6415 }
6416 
6417 /*
6418  * Idempotent.
6419  */
6420 static int
6421 cxgbe_uninit_synchronized(struct vi_info *vi)
6422 {
6423 	struct port_info *pi = vi->pi;
6424 	struct adapter *sc = pi->adapter;
6425 	if_t ifp = vi->ifp;
6426 	int rc, i;
6427 	struct sge_txq *txq;
6428 
6429 	ASSERT_SYNCHRONIZED_OP(sc);
6430 
6431 	if (!(vi->flags & VI_INIT_DONE)) {
6432 		if (__predict_false(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6433 			KASSERT(0, ("uninited VI is running"));
6434 			if_printf(ifp, "uninited VI with running ifnet.  "
6435 			    "vi->flags 0x%016lx, if_flags 0x%08x, "
6436 			    "if_drv_flags 0x%08x\n", vi->flags, if_getflags(ifp),
6437 			    if_getdrvflags(ifp));
6438 		}
6439 		return (0);
6440 	}
6441 
6442 	/*
6443 	 * Disable the VI so that all its data in either direction is discarded
6444 	 * by the MPS.  Leave everything else (the queues, interrupts, and 1Hz
6445 	 * tick) intact as the TP can deliver negative advice or data that it's
6446 	 * holding in its RAM (for an offloaded connection) even after the VI is
6447 	 * disabled.
6448 	 */
6449 	rc = -t4_enable_vi(sc, sc->mbox, vi->viid, false, false);
6450 	if (rc) {
6451 		if_printf(ifp, "disable_vi failed: %d\n", rc);
6452 		return (rc);
6453 	}
6454 
6455 	for_each_txq(vi, i, txq) {
6456 		TXQ_LOCK(txq);
6457 		txq->eq.flags &= ~EQ_ENABLED;
6458 		TXQ_UNLOCK(txq);
6459 	}
6460 
6461 	mtx_lock(&vi->tick_mtx);
6462 	callout_stop(&vi->tick);
6463 	mtx_unlock(&vi->tick_mtx);
6464 
6465 	PORT_LOCK(pi);
6466 	if (!(if_getdrvflags(ifp) & IFF_DRV_RUNNING)) {
6467 		PORT_UNLOCK(pi);
6468 		return (0);
6469 	}
6470 	if_setdrvflagbits(ifp, 0, IFF_DRV_RUNNING);
6471 	pi->up_vis--;
6472 	if (pi->up_vis > 0) {
6473 		PORT_UNLOCK(pi);
6474 		return (0);
6475 	}
6476 
6477 	pi->link_cfg.link_ok = false;
6478 	pi->link_cfg.speed = 0;
6479 	pi->link_cfg.link_down_rc = 255;
6480 	t4_os_link_changed(pi);
6481 	PORT_UNLOCK(pi);
6482 
6483 	return (0);
6484 }
6485 
6486 /*
6487  * It is ok for this function to fail midway and return right away.  t4_detach
6488  * will walk the entire sc->irq list and clean up whatever is valid.
6489  */
6490 int
6491 t4_setup_intr_handlers(struct adapter *sc)
6492 {
6493 	int rc, rid, p, q, v;
6494 	char s[8];
6495 	struct irq *irq;
6496 	struct port_info *pi;
6497 	struct vi_info *vi;
6498 	struct sge *sge = &sc->sge;
6499 	struct sge_rxq *rxq;
6500 #ifdef TCP_OFFLOAD
6501 	struct sge_ofld_rxq *ofld_rxq;
6502 #endif
6503 #ifdef DEV_NETMAP
6504 	struct sge_nm_rxq *nm_rxq;
6505 #endif
6506 #ifdef RSS
6507 	int nbuckets = rss_getnumbuckets();
6508 #endif
6509 
6510 	/*
6511 	 * Setup interrupts.
6512 	 */
6513 	irq = &sc->irq[0];
6514 	rid = sc->intr_type == INTR_INTX ? 0 : 1;
6515 	if (forwarding_intr_to_fwq(sc))
6516 		return (t4_alloc_irq(sc, irq, rid, t4_intr_all, sc, "all"));
6517 
6518 	/* Multiple interrupts. */
6519 	if (sc->flags & IS_VF)
6520 		KASSERT(sc->intr_count >= T4VF_EXTRA_INTR + sc->params.nports,
6521 		    ("%s: too few intr.", __func__));
6522 	else
6523 		KASSERT(sc->intr_count >= T4_EXTRA_INTR + sc->params.nports,
6524 		    ("%s: too few intr.", __func__));
6525 
6526 	/* The first one is always error intr on PFs */
6527 	if (!(sc->flags & IS_VF)) {
6528 		rc = t4_alloc_irq(sc, irq, rid, t4_intr_err, sc, "err");
6529 		if (rc != 0)
6530 			return (rc);
6531 		irq++;
6532 		rid++;
6533 	}
6534 
6535 	/* The second one is always the firmware event queue (first on VFs) */
6536 	rc = t4_alloc_irq(sc, irq, rid, t4_intr_evt, &sge->fwq, "evt");
6537 	if (rc != 0)
6538 		return (rc);
6539 	irq++;
6540 	rid++;
6541 
6542 	for_each_port(sc, p) {
6543 		pi = sc->port[p];
6544 		for_each_vi(pi, v, vi) {
6545 			vi->first_intr = rid - 1;
6546 
6547 			if (vi->nnmrxq > 0) {
6548 				int n = max(vi->nrxq, vi->nnmrxq);
6549 
6550 				rxq = &sge->rxq[vi->first_rxq];
6551 #ifdef DEV_NETMAP
6552 				nm_rxq = &sge->nm_rxq[vi->first_nm_rxq];
6553 #endif
6554 				for (q = 0; q < n; q++) {
6555 					snprintf(s, sizeof(s), "%x%c%x", p,
6556 					    'a' + v, q);
6557 					if (q < vi->nrxq)
6558 						irq->rxq = rxq++;
6559 #ifdef DEV_NETMAP
6560 					if (q < vi->nnmrxq)
6561 						irq->nm_rxq = nm_rxq++;
6562 
6563 					if (irq->nm_rxq != NULL &&
6564 					    irq->rxq == NULL) {
6565 						/* Netmap rx only */
6566 						rc = t4_alloc_irq(sc, irq, rid,
6567 						    t4_nm_intr, irq->nm_rxq, s);
6568 					}
6569 					if (irq->nm_rxq != NULL &&
6570 					    irq->rxq != NULL) {
6571 						/* NIC and Netmap rx */
6572 						rc = t4_alloc_irq(sc, irq, rid,
6573 						    t4_vi_intr, irq, s);
6574 					}
6575 #endif
6576 					if (irq->rxq != NULL &&
6577 					    irq->nm_rxq == NULL) {
6578 						/* NIC rx only */
6579 						rc = t4_alloc_irq(sc, irq, rid,
6580 						    t4_intr, irq->rxq, s);
6581 					}
6582 					if (rc != 0)
6583 						return (rc);
6584 #ifdef RSS
6585 					if (q < vi->nrxq) {
6586 						bus_bind_intr(sc->dev, irq->res,
6587 						    rss_getcpu(q % nbuckets));
6588 					}
6589 #endif
6590 					irq++;
6591 					rid++;
6592 					vi->nintr++;
6593 				}
6594 			} else {
6595 				for_each_rxq(vi, q, rxq) {
6596 					snprintf(s, sizeof(s), "%x%c%x", p,
6597 					    'a' + v, q);
6598 					rc = t4_alloc_irq(sc, irq, rid,
6599 					    t4_intr, rxq, s);
6600 					if (rc != 0)
6601 						return (rc);
6602 #ifdef RSS
6603 					bus_bind_intr(sc->dev, irq->res,
6604 					    rss_getcpu(q % nbuckets));
6605 #endif
6606 					irq++;
6607 					rid++;
6608 					vi->nintr++;
6609 				}
6610 			}
6611 #ifdef TCP_OFFLOAD
6612 			for_each_ofld_rxq(vi, q, ofld_rxq) {
6613 				snprintf(s, sizeof(s), "%x%c%x", p, 'A' + v, q);
6614 				rc = t4_alloc_irq(sc, irq, rid, t4_intr,
6615 				    ofld_rxq, s);
6616 				if (rc != 0)
6617 					return (rc);
6618 				irq++;
6619 				rid++;
6620 				vi->nintr++;
6621 			}
6622 #endif
6623 		}
6624 	}
6625 	MPASS(irq == &sc->irq[sc->intr_count]);
6626 
6627 	return (0);
6628 }
6629 
6630 static void
6631 write_global_rss_key(struct adapter *sc)
6632 {
6633 #ifdef RSS
6634 	int i;
6635 	uint32_t raw_rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6636 	uint32_t rss_key[RSS_KEYSIZE / sizeof(uint32_t)];
6637 
6638 	CTASSERT(RSS_KEYSIZE == 40);
6639 
6640 	rss_getkey((void *)&raw_rss_key[0]);
6641 	for (i = 0; i < nitems(rss_key); i++) {
6642 		rss_key[i] = htobe32(raw_rss_key[nitems(rss_key) - 1 - i]);
6643 	}
6644 	t4_write_rss_key(sc, &rss_key[0], -1, 1);
6645 #endif
6646 }
6647 
6648 /*
6649  * Idempotent.
6650  */
6651 static int
6652 adapter_full_init(struct adapter *sc)
6653 {
6654 	int rc, i;
6655 
6656 	ASSERT_SYNCHRONIZED_OP(sc);
6657 
6658 	/*
6659 	 * queues that belong to the adapter (not any particular port).
6660 	 */
6661 	rc = t4_setup_adapter_queues(sc);
6662 	if (rc != 0)
6663 		return (rc);
6664 
6665 	for (i = 0; i < nitems(sc->tq); i++) {
6666 		if (sc->tq[i] != NULL)
6667 			continue;
6668 		sc->tq[i] = taskqueue_create("t4 taskq", M_NOWAIT,
6669 		    taskqueue_thread_enqueue, &sc->tq[i]);
6670 		if (sc->tq[i] == NULL) {
6671 			CH_ERR(sc, "failed to allocate task queue %d\n", i);
6672 			return (ENOMEM);
6673 		}
6674 		taskqueue_start_threads(&sc->tq[i], 1, PI_NET, "%s tq%d",
6675 		    device_get_nameunit(sc->dev), i);
6676 	}
6677 
6678 	if (!(sc->flags & IS_VF)) {
6679 		write_global_rss_key(sc);
6680 		t4_intr_enable(sc);
6681 	}
6682 	return (0);
6683 }
6684 
6685 int
6686 adapter_init(struct adapter *sc)
6687 {
6688 	int rc;
6689 
6690 	ASSERT_SYNCHRONIZED_OP(sc);
6691 	ADAPTER_LOCK_ASSERT_NOTOWNED(sc);
6692 	KASSERT((sc->flags & FULL_INIT_DONE) == 0,
6693 	    ("%s: FULL_INIT_DONE already", __func__));
6694 
6695 	rc = adapter_full_init(sc);
6696 	if (rc != 0)
6697 		adapter_full_uninit(sc);
6698 	else
6699 		sc->flags |= FULL_INIT_DONE;
6700 
6701 	return (rc);
6702 }
6703 
6704 /*
6705  * Idempotent.
6706  */
6707 static void
6708 adapter_full_uninit(struct adapter *sc)
6709 {
6710 	int i;
6711 
6712 	t4_teardown_adapter_queues(sc);
6713 
6714 	for (i = 0; i < nitems(sc->tq) && sc->tq[i]; i++) {
6715 		taskqueue_free(sc->tq[i]);
6716 		sc->tq[i] = NULL;
6717 	}
6718 
6719 	sc->flags &= ~FULL_INIT_DONE;
6720 }
6721 
6722 #ifdef RSS
6723 #define SUPPORTED_RSS_HASHTYPES (RSS_HASHTYPE_RSS_IPV4 | \
6724     RSS_HASHTYPE_RSS_TCP_IPV4 | RSS_HASHTYPE_RSS_IPV6 | \
6725     RSS_HASHTYPE_RSS_TCP_IPV6 | RSS_HASHTYPE_RSS_UDP_IPV4 | \
6726     RSS_HASHTYPE_RSS_UDP_IPV6)
6727 
6728 /* Translates kernel hash types to hardware. */
6729 static int
6730 hashconfig_to_hashen(int hashconfig)
6731 {
6732 	int hashen = 0;
6733 
6734 	if (hashconfig & RSS_HASHTYPE_RSS_IPV4)
6735 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN;
6736 	if (hashconfig & RSS_HASHTYPE_RSS_IPV6)
6737 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN;
6738 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV4) {
6739 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6740 		    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6741 	}
6742 	if (hashconfig & RSS_HASHTYPE_RSS_UDP_IPV6) {
6743 		hashen |= F_FW_RSS_VI_CONFIG_CMD_UDPEN |
6744 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6745 	}
6746 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV4)
6747 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN;
6748 	if (hashconfig & RSS_HASHTYPE_RSS_TCP_IPV6)
6749 		hashen |= F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN;
6750 
6751 	return (hashen);
6752 }
6753 
6754 /* Translates hardware hash types to kernel. */
6755 static int
6756 hashen_to_hashconfig(int hashen)
6757 {
6758 	int hashconfig = 0;
6759 
6760 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_UDPEN) {
6761 		/*
6762 		 * If UDP hashing was enabled it must have been enabled for
6763 		 * either IPv4 or IPv6 (inclusive or).  Enabling UDP without
6764 		 * enabling any 4-tuple hash is nonsense configuration.
6765 		 */
6766 		MPASS(hashen & (F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6767 		    F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN));
6768 
6769 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6770 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV4;
6771 		if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6772 			hashconfig |= RSS_HASHTYPE_RSS_UDP_IPV6;
6773 	}
6774 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN)
6775 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV4;
6776 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN)
6777 		hashconfig |= RSS_HASHTYPE_RSS_TCP_IPV6;
6778 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN)
6779 		hashconfig |= RSS_HASHTYPE_RSS_IPV4;
6780 	if (hashen & F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN)
6781 		hashconfig |= RSS_HASHTYPE_RSS_IPV6;
6782 
6783 	return (hashconfig);
6784 }
6785 #endif
6786 
6787 /*
6788  * Idempotent.
6789  */
6790 static int
6791 vi_full_init(struct vi_info *vi)
6792 {
6793 	struct adapter *sc = vi->adapter;
6794 	struct sge_rxq *rxq;
6795 	int rc, i, j;
6796 #ifdef RSS
6797 	int nbuckets = rss_getnumbuckets();
6798 	int hashconfig = rss_gethashconfig();
6799 	int extra;
6800 #endif
6801 
6802 	ASSERT_SYNCHRONIZED_OP(sc);
6803 
6804 	/*
6805 	 * Allocate tx/rx/fl queues for this VI.
6806 	 */
6807 	rc = t4_setup_vi_queues(vi);
6808 	if (rc != 0)
6809 		return (rc);
6810 
6811 	/*
6812 	 * Setup RSS for this VI.  Save a copy of the RSS table for later use.
6813 	 */
6814 	if (vi->nrxq > vi->rss_size) {
6815 		CH_ALERT(vi, "nrxq (%d) > hw RSS table size (%d); "
6816 		    "some queues will never receive traffic.\n", vi->nrxq,
6817 		    vi->rss_size);
6818 	} else if (vi->rss_size % vi->nrxq) {
6819 		CH_ALERT(vi, "nrxq (%d), hw RSS table size (%d); "
6820 		    "expect uneven traffic distribution.\n", vi->nrxq,
6821 		    vi->rss_size);
6822 	}
6823 #ifdef RSS
6824 	if (vi->nrxq != nbuckets) {
6825 		CH_ALERT(vi, "nrxq (%d) != kernel RSS buckets (%d);"
6826 		    "performance will be impacted.\n", vi->nrxq, nbuckets);
6827 	}
6828 #endif
6829 	if (vi->rss == NULL)
6830 		vi->rss = malloc(vi->rss_size * sizeof (*vi->rss), M_CXGBE,
6831 		    M_ZERO | M_WAITOK);
6832 	for (i = 0; i < vi->rss_size;) {
6833 #ifdef RSS
6834 		j = rss_get_indirection_to_bucket(i);
6835 		j %= vi->nrxq;
6836 		rxq = &sc->sge.rxq[vi->first_rxq + j];
6837 		vi->rss[i++] = rxq->iq.abs_id;
6838 #else
6839 		for_each_rxq(vi, j, rxq) {
6840 			vi->rss[i++] = rxq->iq.abs_id;
6841 			if (i == vi->rss_size)
6842 				break;
6843 		}
6844 #endif
6845 	}
6846 
6847 	rc = -t4_config_rss_range(sc, sc->mbox, vi->viid, 0, vi->rss_size,
6848 	    vi->rss, vi->rss_size);
6849 	if (rc != 0) {
6850 		CH_ERR(vi, "rss_config failed: %d\n", rc);
6851 		return (rc);
6852 	}
6853 
6854 #ifdef RSS
6855 	vi->hashen = hashconfig_to_hashen(hashconfig);
6856 
6857 	/*
6858 	 * We may have had to enable some hashes even though the global config
6859 	 * wants them disabled.  This is a potential problem that must be
6860 	 * reported to the user.
6861 	 */
6862 	extra = hashen_to_hashconfig(vi->hashen) ^ hashconfig;
6863 
6864 	/*
6865 	 * If we consider only the supported hash types, then the enabled hashes
6866 	 * are a superset of the requested hashes.  In other words, there cannot
6867 	 * be any supported hash that was requested but not enabled, but there
6868 	 * can be hashes that were not requested but had to be enabled.
6869 	 */
6870 	extra &= SUPPORTED_RSS_HASHTYPES;
6871 	MPASS((extra & hashconfig) == 0);
6872 
6873 	if (extra) {
6874 		CH_ALERT(vi,
6875 		    "global RSS config (0x%x) cannot be accommodated.\n",
6876 		    hashconfig);
6877 	}
6878 	if (extra & RSS_HASHTYPE_RSS_IPV4)
6879 		CH_ALERT(vi, "IPv4 2-tuple hashing forced on.\n");
6880 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV4)
6881 		CH_ALERT(vi, "TCP/IPv4 4-tuple hashing forced on.\n");
6882 	if (extra & RSS_HASHTYPE_RSS_IPV6)
6883 		CH_ALERT(vi, "IPv6 2-tuple hashing forced on.\n");
6884 	if (extra & RSS_HASHTYPE_RSS_TCP_IPV6)
6885 		CH_ALERT(vi, "TCP/IPv6 4-tuple hashing forced on.\n");
6886 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV4)
6887 		CH_ALERT(vi, "UDP/IPv4 4-tuple hashing forced on.\n");
6888 	if (extra & RSS_HASHTYPE_RSS_UDP_IPV6)
6889 		CH_ALERT(vi, "UDP/IPv6 4-tuple hashing forced on.\n");
6890 #else
6891 	vi->hashen = F_FW_RSS_VI_CONFIG_CMD_IP6FOURTUPEN |
6892 	    F_FW_RSS_VI_CONFIG_CMD_IP6TWOTUPEN |
6893 	    F_FW_RSS_VI_CONFIG_CMD_IP4FOURTUPEN |
6894 	    F_FW_RSS_VI_CONFIG_CMD_IP4TWOTUPEN | F_FW_RSS_VI_CONFIG_CMD_UDPEN;
6895 #endif
6896 	rc = -t4_config_vi_rss(sc, sc->mbox, vi->viid, vi->hashen, vi->rss[0],
6897 	    0, 0);
6898 	if (rc != 0) {
6899 		CH_ERR(vi, "rss hash/defaultq config failed: %d\n", rc);
6900 		return (rc);
6901 	}
6902 
6903 	return (0);
6904 }
6905 
6906 int
6907 vi_init(struct vi_info *vi)
6908 {
6909 	int rc;
6910 
6911 	ASSERT_SYNCHRONIZED_OP(vi->adapter);
6912 	KASSERT((vi->flags & VI_INIT_DONE) == 0,
6913 	    ("%s: VI_INIT_DONE already", __func__));
6914 
6915 	rc = vi_full_init(vi);
6916 	if (rc != 0)
6917 		vi_full_uninit(vi);
6918 	else
6919 		vi->flags |= VI_INIT_DONE;
6920 
6921 	return (rc);
6922 }
6923 
6924 /*
6925  * Idempotent.
6926  */
6927 static void
6928 vi_full_uninit(struct vi_info *vi)
6929 {
6930 
6931 	if (vi->flags & VI_INIT_DONE) {
6932 		quiesce_vi(vi);
6933 		free(vi->rss, M_CXGBE);
6934 		free(vi->nm_rss, M_CXGBE);
6935 	}
6936 
6937 	t4_teardown_vi_queues(vi);
6938 	vi->flags &= ~VI_INIT_DONE;
6939 }
6940 
6941 static void
6942 quiesce_txq(struct sge_txq *txq)
6943 {
6944 	struct sge_eq *eq = &txq->eq;
6945 	struct sge_qstat *spg = (void *)&eq->desc[eq->sidx];
6946 
6947 	MPASS(eq->flags & EQ_SW_ALLOCATED);
6948 	MPASS(!(eq->flags & EQ_ENABLED));
6949 
6950 	/* Wait for the mp_ring to empty. */
6951 	while (!mp_ring_is_idle(txq->r)) {
6952 		mp_ring_check_drainage(txq->r, 4096);
6953 		pause("rquiesce", 1);
6954 	}
6955 	MPASS(txq->txp.npkt == 0);
6956 
6957 	if (eq->flags & EQ_HW_ALLOCATED) {
6958 		/*
6959 		 * Hardware is alive and working normally.  Wait for it to
6960 		 * finish and then wait for the driver to catch up and reclaim
6961 		 * all descriptors.
6962 		 */
6963 		while (spg->cidx != htobe16(eq->pidx))
6964 			pause("equiesce", 1);
6965 		while (eq->cidx != eq->pidx)
6966 			pause("dquiesce", 1);
6967 	} else {
6968 		/*
6969 		 * Hardware is unavailable.  Discard all pending tx and reclaim
6970 		 * descriptors directly.
6971 		 */
6972 		TXQ_LOCK(txq);
6973 		while (eq->cidx != eq->pidx) {
6974 			struct mbuf *m, *nextpkt;
6975 			struct tx_sdesc *txsd;
6976 
6977 			txsd = &txq->sdesc[eq->cidx];
6978 			for (m = txsd->m; m != NULL; m = nextpkt) {
6979 				nextpkt = m->m_nextpkt;
6980 				m->m_nextpkt = NULL;
6981 				m_freem(m);
6982 			}
6983 			IDXINCR(eq->cidx, txsd->desc_used, eq->sidx);
6984 		}
6985 		spg->pidx = spg->cidx = htobe16(eq->cidx);
6986 		TXQ_UNLOCK(txq);
6987 	}
6988 }
6989 
6990 static void
6991 quiesce_wrq(struct sge_wrq *wrq)
6992 {
6993 
6994 	/* XXXTX */
6995 }
6996 
6997 static void
6998 quiesce_iq_fl(struct adapter *sc, struct sge_iq *iq, struct sge_fl *fl)
6999 {
7000 	/* Synchronize with the interrupt handler */
7001 	while (!atomic_cmpset_int(&iq->state, IQS_IDLE, IQS_DISABLED))
7002 		pause("iqfree", 1);
7003 
7004 	if (fl != NULL) {
7005 		MPASS(iq->flags & IQ_HAS_FL);
7006 
7007 		mtx_lock(&sc->sfl_lock);
7008 		FL_LOCK(fl);
7009 		fl->flags |= FL_DOOMED;
7010 		FL_UNLOCK(fl);
7011 		callout_stop(&sc->sfl_callout);
7012 		mtx_unlock(&sc->sfl_lock);
7013 
7014 		KASSERT((fl->flags & FL_STARVING) == 0,
7015 		    ("%s: still starving", __func__));
7016 
7017 		/* Release all buffers if hardware is no longer available. */
7018 		if (!(iq->flags & IQ_HW_ALLOCATED))
7019 			free_fl_buffers(sc, fl);
7020 	}
7021 }
7022 
7023 /*
7024  * Wait for all activity on all the queues of the VI to complete.  It is assumed
7025  * that no new work is being enqueued by the hardware or the driver.  That part
7026  * should be arranged before calling this function.
7027  */
7028 static void
7029 quiesce_vi(struct vi_info *vi)
7030 {
7031 	int i;
7032 	struct adapter *sc = vi->adapter;
7033 	struct sge_rxq *rxq;
7034 	struct sge_txq *txq;
7035 #ifdef TCP_OFFLOAD
7036 	struct sge_ofld_rxq *ofld_rxq;
7037 #endif
7038 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7039 	struct sge_ofld_txq *ofld_txq;
7040 #endif
7041 
7042 	if (!(vi->flags & VI_INIT_DONE))
7043 		return;
7044 
7045 	for_each_txq(vi, i, txq) {
7046 		quiesce_txq(txq);
7047 	}
7048 
7049 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7050 	for_each_ofld_txq(vi, i, ofld_txq) {
7051 		quiesce_wrq(&ofld_txq->wrq);
7052 	}
7053 #endif
7054 
7055 	for_each_rxq(vi, i, rxq) {
7056 		quiesce_iq_fl(sc, &rxq->iq, &rxq->fl);
7057 	}
7058 
7059 #ifdef TCP_OFFLOAD
7060 	for_each_ofld_rxq(vi, i, ofld_rxq) {
7061 		quiesce_iq_fl(sc, &ofld_rxq->iq, &ofld_rxq->fl);
7062 	}
7063 #endif
7064 }
7065 
7066 static int
7067 t4_alloc_irq(struct adapter *sc, struct irq *irq, int rid,
7068     driver_intr_t *handler, void *arg, char *name)
7069 {
7070 	int rc;
7071 
7072 	irq->rid = rid;
7073 	irq->res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ, &irq->rid,
7074 	    RF_SHAREABLE | RF_ACTIVE);
7075 	if (irq->res == NULL) {
7076 		device_printf(sc->dev,
7077 		    "failed to allocate IRQ for rid %d, name %s.\n", rid, name);
7078 		return (ENOMEM);
7079 	}
7080 
7081 	rc = bus_setup_intr(sc->dev, irq->res, INTR_MPSAFE | INTR_TYPE_NET,
7082 	    NULL, handler, arg, &irq->tag);
7083 	if (rc != 0) {
7084 		device_printf(sc->dev,
7085 		    "failed to setup interrupt for rid %d, name %s: %d\n",
7086 		    rid, name, rc);
7087 	} else if (name)
7088 		bus_describe_intr(sc->dev, irq->res, irq->tag, "%s", name);
7089 
7090 	return (rc);
7091 }
7092 
7093 static int
7094 t4_free_irq(struct adapter *sc, struct irq *irq)
7095 {
7096 	if (irq->tag)
7097 		bus_teardown_intr(sc->dev, irq->res, irq->tag);
7098 	if (irq->res)
7099 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->rid, irq->res);
7100 
7101 	bzero(irq, sizeof(*irq));
7102 
7103 	return (0);
7104 }
7105 
7106 static void
7107 get_regs(struct adapter *sc, struct t4_regdump *regs, uint8_t *buf)
7108 {
7109 
7110 	regs->version = chip_id(sc) | chip_rev(sc) << 10;
7111 	t4_get_regs(sc, buf, regs->len);
7112 }
7113 
7114 #define	A_PL_INDIR_CMD	0x1f8
7115 
7116 #define	S_PL_AUTOINC	31
7117 #define	M_PL_AUTOINC	0x1U
7118 #define	V_PL_AUTOINC(x)	((x) << S_PL_AUTOINC)
7119 #define	G_PL_AUTOINC(x)	(((x) >> S_PL_AUTOINC) & M_PL_AUTOINC)
7120 
7121 #define	S_PL_VFID	20
7122 #define	M_PL_VFID	0xffU
7123 #define	V_PL_VFID(x)	((x) << S_PL_VFID)
7124 #define	G_PL_VFID(x)	(((x) >> S_PL_VFID) & M_PL_VFID)
7125 
7126 #define	S_PL_ADDR	0
7127 #define	M_PL_ADDR	0xfffffU
7128 #define	V_PL_ADDR(x)	((x) << S_PL_ADDR)
7129 #define	G_PL_ADDR(x)	(((x) >> S_PL_ADDR) & M_PL_ADDR)
7130 
7131 #define	A_PL_INDIR_DATA	0x1fc
7132 
7133 static uint64_t
7134 read_vf_stat(struct adapter *sc, u_int vin, int reg)
7135 {
7136 	u32 stats[2];
7137 
7138 	if (sc->flags & IS_VF) {
7139 		stats[0] = t4_read_reg(sc, VF_MPS_REG(reg));
7140 		stats[1] = t4_read_reg(sc, VF_MPS_REG(reg + 4));
7141 	} else {
7142 		mtx_assert(&sc->reg_lock, MA_OWNED);
7143 		t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) |
7144 		    V_PL_VFID(vin) | V_PL_ADDR(VF_MPS_REG(reg)));
7145 		stats[0] = t4_read_reg(sc, A_PL_INDIR_DATA);
7146 		stats[1] = t4_read_reg(sc, A_PL_INDIR_DATA);
7147 	}
7148 	return (((uint64_t)stats[1]) << 32 | stats[0]);
7149 }
7150 
7151 static void
7152 t4_get_vi_stats(struct adapter *sc, u_int vin, struct fw_vi_stats_vf *stats)
7153 {
7154 
7155 #define GET_STAT(name) \
7156 	read_vf_stat(sc, vin, A_MPS_VF_STAT_##name##_L)
7157 
7158 	if (!(sc->flags & IS_VF))
7159 		mtx_lock(&sc->reg_lock);
7160 	stats->tx_bcast_bytes    = GET_STAT(TX_VF_BCAST_BYTES);
7161 	stats->tx_bcast_frames   = GET_STAT(TX_VF_BCAST_FRAMES);
7162 	stats->tx_mcast_bytes    = GET_STAT(TX_VF_MCAST_BYTES);
7163 	stats->tx_mcast_frames   = GET_STAT(TX_VF_MCAST_FRAMES);
7164 	stats->tx_ucast_bytes    = GET_STAT(TX_VF_UCAST_BYTES);
7165 	stats->tx_ucast_frames   = GET_STAT(TX_VF_UCAST_FRAMES);
7166 	stats->tx_drop_frames    = GET_STAT(TX_VF_DROP_FRAMES);
7167 	stats->tx_offload_bytes  = GET_STAT(TX_VF_OFFLOAD_BYTES);
7168 	stats->tx_offload_frames = GET_STAT(TX_VF_OFFLOAD_FRAMES);
7169 	stats->rx_bcast_bytes    = GET_STAT(RX_VF_BCAST_BYTES);
7170 	stats->rx_bcast_frames   = GET_STAT(RX_VF_BCAST_FRAMES);
7171 	stats->rx_mcast_bytes    = GET_STAT(RX_VF_MCAST_BYTES);
7172 	stats->rx_mcast_frames   = GET_STAT(RX_VF_MCAST_FRAMES);
7173 	stats->rx_ucast_bytes    = GET_STAT(RX_VF_UCAST_BYTES);
7174 	stats->rx_ucast_frames   = GET_STAT(RX_VF_UCAST_FRAMES);
7175 	stats->rx_err_frames     = GET_STAT(RX_VF_ERR_FRAMES);
7176 	if (!(sc->flags & IS_VF))
7177 		mtx_unlock(&sc->reg_lock);
7178 
7179 #undef GET_STAT
7180 }
7181 
7182 static void
7183 t4_clr_vi_stats(struct adapter *sc, u_int vin)
7184 {
7185 	int reg;
7186 
7187 	t4_write_reg(sc, A_PL_INDIR_CMD, V_PL_AUTOINC(1) | V_PL_VFID(vin) |
7188 	    V_PL_ADDR(VF_MPS_REG(A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L)));
7189 	for (reg = A_MPS_VF_STAT_TX_VF_BCAST_BYTES_L;
7190 	     reg <= A_MPS_VF_STAT_RX_VF_ERR_FRAMES_H; reg += 4)
7191 		t4_write_reg(sc, A_PL_INDIR_DATA, 0);
7192 }
7193 
7194 static void
7195 vi_refresh_stats(struct vi_info *vi)
7196 {
7197 	struct timeval tv;
7198 	const struct timeval interval = {0, 250000};	/* 250ms */
7199 
7200 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7201 
7202 	if (vi->flags & VI_SKIP_STATS)
7203 		return;
7204 
7205 	getmicrotime(&tv);
7206 	timevalsub(&tv, &interval);
7207 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7208 		return;
7209 
7210 	t4_get_vi_stats(vi->adapter, vi->vin, &vi->stats);
7211 	getmicrotime(&vi->last_refreshed);
7212 }
7213 
7214 static void
7215 cxgbe_refresh_stats(struct vi_info *vi)
7216 {
7217 	u_int i, v, tnl_cong_drops, chan_map;
7218 	struct timeval tv;
7219 	const struct timeval interval = {0, 250000};	/* 250ms */
7220 	struct port_info *pi;
7221 	struct adapter *sc;
7222 
7223 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7224 
7225 	if (vi->flags & VI_SKIP_STATS)
7226 		return;
7227 
7228 	getmicrotime(&tv);
7229 	timevalsub(&tv, &interval);
7230 	if (timevalcmp(&tv, &vi->last_refreshed, <))
7231 		return;
7232 
7233 	pi = vi->pi;
7234 	sc = vi->adapter;
7235 	tnl_cong_drops = 0;
7236 	t4_get_port_stats(sc, pi->port_id, &pi->stats);
7237 	chan_map = pi->rx_e_chan_map;
7238 	while (chan_map) {
7239 		i = ffs(chan_map) - 1;
7240 		mtx_lock(&sc->reg_lock);
7241 		t4_read_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v, 1,
7242 		    A_TP_MIB_TNL_CNG_DROP_0 + i);
7243 		mtx_unlock(&sc->reg_lock);
7244 		tnl_cong_drops += v;
7245 		chan_map &= ~(1 << i);
7246 	}
7247 	pi->tnl_cong_drops = tnl_cong_drops;
7248 	getmicrotime(&vi->last_refreshed);
7249 }
7250 
7251 static void
7252 cxgbe_tick(void *arg)
7253 {
7254 	struct vi_info *vi = arg;
7255 
7256 	MPASS(IS_MAIN_VI(vi));
7257 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7258 
7259 	cxgbe_refresh_stats(vi);
7260 	callout_schedule(&vi->tick, hz);
7261 }
7262 
7263 static void
7264 vi_tick(void *arg)
7265 {
7266 	struct vi_info *vi = arg;
7267 
7268 	mtx_assert(&vi->tick_mtx, MA_OWNED);
7269 
7270 	vi_refresh_stats(vi);
7271 	callout_schedule(&vi->tick, hz);
7272 }
7273 
7274 /*
7275  * Should match fw_caps_config_<foo> enums in t4fw_interface.h
7276  */
7277 static char *caps_decoder[] = {
7278 	"\20\001IPMI\002NCSI",				/* 0: NBM */
7279 	"\20\001PPP\002QFC\003DCBX",			/* 1: link */
7280 	"\20\001INGRESS\002EGRESS",			/* 2: switch */
7281 	"\20\001NIC\002VM\003IDS\004UM\005UM_ISGL"	/* 3: NIC */
7282 	    "\006HASHFILTER\007ETHOFLD",
7283 	"\20\001TOE",					/* 4: TOE */
7284 	"\20\001RDDP\002RDMAC",				/* 5: RDMA */
7285 	"\20\001INITIATOR_PDU\002TARGET_PDU"		/* 6: iSCSI */
7286 	    "\003INITIATOR_CNXOFLD\004TARGET_CNXOFLD"
7287 	    "\005INITIATOR_SSNOFLD\006TARGET_SSNOFLD"
7288 	    "\007T10DIF"
7289 	    "\010INITIATOR_CMDOFLD\011TARGET_CMDOFLD",
7290 	"\20\001LOOKASIDE\002TLSKEYS\003IPSEC_INLINE"	/* 7: Crypto */
7291 	    "\004TLS_HW",
7292 	"\20\001INITIATOR\002TARGET\003CTRL_OFLD"	/* 8: FCoE */
7293 		    "\004PO_INITIATOR\005PO_TARGET",
7294 };
7295 
7296 void
7297 t4_sysctls(struct adapter *sc)
7298 {
7299 	struct sysctl_ctx_list *ctx = &sc->ctx;
7300 	struct sysctl_oid *oid;
7301 	struct sysctl_oid_list *children, *c0;
7302 	static char *doorbells = {"\20\1UDB\2WCWR\3UDBWC\4KDB"};
7303 
7304 	/*
7305 	 * dev.t4nex.X.
7306 	 */
7307 	oid = device_get_sysctl_tree(sc->dev);
7308 	c0 = children = SYSCTL_CHILDREN(oid);
7309 
7310 	sc->sc_do_rxcopy = 1;
7311 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "do_rx_copy", CTLFLAG_RW,
7312 	    &sc->sc_do_rxcopy, 1, "Do RX copy of small frames");
7313 
7314 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nports", CTLFLAG_RD, NULL,
7315 	    sc->params.nports, "# of ports");
7316 
7317 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "doorbells",
7318 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, doorbells,
7319 	    (uintptr_t)&sc->doorbells, sysctl_bitfield_8b, "A",
7320 	    "available doorbells");
7321 
7322 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "core_clock", CTLFLAG_RD, NULL,
7323 	    sc->params.vpd.cclk, "core clock frequency (in KHz)");
7324 
7325 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_timers",
7326 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7327 	    sc->params.sge.timer_val, sizeof(sc->params.sge.timer_val),
7328 	    sysctl_int_array, "A", "interrupt holdoff timer values (us)");
7329 
7330 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pkt_counts",
7331 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE,
7332 	    sc->params.sge.counter_val, sizeof(sc->params.sge.counter_val),
7333 	    sysctl_int_array, "A", "interrupt holdoff packet counter values");
7334 
7335 	t4_sge_sysctls(sc, ctx, children);
7336 
7337 	sc->lro_timeout = 100;
7338 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lro_timeout", CTLFLAG_RW,
7339 	    &sc->lro_timeout, 0, "lro inactive-flush timeout (in us)");
7340 
7341 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "dflags", CTLFLAG_RW,
7342 	    &sc->debug_flags, 0, "flags to enable runtime debugging");
7343 
7344 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "tp_version",
7345 	    CTLFLAG_RD, sc->tp_version, 0, "TP microcode version");
7346 
7347 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "firmware_version",
7348 	    CTLFLAG_RD, sc->fw_version, 0, "firmware version");
7349 
7350 	if (sc->flags & IS_VF)
7351 		return;
7352 
7353 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "hw_revision", CTLFLAG_RD,
7354 	    NULL, chip_rev(sc), "chip hardware revision");
7355 
7356 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "sn",
7357 	    CTLFLAG_RD, sc->params.vpd.sn, 0, "serial number");
7358 
7359 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "pn",
7360 	    CTLFLAG_RD, sc->params.vpd.pn, 0, "part number");
7361 
7362 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "ec",
7363 	    CTLFLAG_RD, sc->params.vpd.ec, 0, "engineering change");
7364 
7365 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "md_version",
7366 	    CTLFLAG_RD, sc->params.vpd.md, 0, "manufacturing diags version");
7367 
7368 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "na",
7369 	    CTLFLAG_RD, sc->params.vpd.na, 0, "network address");
7370 
7371 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "er_version", CTLFLAG_RD,
7372 	    sc->er_version, 0, "expansion ROM version");
7373 
7374 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "bs_version", CTLFLAG_RD,
7375 	    sc->bs_version, 0, "bootstrap firmware version");
7376 
7377 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "scfg_version", CTLFLAG_RD,
7378 	    NULL, sc->params.scfg_vers, "serial config version");
7379 
7380 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "vpd_version", CTLFLAG_RD,
7381 	    NULL, sc->params.vpd_vers, "VPD version");
7382 
7383 	SYSCTL_ADD_STRING(ctx, children, OID_AUTO, "cf",
7384 	    CTLFLAG_RD, sc->cfg_file, 0, "configuration file");
7385 
7386 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "cfcsum", CTLFLAG_RD, NULL,
7387 	    sc->cfcsum, "config file checksum");
7388 
7389 #define SYSCTL_CAP(name, n, text) \
7390 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, #name, \
7391 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, caps_decoder[n], \
7392 	    (uintptr_t)&sc->name, sysctl_bitfield_16b, "A", \
7393 	    "available " text " capabilities")
7394 
7395 	SYSCTL_CAP(nbmcaps, 0, "NBM");
7396 	SYSCTL_CAP(linkcaps, 1, "link");
7397 	SYSCTL_CAP(switchcaps, 2, "switch");
7398 	SYSCTL_CAP(niccaps, 3, "NIC");
7399 	SYSCTL_CAP(toecaps, 4, "TCP offload");
7400 	SYSCTL_CAP(rdmacaps, 5, "RDMA");
7401 	SYSCTL_CAP(iscsicaps, 6, "iSCSI");
7402 	SYSCTL_CAP(cryptocaps, 7, "crypto");
7403 	SYSCTL_CAP(fcoecaps, 8, "FCoE");
7404 #undef SYSCTL_CAP
7405 
7406 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nfilters", CTLFLAG_RD,
7407 	    NULL, sc->tids.nftids, "number of filters");
7408 
7409 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7410 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7411 	    sysctl_temperature, "I", "chip temperature (in Celsius)");
7412 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset_sensor",
7413 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7414 	    sysctl_reset_sensor, "I", "reset the chip's temperature sensor.");
7415 
7416 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "loadavg",
7417 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7418 	    sysctl_loadavg, "A",
7419 	    "microprocessor load averages (debug firmwares only)");
7420 
7421 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "core_vdd",
7422 	    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0, sysctl_vdd,
7423 	    "I", "core Vdd (in mV)");
7424 
7425 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "local_cpus",
7426 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, LOCAL_CPUS,
7427 	    sysctl_cpus, "A", "local CPUs");
7428 
7429 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "intr_cpus",
7430 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, INTR_CPUS,
7431 	    sysctl_cpus, "A", "preferred CPUs for interrupts");
7432 
7433 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "swintr", CTLFLAG_RW,
7434 	    &sc->swintr, 0, "software triggered interrupts");
7435 
7436 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "reset",
7437 	    CTLTYPE_INT | CTLFLAG_RW, sc, 0, sysctl_reset, "I",
7438 	    "1 = reset adapter, 0 = zero reset counter");
7439 
7440 	/*
7441 	 * dev.t4nex.X.misc.  Marked CTLFLAG_SKIP to avoid information overload.
7442 	 */
7443 	oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "misc",
7444 	    CTLFLAG_RD | CTLFLAG_SKIP | CTLFLAG_MPSAFE, NULL,
7445 	    "logs and miscellaneous information");
7446 	children = SYSCTL_CHILDREN(oid);
7447 
7448 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cctrl",
7449 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7450 	    sysctl_cctrl, "A", "congestion control");
7451 
7452 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp0",
7453 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7454 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 0 (TP0)");
7455 
7456 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_tp1",
7457 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7458 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 1 (TP1)");
7459 
7460 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ulp",
7461 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7462 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 2 (ULP)");
7463 
7464 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge0",
7465 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 3,
7466 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 3 (SGE0)");
7467 
7468 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_sge1",
7469 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 4,
7470 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 4 (SGE1)");
7471 
7472 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ibq_ncsi",
7473 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 5,
7474 	    sysctl_cim_ibq_obq, "A", "CIM IBQ 5 (NCSI)");
7475 
7476 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_la",
7477 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7478 	    sysctl_cim_la, "A", "CIM logic analyzer");
7479 
7480 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_ma_la",
7481 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7482 	    sysctl_cim_ma_la, "A", "CIM MA logic analyzer");
7483 
7484 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp0",
7485 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7486 	    0 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 0 (ULP0)");
7487 
7488 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp1",
7489 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7490 	    1 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 1 (ULP1)");
7491 
7492 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp2",
7493 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7494 	    2 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 2 (ULP2)");
7495 
7496 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ulp3",
7497 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7498 	    3 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 3 (ULP3)");
7499 
7500 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge",
7501 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7502 	    4 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 4 (SGE)");
7503 
7504 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_ncsi",
7505 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7506 	    5 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A", "CIM OBQ 5 (NCSI)");
7507 
7508 	if (chip_id(sc) > CHELSIO_T4) {
7509 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge0_rx",
7510 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7511 		    6 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7512 		    "CIM OBQ 6 (SGE0-RX)");
7513 
7514 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_obq_sge1_rx",
7515 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7516 		    7 + CIM_NUM_IBQ, sysctl_cim_ibq_obq, "A",
7517 		    "CIM OBQ 7 (SGE1-RX)");
7518 	}
7519 
7520 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_pif_la",
7521 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7522 	    sysctl_cim_pif_la, "A", "CIM PIF logic analyzer");
7523 
7524 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cim_qcfg",
7525 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7526 	    sysctl_cim_qcfg, "A", "CIM queue configuration");
7527 
7528 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "cpl_stats",
7529 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7530 	    sysctl_cpl_stats, "A", "CPL statistics");
7531 
7532 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ddp_stats",
7533 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7534 	    sysctl_ddp_stats, "A", "non-TCP DDP statistics");
7535 
7536 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tid_stats",
7537 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7538 	    sysctl_tid_stats, "A", "tid stats");
7539 
7540 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "devlog",
7541 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7542 	    sysctl_devlog, "A", "firmware's device log");
7543 
7544 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fcoe_stats",
7545 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7546 	    sysctl_fcoe_stats, "A", "FCoE statistics");
7547 
7548 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "hw_sched",
7549 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7550 	    sysctl_hw_sched, "A", "hardware scheduler ");
7551 
7552 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "l2t",
7553 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7554 	    sysctl_l2t, "A", "hardware L2 table");
7555 
7556 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "smt",
7557 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7558 	    sysctl_smt, "A", "hardware source MAC table");
7559 
7560 #ifdef INET6
7561 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "clip",
7562 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7563 	    sysctl_clip, "A", "active CLIP table entries");
7564 #endif
7565 
7566 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "lb_stats",
7567 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7568 	    sysctl_lb_stats, "A", "loopback statistics");
7569 
7570 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "meminfo",
7571 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7572 	    sysctl_meminfo, "A", "memory regions");
7573 
7574 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "mps_tcam",
7575 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7576 	    chip_id(sc) <= CHELSIO_T5 ? sysctl_mps_tcam : sysctl_mps_tcam_t6,
7577 	    "A", "MPS TCAM entries");
7578 
7579 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "path_mtus",
7580 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7581 	    sysctl_path_mtus, "A", "path MTUs");
7582 
7583 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pm_stats",
7584 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7585 	    sysctl_pm_stats, "A", "PM statistics");
7586 
7587 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rdma_stats",
7588 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7589 	    sysctl_rdma_stats, "A", "RDMA statistics");
7590 
7591 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tcp_stats",
7592 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7593 	    sysctl_tcp_stats, "A", "TCP statistics");
7594 
7595 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tids",
7596 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7597 	    sysctl_tids, "A", "TID information");
7598 
7599 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_err_stats",
7600 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7601 	    sysctl_tp_err_stats, "A", "TP error statistics");
7602 
7603 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tnl_stats",
7604 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7605 	    sysctl_tnl_stats, "A", "TP tunnel statistics");
7606 
7607 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la_mask",
7608 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0,
7609 	    sysctl_tp_la_mask, "I", "TP logic analyzer event capture mask");
7610 
7611 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tp_la",
7612 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7613 	    sysctl_tp_la, "A", "TP logic analyzer");
7614 
7615 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_rate",
7616 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7617 	    sysctl_tx_rate, "A", "Tx rate");
7618 
7619 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "ulprx_la",
7620 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7621 	    sysctl_ulprx_la, "A", "ULPRX logic analyzer");
7622 
7623 	if (chip_id(sc) >= CHELSIO_T5) {
7624 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "wcwr_stats",
7625 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7626 		    sysctl_wcwr_stats, "A", "write combined work requests");
7627 	}
7628 
7629 #ifdef KERN_TLS
7630 	if (is_ktls(sc)) {
7631 		/*
7632 		 * dev.t4nex.0.tls.
7633 		 */
7634 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "tls",
7635 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "KERN_TLS parameters");
7636 		children = SYSCTL_CHILDREN(oid);
7637 
7638 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "inline_keys",
7639 		    CTLFLAG_RW, &sc->tlst.inline_keys, 0, "Always pass TLS "
7640 		    "keys in work requests (1) or attempt to store TLS keys "
7641 		    "in card memory.");
7642 
7643 		if (is_t6(sc))
7644 			SYSCTL_ADD_INT(ctx, children, OID_AUTO, "combo_wrs",
7645 			    CTLFLAG_RW, &sc->tlst.combo_wrs, 0, "Attempt to "
7646 			    "combine TCB field updates with TLS record work "
7647 			    "requests.");
7648 	}
7649 #endif
7650 
7651 #ifdef TCP_OFFLOAD
7652 	if (is_offload(sc)) {
7653 		int i;
7654 		char s[4];
7655 
7656 		/*
7657 		 * dev.t4nex.X.toe.
7658 		 */
7659 		oid = SYSCTL_ADD_NODE(ctx, c0, OID_AUTO, "toe",
7660 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "TOE parameters");
7661 		children = SYSCTL_CHILDREN(oid);
7662 
7663 		sc->tt.cong_algorithm = -1;
7664 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "cong_algorithm",
7665 		    CTLFLAG_RW, &sc->tt.cong_algorithm, 0, "congestion control "
7666 		    "(-1 = default, 0 = reno, 1 = tahoe, 2 = newreno, "
7667 		    "3 = highspeed)");
7668 
7669 		sc->tt.sndbuf = -1;
7670 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "sndbuf", CTLFLAG_RW,
7671 		    &sc->tt.sndbuf, 0, "hardware send buffer");
7672 
7673 		sc->tt.ddp = 0;
7674 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ddp",
7675 		    CTLFLAG_RW | CTLFLAG_SKIP, &sc->tt.ddp, 0, "");
7676 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_zcopy", CTLFLAG_RW,
7677 		    &sc->tt.ddp, 0, "Enable zero-copy aio_read(2)");
7678 
7679 		sc->tt.rx_coalesce = -1;
7680 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_coalesce",
7681 		    CTLFLAG_RW, &sc->tt.rx_coalesce, 0, "receive coalescing");
7682 
7683 		sc->tt.tls = 0;
7684 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tls", CTLTYPE_INT |
7685 		    CTLFLAG_RW | CTLFLAG_MPSAFE, sc, 0, sysctl_tls, "I",
7686 		    "Inline TLS allowed");
7687 
7688 		sc->tt.tx_align = -1;
7689 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_align",
7690 		    CTLFLAG_RW, &sc->tt.tx_align, 0, "chop and align payload");
7691 
7692 		sc->tt.tx_zcopy = 0;
7693 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "tx_zcopy",
7694 		    CTLFLAG_RW, &sc->tt.tx_zcopy, 0,
7695 		    "Enable zero-copy aio_write(2)");
7696 
7697 		sc->tt.cop_managed_offloading = !!t4_cop_managed_offloading;
7698 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7699 		    "cop_managed_offloading", CTLFLAG_RW,
7700 		    &sc->tt.cop_managed_offloading, 0,
7701 		    "COP (Connection Offload Policy) controls all TOE offload");
7702 
7703 		sc->tt.autorcvbuf_inc = 16 * 1024;
7704 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "autorcvbuf_inc",
7705 		    CTLFLAG_RW, &sc->tt.autorcvbuf_inc, 0,
7706 		    "autorcvbuf increment");
7707 
7708 		sc->tt.update_hc_on_pmtu_change = 1;
7709 		SYSCTL_ADD_INT(ctx, children, OID_AUTO,
7710 		    "update_hc_on_pmtu_change", CTLFLAG_RW,
7711 		    &sc->tt.update_hc_on_pmtu_change, 0,
7712 		    "Update hostcache entry if the PMTU changes");
7713 
7714 		sc->tt.iso = 1;
7715 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "iso", CTLFLAG_RW,
7716 		    &sc->tt.iso, 0, "Enable iSCSI segmentation offload");
7717 
7718 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timer_tick",
7719 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7720 		    sysctl_tp_tick, "A", "TP timer tick (us)");
7721 
7722 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "timestamp_tick",
7723 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 1,
7724 		    sysctl_tp_tick, "A", "TCP timestamp tick (us)");
7725 
7726 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_tick",
7727 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 2,
7728 		    sysctl_tp_tick, "A", "DACK tick (us)");
7729 
7730 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "dack_timer",
7731 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, 0,
7732 		    sysctl_tp_dack_timer, "IU", "DACK timer (us)");
7733 
7734 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_min",
7735 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7736 		    A_TP_RXT_MIN, sysctl_tp_timer, "LU",
7737 		    "Minimum retransmit interval (us)");
7738 
7739 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_max",
7740 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7741 		    A_TP_RXT_MAX, sysctl_tp_timer, "LU",
7742 		    "Maximum retransmit interval (us)");
7743 
7744 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_min",
7745 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7746 		    A_TP_PERS_MIN, sysctl_tp_timer, "LU",
7747 		    "Persist timer min (us)");
7748 
7749 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "persist_max",
7750 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7751 		    A_TP_PERS_MAX, sysctl_tp_timer, "LU",
7752 		    "Persist timer max (us)");
7753 
7754 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_idle",
7755 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7756 		    A_TP_KEEP_IDLE, sysctl_tp_timer, "LU",
7757 		    "Keepalive idle timer (us)");
7758 
7759 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_interval",
7760 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7761 		    A_TP_KEEP_INTVL, sysctl_tp_timer, "LU",
7762 		    "Keepalive interval timer (us)");
7763 
7764 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "initial_srtt",
7765 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7766 		    A_TP_INIT_SRTT, sysctl_tp_timer, "LU", "Initial SRTT (us)");
7767 
7768 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "finwait2_timer",
7769 		    CTLTYPE_ULONG | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7770 		    A_TP_FINWAIT2_TIMER, sysctl_tp_timer, "LU",
7771 		    "FINWAIT2 timer (us)");
7772 
7773 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "syn_rexmt_count",
7774 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7775 		    S_SYNSHIFTMAX, sysctl_tp_shift_cnt, "IU",
7776 		    "Number of SYN retransmissions before abort");
7777 
7778 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rexmt_count",
7779 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7780 		    S_RXTSHIFTMAXR2, sysctl_tp_shift_cnt, "IU",
7781 		    "Number of retransmissions before abort");
7782 
7783 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "keepalive_count",
7784 		    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7785 		    S_KEEPALIVEMAXR2, sysctl_tp_shift_cnt, "IU",
7786 		    "Number of keepalive probes before abort");
7787 
7788 		oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "rexmt_backoff",
7789 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7790 		    "TOE retransmit backoffs");
7791 		children = SYSCTL_CHILDREN(oid);
7792 		for (i = 0; i < 16; i++) {
7793 			snprintf(s, sizeof(s), "%u", i);
7794 			SYSCTL_ADD_PROC(ctx, children, OID_AUTO, s,
7795 			    CTLTYPE_UINT | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
7796 			    i, sysctl_tp_backoff, "IU",
7797 			    "TOE retransmit backoff");
7798 		}
7799 	}
7800 #endif
7801 }
7802 
7803 void
7804 vi_sysctls(struct vi_info *vi)
7805 {
7806 	struct sysctl_ctx_list *ctx = &vi->ctx;
7807 	struct sysctl_oid *oid;
7808 	struct sysctl_oid_list *children;
7809 
7810 	/*
7811 	 * dev.v?(cxgbe|cxl).X.
7812 	 */
7813 	oid = device_get_sysctl_tree(vi->dev);
7814 	children = SYSCTL_CHILDREN(oid);
7815 
7816 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "viid", CTLFLAG_RD, NULL,
7817 	    vi->viid, "VI identifer");
7818 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nrxq", CTLFLAG_RD,
7819 	    &vi->nrxq, 0, "# of rx queues");
7820 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "ntxq", CTLFLAG_RD,
7821 	    &vi->ntxq, 0, "# of tx queues");
7822 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_rxq", CTLFLAG_RD,
7823 	    &vi->first_rxq, 0, "index of first rx queue");
7824 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_txq", CTLFLAG_RD,
7825 	    &vi->first_txq, 0, "index of first tx queue");
7826 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_base", CTLFLAG_RD, NULL,
7827 	    vi->rss_base, "start of RSS indirection table");
7828 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "rss_size", CTLFLAG_RD, NULL,
7829 	    vi->rss_size, "size of RSS indirection table");
7830 
7831 	if (IS_MAIN_VI(vi)) {
7832 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "rsrv_noflowq",
7833 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7834 		    sysctl_noflowq, "IU",
7835 		    "Reserve queue 0 for non-flowid packets");
7836 	}
7837 
7838 	if (vi->adapter->flags & IS_VF) {
7839 		MPASS(vi->flags & TX_USES_VM_WR);
7840 		SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_vm_wr", CTLFLAG_RD,
7841 		    NULL, 1, "use VM work requests for transmit");
7842 	} else {
7843 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "tx_vm_wr",
7844 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7845 		    sysctl_tx_vm_wr, "I", "use VM work requestes for transmit");
7846 	}
7847 
7848 #ifdef TCP_OFFLOAD
7849 	if (vi->nofldrxq != 0) {
7850 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldrxq", CTLFLAG_RD,
7851 		    &vi->nofldrxq, 0,
7852 		    "# of rx queues for offloaded TCP connections");
7853 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_rxq",
7854 		    CTLFLAG_RD, &vi->first_ofld_rxq, 0,
7855 		    "index of first TOE rx queue");
7856 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx_ofld",
7857 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7858 		    sysctl_holdoff_tmr_idx_ofld, "I",
7859 		    "holdoff timer index for TOE queues");
7860 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx_ofld",
7861 		    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7862 		    sysctl_holdoff_pktc_idx_ofld, "I",
7863 		    "holdoff packet counter index for TOE queues");
7864 	}
7865 #endif
7866 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
7867 	if (vi->nofldtxq != 0) {
7868 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nofldtxq", CTLFLAG_RD,
7869 		    &vi->nofldtxq, 0,
7870 		    "# of tx queues for TOE/ETHOFLD");
7871 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_ofld_txq",
7872 		    CTLFLAG_RD, &vi->first_ofld_txq, 0,
7873 		    "index of first TOE/ETHOFLD tx queue");
7874 	}
7875 #endif
7876 #ifdef DEV_NETMAP
7877 	if (vi->nnmrxq != 0) {
7878 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmrxq", CTLFLAG_RD,
7879 		    &vi->nnmrxq, 0, "# of netmap rx queues");
7880 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "nnmtxq", CTLFLAG_RD,
7881 		    &vi->nnmtxq, 0, "# of netmap tx queues");
7882 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_rxq",
7883 		    CTLFLAG_RD, &vi->first_nm_rxq, 0,
7884 		    "index of first netmap rx queue");
7885 		SYSCTL_ADD_INT(ctx, children, OID_AUTO, "first_nm_txq",
7886 		    CTLFLAG_RD, &vi->first_nm_txq, 0,
7887 		    "index of first netmap tx queue");
7888 	}
7889 #endif
7890 
7891 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_tmr_idx",
7892 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7893 	    sysctl_holdoff_tmr_idx, "I", "holdoff timer index");
7894 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "holdoff_pktc_idx",
7895 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7896 	    sysctl_holdoff_pktc_idx, "I", "holdoff packet counter index");
7897 
7898 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_rxq",
7899 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7900 	    sysctl_qsize_rxq, "I", "rx queue size");
7901 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "qsize_txq",
7902 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, vi, 0,
7903 	    sysctl_qsize_txq, "I", "tx queue size");
7904 }
7905 
7906 static void
7907 cxgbe_sysctls(struct port_info *pi)
7908 {
7909 	struct sysctl_ctx_list *ctx = &pi->ctx;
7910 	struct sysctl_oid *oid;
7911 	struct sysctl_oid_list *children, *children2;
7912 	struct adapter *sc = pi->adapter;
7913 	int i;
7914 	char name[16];
7915 	static char *tc_flags = {"\20\1USER"};
7916 
7917 	/*
7918 	 * dev.cxgbe.X.
7919 	 */
7920 	oid = device_get_sysctl_tree(pi->dev);
7921 	children = SYSCTL_CHILDREN(oid);
7922 
7923 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "linkdnrc",
7924 	    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7925 	    sysctl_linkdnrc, "A", "reason why link is down");
7926 	if (pi->port_type == FW_PORT_TYPE_BT_XAUI) {
7927 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "temperature",
7928 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 0,
7929 		    sysctl_btphy, "I", "PHY temperature (in Celsius)");
7930 		SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "fw_version",
7931 		    CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, pi, 1,
7932 		    sysctl_btphy, "I", "PHY firmware version");
7933 	}
7934 
7935 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "pause_settings",
7936 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7937 	    sysctl_pause_settings, "A",
7938 	    "PAUSE settings (bit 0 = rx_pause, 1 = tx_pause, 2 = pause_autoneg)");
7939 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "link_fec",
7940 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_link_fec, "A",
7941 	    "FEC in use on the link");
7942 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "requested_fec",
7943 	    CTLTYPE_STRING | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7944 	    sysctl_requested_fec, "A",
7945 	    "FECs to use (bit 0 = RS, 1 = FC, 2 = none, 5 = auto, 6 = module)");
7946 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "module_fec",
7947 	    CTLTYPE_STRING | CTLFLAG_MPSAFE, pi, 0, sysctl_module_fec, "A",
7948 	    "FEC recommended by the cable/transceiver");
7949 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "autoneg",
7950 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7951 	    sysctl_autoneg, "I",
7952 	    "autonegotiation (-1 = not supported)");
7953 	SYSCTL_ADD_PROC(ctx, children, OID_AUTO, "force_fec",
7954 	    CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, pi, 0,
7955 	    sysctl_force_fec, "I", "when to use FORCE_FEC bit for link config");
7956 
7957 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rcaps", CTLFLAG_RD,
7958 	    &pi->link_cfg.requested_caps, 0, "L1 config requested by driver");
7959 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "pcaps", CTLFLAG_RD,
7960 	    &pi->link_cfg.pcaps, 0, "port capabilities");
7961 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "acaps", CTLFLAG_RD,
7962 	    &pi->link_cfg.acaps, 0, "advertised capabilities");
7963 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "lpacaps", CTLFLAG_RD,
7964 	    &pi->link_cfg.lpacaps, 0, "link partner advertised capabilities");
7965 
7966 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "max_speed", CTLFLAG_RD, NULL,
7967 	    port_top_speed(pi), "max speed (in Gbps)");
7968 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "mps_bg_map", CTLFLAG_RD, NULL,
7969 	    pi->mps_bg_map, "MPS buffer group map");
7970 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_e_chan_map", CTLFLAG_RD,
7971 	    NULL, pi->rx_e_chan_map, "TP rx e-channel map");
7972 	SYSCTL_ADD_INT(ctx, children, OID_AUTO, "rx_c_chan", CTLFLAG_RD, NULL,
7973 	    pi->rx_c_chan, "TP rx c-channel");
7974 
7975 	if (sc->flags & IS_VF)
7976 		return;
7977 
7978 	/*
7979 	 * dev.(cxgbe|cxl).X.tc.
7980 	 */
7981 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "tc",
7982 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL,
7983 	    "Tx scheduler traffic classes (cl_rl)");
7984 	children2 = SYSCTL_CHILDREN(oid);
7985 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "pktsize",
7986 	    CTLFLAG_RW, &pi->sched_params->pktsize, 0,
7987 	    "pktsize for per-flow cl-rl (0 means up to the driver )");
7988 	SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "burstsize",
7989 	    CTLFLAG_RW, &pi->sched_params->burstsize, 0,
7990 	    "burstsize for per-flow cl-rl (0 means up to the driver)");
7991 	for (i = 0; i < sc->params.nsched_cls; i++) {
7992 		struct tx_cl_rl_params *tc = &pi->sched_params->cl_rl[i];
7993 
7994 		snprintf(name, sizeof(name), "%d", i);
7995 		children2 = SYSCTL_CHILDREN(SYSCTL_ADD_NODE(ctx,
7996 		    SYSCTL_CHILDREN(oid), OID_AUTO, name,
7997 		    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "traffic class"));
7998 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "state",
7999 		    CTLFLAG_RD, &tc->state, 0, "current state");
8000 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "flags",
8001 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, tc_flags,
8002 		    (uintptr_t)&tc->flags, sysctl_bitfield_8b, "A", "flags");
8003 		SYSCTL_ADD_UINT(ctx, children2, OID_AUTO, "refcount",
8004 		    CTLFLAG_RD, &tc->refcount, 0, "references to this class");
8005 		SYSCTL_ADD_PROC(ctx, children2, OID_AUTO, "params",
8006 		    CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, sc,
8007 		    (pi->port_id << 16) | i, sysctl_tc_params, "A",
8008 		    "traffic class parameters");
8009 	}
8010 
8011 	/*
8012 	 * dev.cxgbe.X.stats.
8013 	 */
8014 	oid = SYSCTL_ADD_NODE(ctx, children, OID_AUTO, "stats",
8015 	    CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, "port statistics");
8016 	children = SYSCTL_CHILDREN(oid);
8017 	SYSCTL_ADD_UINT(ctx, children, OID_AUTO, "tx_parse_error", CTLFLAG_RD,
8018 	    &pi->tx_parse_error, 0,
8019 	    "# of tx packets with invalid length or # of segments");
8020 
8021 #define T4_REGSTAT(name, stat, desc) \
8022     SYSCTL_ADD_OID(ctx, children, OID_AUTO, #name, \
8023         CTLTYPE_U64 | CTLFLAG_RD | CTLFLAG_MPSAFE, sc, \
8024 	(is_t4(sc) ? PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L) : \
8025 	T5_PORT_REG(pi->tx_chan, A_MPS_PORT_STAT_##stat##_L)), \
8026         sysctl_handle_t4_reg64, "QU", desc)
8027 
8028 /* We get these from port_stats and they may be stale by up to 1s */
8029 #define T4_PORTSTAT(name, desc) \
8030 	SYSCTL_ADD_UQUAD(ctx, children, OID_AUTO, #name, CTLFLAG_RD, \
8031 	    &pi->stats.name, desc)
8032 
8033 	T4_REGSTAT(tx_octets, TX_PORT_BYTES, "# of octets in good frames");
8034 	T4_REGSTAT(tx_frames, TX_PORT_FRAMES, "total # of good frames");
8035 	T4_REGSTAT(tx_bcast_frames, TX_PORT_BCAST, "# of broadcast frames");
8036 	T4_REGSTAT(tx_mcast_frames, TX_PORT_MCAST, "# of multicast frames");
8037 	T4_REGSTAT(tx_ucast_frames, TX_PORT_UCAST, "# of unicast frames");
8038 	T4_REGSTAT(tx_error_frames, TX_PORT_ERROR, "# of error frames");
8039 	T4_REGSTAT(tx_frames_64, TX_PORT_64B, "# of tx frames in this range");
8040 	T4_REGSTAT(tx_frames_65_127, TX_PORT_65B_127B, "# of tx frames in this range");
8041 	T4_REGSTAT(tx_frames_128_255, TX_PORT_128B_255B, "# of tx frames in this range");
8042 	T4_REGSTAT(tx_frames_256_511, TX_PORT_256B_511B, "# of tx frames in this range");
8043 	T4_REGSTAT(tx_frames_512_1023, TX_PORT_512B_1023B, "# of tx frames in this range");
8044 	T4_REGSTAT(tx_frames_1024_1518, TX_PORT_1024B_1518B, "# of tx frames in this range");
8045 	T4_REGSTAT(tx_frames_1519_max, TX_PORT_1519B_MAX, "# of tx frames in this range");
8046 	T4_REGSTAT(tx_drop, TX_PORT_DROP, "# of dropped tx frames");
8047 	T4_REGSTAT(tx_pause, TX_PORT_PAUSE, "# of pause frames transmitted");
8048 	T4_REGSTAT(tx_ppp0, TX_PORT_PPP0, "# of PPP prio 0 frames transmitted");
8049 	T4_REGSTAT(tx_ppp1, TX_PORT_PPP1, "# of PPP prio 1 frames transmitted");
8050 	T4_REGSTAT(tx_ppp2, TX_PORT_PPP2, "# of PPP prio 2 frames transmitted");
8051 	T4_REGSTAT(tx_ppp3, TX_PORT_PPP3, "# of PPP prio 3 frames transmitted");
8052 	T4_REGSTAT(tx_ppp4, TX_PORT_PPP4, "# of PPP prio 4 frames transmitted");
8053 	T4_REGSTAT(tx_ppp5, TX_PORT_PPP5, "# of PPP prio 5 frames transmitted");
8054 	T4_REGSTAT(tx_ppp6, TX_PORT_PPP6, "# of PPP prio 6 frames transmitted");
8055 	T4_REGSTAT(tx_ppp7, TX_PORT_PPP7, "# of PPP prio 7 frames transmitted");
8056 
8057 	T4_REGSTAT(rx_octets, RX_PORT_BYTES, "# of octets in good frames");
8058 	T4_REGSTAT(rx_frames, RX_PORT_FRAMES, "total # of good frames");
8059 	T4_REGSTAT(rx_bcast_frames, RX_PORT_BCAST, "# of broadcast frames");
8060 	T4_REGSTAT(rx_mcast_frames, RX_PORT_MCAST, "# of multicast frames");
8061 	T4_REGSTAT(rx_ucast_frames, RX_PORT_UCAST, "# of unicast frames");
8062 	T4_REGSTAT(rx_too_long, RX_PORT_MTU_ERROR, "# of frames exceeding MTU");
8063 	T4_REGSTAT(rx_jabber, RX_PORT_MTU_CRC_ERROR, "# of jabber frames");
8064 	if (is_t6(sc)) {
8065 		T4_PORTSTAT(rx_fcs_err,
8066 		    "# of frames received with bad FCS since last link up");
8067 	} else {
8068 		T4_REGSTAT(rx_fcs_err, RX_PORT_CRC_ERROR,
8069 		    "# of frames received with bad FCS");
8070 	}
8071 	T4_REGSTAT(rx_len_err, RX_PORT_LEN_ERROR, "# of frames received with length error");
8072 	T4_REGSTAT(rx_symbol_err, RX_PORT_SYM_ERROR, "symbol errors");
8073 	T4_REGSTAT(rx_runt, RX_PORT_LESS_64B, "# of short frames received");
8074 	T4_REGSTAT(rx_frames_64, RX_PORT_64B, "# of rx frames in this range");
8075 	T4_REGSTAT(rx_frames_65_127, RX_PORT_65B_127B, "# of rx frames in this range");
8076 	T4_REGSTAT(rx_frames_128_255, RX_PORT_128B_255B, "# of rx frames in this range");
8077 	T4_REGSTAT(rx_frames_256_511, RX_PORT_256B_511B, "# of rx frames in this range");
8078 	T4_REGSTAT(rx_frames_512_1023, RX_PORT_512B_1023B, "# of rx frames in this range");
8079 	T4_REGSTAT(rx_frames_1024_1518, RX_PORT_1024B_1518B, "# of rx frames in this range");
8080 	T4_REGSTAT(rx_frames_1519_max, RX_PORT_1519B_MAX, "# of rx frames in this range");
8081 	T4_REGSTAT(rx_pause, RX_PORT_PAUSE, "# of pause frames received");
8082 	T4_REGSTAT(rx_ppp0, RX_PORT_PPP0, "# of PPP prio 0 frames received");
8083 	T4_REGSTAT(rx_ppp1, RX_PORT_PPP1, "# of PPP prio 1 frames received");
8084 	T4_REGSTAT(rx_ppp2, RX_PORT_PPP2, "# of PPP prio 2 frames received");
8085 	T4_REGSTAT(rx_ppp3, RX_PORT_PPP3, "# of PPP prio 3 frames received");
8086 	T4_REGSTAT(rx_ppp4, RX_PORT_PPP4, "# of PPP prio 4 frames received");
8087 	T4_REGSTAT(rx_ppp5, RX_PORT_PPP5, "# of PPP prio 5 frames received");
8088 	T4_REGSTAT(rx_ppp6, RX_PORT_PPP6, "# of PPP prio 6 frames received");
8089 	T4_REGSTAT(rx_ppp7, RX_PORT_PPP7, "# of PPP prio 7 frames received");
8090 
8091 	T4_PORTSTAT(rx_ovflow0, "# drops due to buffer-group 0 overflows");
8092 	T4_PORTSTAT(rx_ovflow1, "# drops due to buffer-group 1 overflows");
8093 	T4_PORTSTAT(rx_ovflow2, "# drops due to buffer-group 2 overflows");
8094 	T4_PORTSTAT(rx_ovflow3, "# drops due to buffer-group 3 overflows");
8095 	T4_PORTSTAT(rx_trunc0, "# of buffer-group 0 truncated packets");
8096 	T4_PORTSTAT(rx_trunc1, "# of buffer-group 1 truncated packets");
8097 	T4_PORTSTAT(rx_trunc2, "# of buffer-group 2 truncated packets");
8098 	T4_PORTSTAT(rx_trunc3, "# of buffer-group 3 truncated packets");
8099 
8100 #undef T4_REGSTAT
8101 #undef T4_PORTSTAT
8102 }
8103 
8104 static int
8105 sysctl_int_array(SYSCTL_HANDLER_ARGS)
8106 {
8107 	int rc, *i, space = 0;
8108 	struct sbuf sb;
8109 
8110 	sbuf_new_for_sysctl(&sb, NULL, 64, req);
8111 	for (i = arg1; arg2; arg2 -= sizeof(int), i++) {
8112 		if (space)
8113 			sbuf_printf(&sb, " ");
8114 		sbuf_printf(&sb, "%d", *i);
8115 		space = 1;
8116 	}
8117 	rc = sbuf_finish(&sb);
8118 	sbuf_delete(&sb);
8119 	return (rc);
8120 }
8121 
8122 static int
8123 sysctl_bitfield_8b(SYSCTL_HANDLER_ARGS)
8124 {
8125 	int rc;
8126 	struct sbuf *sb;
8127 
8128 	rc = sysctl_wire_old_buffer(req, 0);
8129 	if (rc != 0)
8130 		return(rc);
8131 
8132 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8133 	if (sb == NULL)
8134 		return (ENOMEM);
8135 
8136 	sbuf_printf(sb, "%b", *(uint8_t *)(uintptr_t)arg2, (char *)arg1);
8137 	rc = sbuf_finish(sb);
8138 	sbuf_delete(sb);
8139 
8140 	return (rc);
8141 }
8142 
8143 static int
8144 sysctl_bitfield_16b(SYSCTL_HANDLER_ARGS)
8145 {
8146 	int rc;
8147 	struct sbuf *sb;
8148 
8149 	rc = sysctl_wire_old_buffer(req, 0);
8150 	if (rc != 0)
8151 		return(rc);
8152 
8153 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8154 	if (sb == NULL)
8155 		return (ENOMEM);
8156 
8157 	sbuf_printf(sb, "%b", *(uint16_t *)(uintptr_t)arg2, (char *)arg1);
8158 	rc = sbuf_finish(sb);
8159 	sbuf_delete(sb);
8160 
8161 	return (rc);
8162 }
8163 
8164 static int
8165 sysctl_btphy(SYSCTL_HANDLER_ARGS)
8166 {
8167 	struct port_info *pi = arg1;
8168 	int op = arg2;
8169 	struct adapter *sc = pi->adapter;
8170 	u_int v;
8171 	int rc;
8172 
8173 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4btt");
8174 	if (rc)
8175 		return (rc);
8176 	if (hw_off_limits(sc))
8177 		rc = ENXIO;
8178 	else {
8179 		/* XXX: magic numbers */
8180 		rc = -t4_mdio_rd(sc, sc->mbox, pi->mdio_addr, 0x1e,
8181 		    op ? 0x20 : 0xc820, &v);
8182 	}
8183 	end_synchronized_op(sc, 0);
8184 	if (rc)
8185 		return (rc);
8186 	if (op == 0)
8187 		v /= 256;
8188 
8189 	rc = sysctl_handle_int(oidp, &v, 0, req);
8190 	return (rc);
8191 }
8192 
8193 static int
8194 sysctl_noflowq(SYSCTL_HANDLER_ARGS)
8195 {
8196 	struct vi_info *vi = arg1;
8197 	int rc, val;
8198 
8199 	val = vi->rsrv_noflowq;
8200 	rc = sysctl_handle_int(oidp, &val, 0, req);
8201 	if (rc != 0 || req->newptr == NULL)
8202 		return (rc);
8203 
8204 	if ((val >= 1) && (vi->ntxq > 1))
8205 		vi->rsrv_noflowq = 1;
8206 	else
8207 		vi->rsrv_noflowq = 0;
8208 
8209 	return (rc);
8210 }
8211 
8212 static int
8213 sysctl_tx_vm_wr(SYSCTL_HANDLER_ARGS)
8214 {
8215 	struct vi_info *vi = arg1;
8216 	struct adapter *sc = vi->adapter;
8217 	int rc, val, i;
8218 
8219 	MPASS(!(sc->flags & IS_VF));
8220 
8221 	val = vi->flags & TX_USES_VM_WR ? 1 : 0;
8222 	rc = sysctl_handle_int(oidp, &val, 0, req);
8223 	if (rc != 0 || req->newptr == NULL)
8224 		return (rc);
8225 
8226 	if (val != 0 && val != 1)
8227 		return (EINVAL);
8228 
8229 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8230 	    "t4txvm");
8231 	if (rc)
8232 		return (rc);
8233 	if (hw_off_limits(sc))
8234 		rc = ENXIO;
8235 	else if (if_getdrvflags(vi->ifp) & IFF_DRV_RUNNING) {
8236 		/*
8237 		 * We don't want parse_pkt to run with one setting (VF or PF)
8238 		 * and then eth_tx to see a different setting but still use
8239 		 * stale information calculated by parse_pkt.
8240 		 */
8241 		rc = EBUSY;
8242 	} else {
8243 		struct port_info *pi = vi->pi;
8244 		struct sge_txq *txq;
8245 		uint32_t ctrl0;
8246 		uint8_t npkt = sc->params.max_pkts_per_eth_tx_pkts_wr;
8247 
8248 		if (val) {
8249 			vi->flags |= TX_USES_VM_WR;
8250 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_VM_TSO);
8251 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8252 			    V_TXPKT_INTF(pi->tx_chan));
8253 			if (!(sc->flags & IS_VF))
8254 				npkt--;
8255 		} else {
8256 			vi->flags &= ~TX_USES_VM_WR;
8257 			if_sethwtsomaxsegcount(vi->ifp, TX_SGL_SEGS_TSO);
8258 			ctrl0 = htobe32(V_TXPKT_OPCODE(CPL_TX_PKT_XT) |
8259 			    V_TXPKT_INTF(pi->tx_chan) | V_TXPKT_PF(sc->pf) |
8260 			    V_TXPKT_VF(vi->vin) | V_TXPKT_VF_VLD(vi->vfvld));
8261 		}
8262 		for_each_txq(vi, i, txq) {
8263 			txq->cpl_ctrl0 = ctrl0;
8264 			txq->txp.max_npkt = npkt;
8265 		}
8266 	}
8267 	end_synchronized_op(sc, LOCK_HELD);
8268 	return (rc);
8269 }
8270 
8271 static int
8272 sysctl_holdoff_tmr_idx(SYSCTL_HANDLER_ARGS)
8273 {
8274 	struct vi_info *vi = arg1;
8275 	struct adapter *sc = vi->adapter;
8276 	int idx, rc, i;
8277 	struct sge_rxq *rxq;
8278 	uint8_t v;
8279 
8280 	idx = vi->tmr_idx;
8281 
8282 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8283 	if (rc != 0 || req->newptr == NULL)
8284 		return (rc);
8285 
8286 	if (idx < 0 || idx >= SGE_NTIMERS)
8287 		return (EINVAL);
8288 
8289 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8290 	    "t4tmr");
8291 	if (rc)
8292 		return (rc);
8293 
8294 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->pktc_idx != -1);
8295 	for_each_rxq(vi, i, rxq) {
8296 #ifdef atomic_store_rel_8
8297 		atomic_store_rel_8(&rxq->iq.intr_params, v);
8298 #else
8299 		rxq->iq.intr_params = v;
8300 #endif
8301 	}
8302 	vi->tmr_idx = idx;
8303 
8304 	end_synchronized_op(sc, LOCK_HELD);
8305 	return (0);
8306 }
8307 
8308 static int
8309 sysctl_holdoff_pktc_idx(SYSCTL_HANDLER_ARGS)
8310 {
8311 	struct vi_info *vi = arg1;
8312 	struct adapter *sc = vi->adapter;
8313 	int idx, rc;
8314 
8315 	idx = vi->pktc_idx;
8316 
8317 	rc = sysctl_handle_int(oidp, &idx, 0, req);
8318 	if (rc != 0 || req->newptr == NULL)
8319 		return (rc);
8320 
8321 	if (idx < -1 || idx >= SGE_NCOUNTERS)
8322 		return (EINVAL);
8323 
8324 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8325 	    "t4pktc");
8326 	if (rc)
8327 		return (rc);
8328 
8329 	if (vi->flags & VI_INIT_DONE)
8330 		rc = EBUSY; /* cannot be changed once the queues are created */
8331 	else
8332 		vi->pktc_idx = idx;
8333 
8334 	end_synchronized_op(sc, LOCK_HELD);
8335 	return (rc);
8336 }
8337 
8338 static int
8339 sysctl_qsize_rxq(SYSCTL_HANDLER_ARGS)
8340 {
8341 	struct vi_info *vi = arg1;
8342 	struct adapter *sc = vi->adapter;
8343 	int qsize, rc;
8344 
8345 	qsize = vi->qsize_rxq;
8346 
8347 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8348 	if (rc != 0 || req->newptr == NULL)
8349 		return (rc);
8350 
8351 	if (qsize < 128 || (qsize & 7))
8352 		return (EINVAL);
8353 
8354 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8355 	    "t4rxqs");
8356 	if (rc)
8357 		return (rc);
8358 
8359 	if (vi->flags & VI_INIT_DONE)
8360 		rc = EBUSY; /* cannot be changed once the queues are created */
8361 	else
8362 		vi->qsize_rxq = qsize;
8363 
8364 	end_synchronized_op(sc, LOCK_HELD);
8365 	return (rc);
8366 }
8367 
8368 static int
8369 sysctl_qsize_txq(SYSCTL_HANDLER_ARGS)
8370 {
8371 	struct vi_info *vi = arg1;
8372 	struct adapter *sc = vi->adapter;
8373 	int qsize, rc;
8374 
8375 	qsize = vi->qsize_txq;
8376 
8377 	rc = sysctl_handle_int(oidp, &qsize, 0, req);
8378 	if (rc != 0 || req->newptr == NULL)
8379 		return (rc);
8380 
8381 	if (qsize < 128 || qsize > 65536)
8382 		return (EINVAL);
8383 
8384 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
8385 	    "t4txqs");
8386 	if (rc)
8387 		return (rc);
8388 
8389 	if (vi->flags & VI_INIT_DONE)
8390 		rc = EBUSY; /* cannot be changed once the queues are created */
8391 	else
8392 		vi->qsize_txq = qsize;
8393 
8394 	end_synchronized_op(sc, LOCK_HELD);
8395 	return (rc);
8396 }
8397 
8398 static int
8399 sysctl_pause_settings(SYSCTL_HANDLER_ARGS)
8400 {
8401 	struct port_info *pi = arg1;
8402 	struct adapter *sc = pi->adapter;
8403 	struct link_config *lc = &pi->link_cfg;
8404 	int rc;
8405 
8406 	if (req->newptr == NULL) {
8407 		struct sbuf *sb;
8408 		static char *bits = "\20\1RX\2TX\3AUTO";
8409 
8410 		rc = sysctl_wire_old_buffer(req, 0);
8411 		if (rc != 0)
8412 			return(rc);
8413 
8414 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8415 		if (sb == NULL)
8416 			return (ENOMEM);
8417 
8418 		if (lc->link_ok) {
8419 			sbuf_printf(sb, "%b", (lc->fc & (PAUSE_TX | PAUSE_RX)) |
8420 			    (lc->requested_fc & PAUSE_AUTONEG), bits);
8421 		} else {
8422 			sbuf_printf(sb, "%b", lc->requested_fc & (PAUSE_TX |
8423 			    PAUSE_RX | PAUSE_AUTONEG), bits);
8424 		}
8425 		rc = sbuf_finish(sb);
8426 		sbuf_delete(sb);
8427 	} else {
8428 		char s[2];
8429 		int n;
8430 
8431 		s[0] = '0' + (lc->requested_fc & (PAUSE_TX | PAUSE_RX |
8432 		    PAUSE_AUTONEG));
8433 		s[1] = 0;
8434 
8435 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8436 		if (rc != 0)
8437 			return(rc);
8438 
8439 		if (s[1] != 0)
8440 			return (EINVAL);
8441 		if (s[0] < '0' || s[0] > '9')
8442 			return (EINVAL);	/* not a number */
8443 		n = s[0] - '0';
8444 		if (n & ~(PAUSE_TX | PAUSE_RX | PAUSE_AUTONEG))
8445 			return (EINVAL);	/* some other bit is set too */
8446 
8447 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8448 		    "t4PAUSE");
8449 		if (rc)
8450 			return (rc);
8451 		if (!hw_off_limits(sc)) {
8452 			PORT_LOCK(pi);
8453 			lc->requested_fc = n;
8454 			fixup_link_config(pi);
8455 			if (pi->up_vis > 0)
8456 				rc = apply_link_config(pi);
8457 			set_current_media(pi);
8458 			PORT_UNLOCK(pi);
8459 		}
8460 		end_synchronized_op(sc, 0);
8461 	}
8462 
8463 	return (rc);
8464 }
8465 
8466 static int
8467 sysctl_link_fec(SYSCTL_HANDLER_ARGS)
8468 {
8469 	struct port_info *pi = arg1;
8470 	struct link_config *lc = &pi->link_cfg;
8471 	int rc;
8472 	struct sbuf *sb;
8473 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD1\5RSVD2";
8474 
8475 	rc = sysctl_wire_old_buffer(req, 0);
8476 	if (rc != 0)
8477 		return(rc);
8478 
8479 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8480 	if (sb == NULL)
8481 		return (ENOMEM);
8482 	if (lc->link_ok)
8483 		sbuf_printf(sb, "%b", lc->fec, bits);
8484 	else
8485 		sbuf_printf(sb, "no link");
8486 	rc = sbuf_finish(sb);
8487 	sbuf_delete(sb);
8488 
8489 	return (rc);
8490 }
8491 
8492 static int
8493 sysctl_requested_fec(SYSCTL_HANDLER_ARGS)
8494 {
8495 	struct port_info *pi = arg1;
8496 	struct adapter *sc = pi->adapter;
8497 	struct link_config *lc = &pi->link_cfg;
8498 	int rc;
8499 	int8_t old;
8500 
8501 	if (req->newptr == NULL) {
8502 		struct sbuf *sb;
8503 		static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2"
8504 		    "\5RSVD3\6auto\7module";
8505 
8506 		rc = sysctl_wire_old_buffer(req, 0);
8507 		if (rc != 0)
8508 			return(rc);
8509 
8510 		sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8511 		if (sb == NULL)
8512 			return (ENOMEM);
8513 
8514 		sbuf_printf(sb, "%b", lc->requested_fec, bits);
8515 		rc = sbuf_finish(sb);
8516 		sbuf_delete(sb);
8517 	} else {
8518 		char s[8];
8519 		int n;
8520 
8521 		snprintf(s, sizeof(s), "%d",
8522 		    lc->requested_fec == FEC_AUTO ? -1 :
8523 		    lc->requested_fec & (M_FW_PORT_CAP32_FEC | FEC_MODULE));
8524 
8525 		rc = sysctl_handle_string(oidp, s, sizeof(s), req);
8526 		if (rc != 0)
8527 			return(rc);
8528 
8529 		n = strtol(&s[0], NULL, 0);
8530 		if (n < 0 || n & FEC_AUTO)
8531 			n = FEC_AUTO;
8532 		else if (n & ~(M_FW_PORT_CAP32_FEC | FEC_MODULE))
8533 			return (EINVAL);/* some other bit is set too */
8534 
8535 		rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8536 		    "t4reqf");
8537 		if (rc)
8538 			return (rc);
8539 		PORT_LOCK(pi);
8540 		old = lc->requested_fec;
8541 		if (n == FEC_AUTO)
8542 			lc->requested_fec = FEC_AUTO;
8543 		else if (n == 0 || n == FEC_NONE)
8544 			lc->requested_fec = FEC_NONE;
8545 		else {
8546 			if ((lc->pcaps |
8547 			    V_FW_PORT_CAP32_FEC(n & M_FW_PORT_CAP32_FEC)) !=
8548 			    lc->pcaps) {
8549 				rc = ENOTSUP;
8550 				goto done;
8551 			}
8552 			lc->requested_fec = n & (M_FW_PORT_CAP32_FEC |
8553 			    FEC_MODULE);
8554 		}
8555 		if (!hw_off_limits(sc)) {
8556 			fixup_link_config(pi);
8557 			if (pi->up_vis > 0) {
8558 				rc = apply_link_config(pi);
8559 				if (rc != 0) {
8560 					lc->requested_fec = old;
8561 					if (rc == FW_EPROTO)
8562 						rc = ENOTSUP;
8563 				}
8564 			}
8565 		}
8566 done:
8567 		PORT_UNLOCK(pi);
8568 		end_synchronized_op(sc, 0);
8569 	}
8570 
8571 	return (rc);
8572 }
8573 
8574 static int
8575 sysctl_module_fec(SYSCTL_HANDLER_ARGS)
8576 {
8577 	struct port_info *pi = arg1;
8578 	struct adapter *sc = pi->adapter;
8579 	struct link_config *lc = &pi->link_cfg;
8580 	int rc;
8581 	int8_t fec;
8582 	struct sbuf *sb;
8583 	static char *bits = "\20\1RS-FEC\2FC-FEC\3NO-FEC\4RSVD2\5RSVD3";
8584 
8585 	rc = sysctl_wire_old_buffer(req, 0);
8586 	if (rc != 0)
8587 		return (rc);
8588 
8589 	sb = sbuf_new_for_sysctl(NULL, NULL, 128, req);
8590 	if (sb == NULL)
8591 		return (ENOMEM);
8592 
8593 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4mfec") != 0) {
8594 		rc = EBUSY;
8595 		goto done;
8596 	}
8597 	if (hw_off_limits(sc)) {
8598 		rc = ENXIO;
8599 		goto done;
8600 	}
8601 	PORT_LOCK(pi);
8602 	if (pi->up_vis == 0) {
8603 		/*
8604 		 * If all the interfaces are administratively down the firmware
8605 		 * does not report transceiver changes.  Refresh port info here.
8606 		 * This is the only reason we have a synchronized op in this
8607 		 * function.  Just PORT_LOCK would have been enough otherwise.
8608 		 */
8609 		t4_update_port_info(pi);
8610 	}
8611 
8612 	fec = lc->fec_hint;
8613 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE ||
8614 	    !fec_supported(lc->pcaps)) {
8615 		sbuf_printf(sb, "n/a");
8616 	} else {
8617 		if (fec == 0)
8618 			fec = FEC_NONE;
8619 		sbuf_printf(sb, "%b", fec & M_FW_PORT_CAP32_FEC, bits);
8620 	}
8621 	rc = sbuf_finish(sb);
8622 	PORT_UNLOCK(pi);
8623 done:
8624 	sbuf_delete(sb);
8625 	end_synchronized_op(sc, 0);
8626 
8627 	return (rc);
8628 }
8629 
8630 static int
8631 sysctl_autoneg(SYSCTL_HANDLER_ARGS)
8632 {
8633 	struct port_info *pi = arg1;
8634 	struct adapter *sc = pi->adapter;
8635 	struct link_config *lc = &pi->link_cfg;
8636 	int rc, val;
8637 
8638 	if (lc->pcaps & FW_PORT_CAP32_ANEG)
8639 		val = lc->requested_aneg == AUTONEG_DISABLE ? 0 : 1;
8640 	else
8641 		val = -1;
8642 	rc = sysctl_handle_int(oidp, &val, 0, req);
8643 	if (rc != 0 || req->newptr == NULL)
8644 		return (rc);
8645 	if (val == 0)
8646 		val = AUTONEG_DISABLE;
8647 	else if (val == 1)
8648 		val = AUTONEG_ENABLE;
8649 	else
8650 		val = AUTONEG_AUTO;
8651 
8652 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK,
8653 	    "t4aneg");
8654 	if (rc)
8655 		return (rc);
8656 	PORT_LOCK(pi);
8657 	if (val == AUTONEG_ENABLE && !(lc->pcaps & FW_PORT_CAP32_ANEG)) {
8658 		rc = ENOTSUP;
8659 		goto done;
8660 	}
8661 	lc->requested_aneg = val;
8662 	if (!hw_off_limits(sc)) {
8663 		fixup_link_config(pi);
8664 		if (pi->up_vis > 0)
8665 			rc = apply_link_config(pi);
8666 		set_current_media(pi);
8667 	}
8668 done:
8669 	PORT_UNLOCK(pi);
8670 	end_synchronized_op(sc, 0);
8671 	return (rc);
8672 }
8673 
8674 static int
8675 sysctl_force_fec(SYSCTL_HANDLER_ARGS)
8676 {
8677 	struct port_info *pi = arg1;
8678 	struct adapter *sc = pi->adapter;
8679 	struct link_config *lc = &pi->link_cfg;
8680 	int rc, val;
8681 
8682 	val = lc->force_fec;
8683 	MPASS(val >= -1 && val <= 1);
8684 	rc = sysctl_handle_int(oidp, &val, 0, req);
8685 	if (rc != 0 || req->newptr == NULL)
8686 		return (rc);
8687 	if (!(lc->pcaps & FW_PORT_CAP32_FORCE_FEC))
8688 		return (ENOTSUP);
8689 	if (val < -1 || val > 1)
8690 		return (EINVAL);
8691 
8692 	rc = begin_synchronized_op(sc, &pi->vi[0], SLEEP_OK | INTR_OK, "t4ff");
8693 	if (rc)
8694 		return (rc);
8695 	PORT_LOCK(pi);
8696 	lc->force_fec = 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 	}
8702 	PORT_UNLOCK(pi);
8703 	end_synchronized_op(sc, 0);
8704 	return (rc);
8705 }
8706 
8707 static int
8708 sysctl_handle_t4_reg64(SYSCTL_HANDLER_ARGS)
8709 {
8710 	struct adapter *sc = arg1;
8711 	int rc, reg = arg2;
8712 	uint64_t val;
8713 
8714 	mtx_lock(&sc->reg_lock);
8715 	if (hw_off_limits(sc))
8716 		rc = ENXIO;
8717 	else {
8718 		rc = 0;
8719 		val = t4_read_reg64(sc, reg);
8720 	}
8721 	mtx_unlock(&sc->reg_lock);
8722 	if (rc == 0)
8723 		rc = sysctl_handle_64(oidp, &val, 0, req);
8724 	return (rc);
8725 }
8726 
8727 static int
8728 sysctl_temperature(SYSCTL_HANDLER_ARGS)
8729 {
8730 	struct adapter *sc = arg1;
8731 	int rc, t;
8732 	uint32_t param, val;
8733 
8734 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4temp");
8735 	if (rc)
8736 		return (rc);
8737 	if (hw_off_limits(sc))
8738 		rc = ENXIO;
8739 	else {
8740 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8741 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8742 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_TMP);
8743 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8744 	}
8745 	end_synchronized_op(sc, 0);
8746 	if (rc)
8747 		return (rc);
8748 
8749 	/* unknown is returned as 0 but we display -1 in that case */
8750 	t = val == 0 ? -1 : val;
8751 
8752 	rc = sysctl_handle_int(oidp, &t, 0, req);
8753 	return (rc);
8754 }
8755 
8756 static int
8757 sysctl_vdd(SYSCTL_HANDLER_ARGS)
8758 {
8759 	struct adapter *sc = arg1;
8760 	int rc;
8761 	uint32_t param, val;
8762 
8763 	if (sc->params.core_vdd == 0) {
8764 		rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
8765 		    "t4vdd");
8766 		if (rc)
8767 			return (rc);
8768 		if (hw_off_limits(sc))
8769 			rc = ENXIO;
8770 		else {
8771 			param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8772 			    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8773 			    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_VDD);
8774 			rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1,
8775 			    &param, &val);
8776 		}
8777 		end_synchronized_op(sc, 0);
8778 		if (rc)
8779 			return (rc);
8780 		sc->params.core_vdd = val;
8781 	}
8782 
8783 	return (sysctl_handle_int(oidp, &sc->params.core_vdd, 0, req));
8784 }
8785 
8786 static int
8787 sysctl_reset_sensor(SYSCTL_HANDLER_ARGS)
8788 {
8789 	struct adapter *sc = arg1;
8790 	int rc, v;
8791 	uint32_t param, val;
8792 
8793 	v = sc->sensor_resets;
8794 	rc = sysctl_handle_int(oidp, &v, 0, req);
8795 	if (rc != 0 || req->newptr == NULL || v <= 0)
8796 		return (rc);
8797 
8798 	if (sc->params.fw_vers < FW_VERSION32(1, 24, 7, 0) ||
8799 	    chip_id(sc) < CHELSIO_T5)
8800 		return (ENOTSUP);
8801 
8802 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4srst");
8803 	if (rc)
8804 		return (rc);
8805 	if (hw_off_limits(sc))
8806 		rc = ENXIO;
8807 	else {
8808 		param = (V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8809 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_DIAG) |
8810 		    V_FW_PARAMS_PARAM_Y(FW_PARAM_DEV_DIAG_RESET_TMP_SENSOR));
8811 		val = 1;
8812 		rc = -t4_set_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8813 	}
8814 	end_synchronized_op(sc, 0);
8815 	if (rc == 0)
8816 		sc->sensor_resets++;
8817 	return (rc);
8818 }
8819 
8820 static int
8821 sysctl_loadavg(SYSCTL_HANDLER_ARGS)
8822 {
8823 	struct adapter *sc = arg1;
8824 	struct sbuf *sb;
8825 	int rc;
8826 	uint32_t param, val;
8827 
8828 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4lavg");
8829 	if (rc)
8830 		return (rc);
8831 	if (hw_off_limits(sc))
8832 		rc = ENXIO;
8833 	else {
8834 		param = V_FW_PARAMS_MNEM(FW_PARAMS_MNEM_DEV) |
8835 		    V_FW_PARAMS_PARAM_X(FW_PARAMS_PARAM_DEV_LOAD);
8836 		rc = -t4_query_params(sc, sc->mbox, sc->pf, 0, 1, &param, &val);
8837 	}
8838 	end_synchronized_op(sc, 0);
8839 	if (rc)
8840 		return (rc);
8841 
8842 	rc = sysctl_wire_old_buffer(req, 0);
8843 	if (rc != 0)
8844 		return (rc);
8845 
8846 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8847 	if (sb == NULL)
8848 		return (ENOMEM);
8849 
8850 	if (val == 0xffffffff) {
8851 		/* Only debug and custom firmwares report load averages. */
8852 		sbuf_printf(sb, "not available");
8853 	} else {
8854 		sbuf_printf(sb, "%d %d %d", val & 0xff, (val >> 8) & 0xff,
8855 		    (val >> 16) & 0xff);
8856 	}
8857 	rc = sbuf_finish(sb);
8858 	sbuf_delete(sb);
8859 
8860 	return (rc);
8861 }
8862 
8863 static int
8864 sysctl_cctrl(SYSCTL_HANDLER_ARGS)
8865 {
8866 	struct adapter *sc = arg1;
8867 	struct sbuf *sb;
8868 	int rc, i;
8869 	uint16_t incr[NMTUS][NCCTRL_WIN];
8870 	static const char *dec_fac[] = {
8871 		"0.5", "0.5625", "0.625", "0.6875", "0.75", "0.8125", "0.875",
8872 		"0.9375"
8873 	};
8874 
8875 	rc = sysctl_wire_old_buffer(req, 0);
8876 	if (rc != 0)
8877 		return (rc);
8878 
8879 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
8880 	if (sb == NULL)
8881 		return (ENOMEM);
8882 
8883 	mtx_lock(&sc->reg_lock);
8884 	if (hw_off_limits(sc))
8885 		rc = ENXIO;
8886 	else
8887 		t4_read_cong_tbl(sc, incr);
8888 	mtx_unlock(&sc->reg_lock);
8889 	if (rc)
8890 		goto done;
8891 
8892 	for (i = 0; i < NCCTRL_WIN; ++i) {
8893 		sbuf_printf(sb, "%2d: %4u %4u %4u %4u %4u %4u %4u %4u\n", i,
8894 		    incr[0][i], incr[1][i], incr[2][i], incr[3][i], incr[4][i],
8895 		    incr[5][i], incr[6][i], incr[7][i]);
8896 		sbuf_printf(sb, "%8u %4u %4u %4u %4u %4u %4u %4u %5u %s\n",
8897 		    incr[8][i], incr[9][i], incr[10][i], incr[11][i],
8898 		    incr[12][i], incr[13][i], incr[14][i], incr[15][i],
8899 		    sc->params.a_wnd[i], dec_fac[sc->params.b_wnd[i]]);
8900 	}
8901 
8902 	rc = sbuf_finish(sb);
8903 done:
8904 	sbuf_delete(sb);
8905 	return (rc);
8906 }
8907 
8908 static const char *qname[CIM_NUM_IBQ + CIM_NUM_OBQ_T5] = {
8909 	"TP0", "TP1", "ULP", "SGE0", "SGE1", "NC-SI",	/* ibq's */
8910 	"ULP0", "ULP1", "ULP2", "ULP3", "SGE", "NC-SI",	/* obq's */
8911 	"SGE0-RX", "SGE1-RX"	/* additional obq's (T5 onwards) */
8912 };
8913 
8914 static int
8915 sysctl_cim_ibq_obq(SYSCTL_HANDLER_ARGS)
8916 {
8917 	struct adapter *sc = arg1;
8918 	struct sbuf *sb;
8919 	int rc, i, n, qid = arg2;
8920 	uint32_t *buf, *p;
8921 	char *qtype;
8922 	u_int cim_num_obq = sc->chip_params->cim_num_obq;
8923 
8924 	KASSERT(qid >= 0 && qid < CIM_NUM_IBQ + cim_num_obq,
8925 	    ("%s: bad qid %d\n", __func__, qid));
8926 
8927 	if (qid < CIM_NUM_IBQ) {
8928 		/* inbound queue */
8929 		qtype = "IBQ";
8930 		n = 4 * CIM_IBQ_SIZE;
8931 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8932 		mtx_lock(&sc->reg_lock);
8933 		if (hw_off_limits(sc))
8934 			rc = -ENXIO;
8935 		else
8936 			rc = t4_read_cim_ibq(sc, qid, buf, n);
8937 		mtx_unlock(&sc->reg_lock);
8938 	} else {
8939 		/* outbound queue */
8940 		qtype = "OBQ";
8941 		qid -= CIM_NUM_IBQ;
8942 		n = 4 * cim_num_obq * CIM_OBQ_SIZE;
8943 		buf = malloc(n * sizeof(uint32_t), M_CXGBE, M_ZERO | M_WAITOK);
8944 		mtx_lock(&sc->reg_lock);
8945 		if (hw_off_limits(sc))
8946 			rc = -ENXIO;
8947 		else
8948 			rc = t4_read_cim_obq(sc, qid, buf, n);
8949 		mtx_unlock(&sc->reg_lock);
8950 	}
8951 
8952 	if (rc < 0) {
8953 		rc = -rc;
8954 		goto done;
8955 	}
8956 	n = rc * sizeof(uint32_t);	/* rc has # of words actually read */
8957 
8958 	rc = sysctl_wire_old_buffer(req, 0);
8959 	if (rc != 0)
8960 		goto done;
8961 
8962 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
8963 	if (sb == NULL) {
8964 		rc = ENOMEM;
8965 		goto done;
8966 	}
8967 
8968 	sbuf_printf(sb, "%s%d %s", qtype , qid, qname[arg2]);
8969 	for (i = 0, p = buf; i < n; i += 16, p += 4)
8970 		sbuf_printf(sb, "\n%#06x: %08x %08x %08x %08x", i, p[0], p[1],
8971 		    p[2], p[3]);
8972 
8973 	rc = sbuf_finish(sb);
8974 	sbuf_delete(sb);
8975 done:
8976 	free(buf, M_CXGBE);
8977 	return (rc);
8978 }
8979 
8980 static void
8981 sbuf_cim_la4(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
8982 {
8983 	uint32_t *p;
8984 
8985 	sbuf_printf(sb, "Status   Data      PC%s",
8986 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
8987 	    "     LS0Stat  LS0Addr             LS0Data");
8988 
8989 	for (p = buf; p <= &buf[sc->params.cim_la_size - 8]; p += 8) {
8990 		if (cfg & F_UPDBGLACAPTPCONLY) {
8991 			sbuf_printf(sb, "\n  %02x   %08x %08x", p[5] & 0xff,
8992 			    p[6], p[7]);
8993 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x",
8994 			    (p[3] >> 8) & 0xff, p[3] & 0xff, p[4] >> 8,
8995 			    p[4] & 0xff, p[5] >> 8);
8996 			sbuf_printf(sb, "\n  %02x   %x%07x %x%07x",
8997 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
8998 			    p[1] & 0xf, p[2] >> 4);
8999 		} else {
9000 			sbuf_printf(sb,
9001 			    "\n  %02x   %x%07x %x%07x %08x %08x "
9002 			    "%08x%08x%08x%08x",
9003 			    (p[0] >> 4) & 0xff, p[0] & 0xf, p[1] >> 4,
9004 			    p[1] & 0xf, p[2] >> 4, p[2] & 0xf, p[3], p[4], p[5],
9005 			    p[6], p[7]);
9006 		}
9007 	}
9008 }
9009 
9010 static void
9011 sbuf_cim_la6(struct adapter *sc, struct sbuf *sb, uint32_t *buf, uint32_t cfg)
9012 {
9013 	uint32_t *p;
9014 
9015 	sbuf_printf(sb, "Status   Inst    Data      PC%s",
9016 	    cfg & F_UPDBGLACAPTPCONLY ? "" :
9017 	    "     LS0Stat  LS0Addr  LS0Data  LS1Stat  LS1Addr  LS1Data");
9018 
9019 	for (p = buf; p <= &buf[sc->params.cim_la_size - 10]; p += 10) {
9020 		if (cfg & F_UPDBGLACAPTPCONLY) {
9021 			sbuf_printf(sb, "\n  %02x   %08x %08x %08x",
9022 			    p[3] & 0xff, p[2], p[1], p[0]);
9023 			sbuf_printf(sb, "\n  %02x   %02x%06x %02x%06x %02x%06x",
9024 			    (p[6] >> 8) & 0xff, p[6] & 0xff, p[5] >> 8,
9025 			    p[5] & 0xff, p[4] >> 8, p[4] & 0xff, p[3] >> 8);
9026 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x",
9027 			    (p[9] >> 16) & 0xff, p[9] & 0xffff, p[8] >> 16,
9028 			    p[8] & 0xffff, p[7] >> 16, p[7] & 0xffff,
9029 			    p[6] >> 16);
9030 		} else {
9031 			sbuf_printf(sb, "\n  %02x   %04x%04x %04x%04x %04x%04x "
9032 			    "%08x %08x %08x %08x %08x %08x",
9033 			    (p[9] >> 16) & 0xff,
9034 			    p[9] & 0xffff, p[8] >> 16,
9035 			    p[8] & 0xffff, p[7] >> 16,
9036 			    p[7] & 0xffff, p[6] >> 16,
9037 			    p[2], p[1], p[0], p[5], p[4], p[3]);
9038 		}
9039 	}
9040 }
9041 
9042 static int
9043 sbuf_cim_la(struct adapter *sc, struct sbuf *sb, int flags)
9044 {
9045 	uint32_t cfg, *buf;
9046 	int rc;
9047 
9048 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9049 	buf = malloc(sc->params.cim_la_size * sizeof(uint32_t), M_CXGBE,
9050 	    M_ZERO | flags);
9051 	if (buf == NULL)
9052 		return (ENOMEM);
9053 
9054 	mtx_lock(&sc->reg_lock);
9055 	if (hw_off_limits(sc))
9056 		rc = ENXIO;
9057 	else {
9058 		rc = -t4_cim_read(sc, A_UP_UP_DBG_LA_CFG, 1, &cfg);
9059 		if (rc == 0)
9060 			rc = -t4_cim_read_la(sc, buf, NULL);
9061 	}
9062 	mtx_unlock(&sc->reg_lock);
9063 	if (rc == 0) {
9064 		if (chip_id(sc) < CHELSIO_T6)
9065 			sbuf_cim_la4(sc, sb, buf, cfg);
9066 		else
9067 			sbuf_cim_la6(sc, sb, buf, cfg);
9068 	}
9069 	free(buf, M_CXGBE);
9070 	return (rc);
9071 }
9072 
9073 static int
9074 sysctl_cim_la(SYSCTL_HANDLER_ARGS)
9075 {
9076 	struct adapter *sc = arg1;
9077 	struct sbuf *sb;
9078 	int rc;
9079 
9080 	rc = sysctl_wire_old_buffer(req, 0);
9081 	if (rc != 0)
9082 		return (rc);
9083 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9084 	if (sb == NULL)
9085 		return (ENOMEM);
9086 
9087 	rc = sbuf_cim_la(sc, sb, M_WAITOK);
9088 	if (rc == 0)
9089 		rc = sbuf_finish(sb);
9090 	sbuf_delete(sb);
9091 	return (rc);
9092 }
9093 
9094 static void
9095 dump_cim_regs(struct adapter *sc)
9096 {
9097 	log(LOG_DEBUG, "%s: CIM debug regs1 %08x %08x %08x %08x %08x\n",
9098 	    device_get_nameunit(sc->dev),
9099 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9100 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9101 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA2),
9102 	    t4_read_reg(sc, A_EDC_H_BIST_DATA_PATTERN),
9103 	    t4_read_reg(sc, A_EDC_H_BIST_STATUS_RDATA));
9104 	log(LOG_DEBUG, "%s: CIM debug regs2 %08x %08x %08x %08x %08x\n",
9105 	    device_get_nameunit(sc->dev),
9106 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0),
9107 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1),
9108 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA0 + 0x800),
9109 	    t4_read_reg(sc, A_EDC_H_BIST_USER_WDATA1 + 0x800),
9110 	    t4_read_reg(sc, A_EDC_H_BIST_CMD_LEN));
9111 }
9112 
9113 static void
9114 dump_cimla(struct adapter *sc)
9115 {
9116 	struct sbuf sb;
9117 	int rc;
9118 
9119 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9120 		log(LOG_DEBUG, "%s: failed to generate CIM LA dump.\n",
9121 		    device_get_nameunit(sc->dev));
9122 		return;
9123 	}
9124 	rc = sbuf_cim_la(sc, &sb, M_WAITOK);
9125 	if (rc == 0) {
9126 		rc = sbuf_finish(&sb);
9127 		if (rc == 0) {
9128 			log(LOG_DEBUG, "%s: CIM LA dump follows.\n%s\n",
9129 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9130 		}
9131 	}
9132 	sbuf_delete(&sb);
9133 }
9134 
9135 void
9136 t4_os_cim_err(struct adapter *sc)
9137 {
9138 	atomic_set_int(&sc->error_flags, ADAP_CIM_ERR);
9139 }
9140 
9141 static int
9142 sysctl_cim_ma_la(SYSCTL_HANDLER_ARGS)
9143 {
9144 	struct adapter *sc = arg1;
9145 	u_int i;
9146 	struct sbuf *sb;
9147 	uint32_t *buf, *p;
9148 	int rc;
9149 
9150 	rc = sysctl_wire_old_buffer(req, 0);
9151 	if (rc != 0)
9152 		return (rc);
9153 
9154 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9155 	if (sb == NULL)
9156 		return (ENOMEM);
9157 
9158 	buf = malloc(2 * CIM_MALA_SIZE * 5 * sizeof(uint32_t), M_CXGBE,
9159 	    M_ZERO | M_WAITOK);
9160 
9161 	mtx_lock(&sc->reg_lock);
9162 	if (hw_off_limits(sc))
9163 		rc = ENXIO;
9164 	else
9165 		t4_cim_read_ma_la(sc, buf, buf + 5 * CIM_MALA_SIZE);
9166 	mtx_unlock(&sc->reg_lock);
9167 	if (rc)
9168 		goto done;
9169 
9170 	p = buf;
9171 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9172 		sbuf_printf(sb, "\n%02x%08x%08x%08x%08x", p[4], p[3], p[2],
9173 		    p[1], p[0]);
9174 	}
9175 
9176 	sbuf_printf(sb, "\n\nCnt ID Tag UE       Data       RDY VLD");
9177 	for (i = 0; i < CIM_MALA_SIZE; i++, p += 5) {
9178 		sbuf_printf(sb, "\n%3u %2u  %x   %u %08x%08x  %u   %u",
9179 		    (p[2] >> 10) & 0xff, (p[2] >> 7) & 7,
9180 		    (p[2] >> 3) & 0xf, (p[2] >> 2) & 1,
9181 		    (p[1] >> 2) | ((p[2] & 3) << 30),
9182 		    (p[0] >> 2) | ((p[1] & 3) << 30), (p[0] >> 1) & 1,
9183 		    p[0] & 1);
9184 	}
9185 	rc = sbuf_finish(sb);
9186 done:
9187 	sbuf_delete(sb);
9188 	free(buf, M_CXGBE);
9189 	return (rc);
9190 }
9191 
9192 static int
9193 sysctl_cim_pif_la(SYSCTL_HANDLER_ARGS)
9194 {
9195 	struct adapter *sc = arg1;
9196 	u_int i;
9197 	struct sbuf *sb;
9198 	uint32_t *buf, *p;
9199 	int rc;
9200 
9201 	rc = sysctl_wire_old_buffer(req, 0);
9202 	if (rc != 0)
9203 		return (rc);
9204 
9205 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9206 	if (sb == NULL)
9207 		return (ENOMEM);
9208 
9209 	buf = malloc(2 * CIM_PIFLA_SIZE * 6 * sizeof(uint32_t), M_CXGBE,
9210 	    M_ZERO | M_WAITOK);
9211 
9212 	mtx_lock(&sc->reg_lock);
9213 	if (hw_off_limits(sc))
9214 		rc = ENXIO;
9215 	else
9216 		t4_cim_read_pif_la(sc, buf, buf + 6 * CIM_PIFLA_SIZE, NULL, NULL);
9217 	mtx_unlock(&sc->reg_lock);
9218 	if (rc)
9219 		goto done;
9220 
9221 	p = buf;
9222 	sbuf_printf(sb, "Cntl ID DataBE   Addr                 Data");
9223 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9224 		sbuf_printf(sb, "\n %02x  %02x  %04x  %08x %08x%08x%08x%08x",
9225 		    (p[5] >> 22) & 0xff, (p[5] >> 16) & 0x3f, p[5] & 0xffff,
9226 		    p[4], p[3], p[2], p[1], p[0]);
9227 	}
9228 
9229 	sbuf_printf(sb, "\n\nCntl ID               Data");
9230 	for (i = 0; i < CIM_PIFLA_SIZE; i++, p += 6) {
9231 		sbuf_printf(sb, "\n %02x  %02x %08x%08x%08x%08x",
9232 		    (p[4] >> 6) & 0xff, p[4] & 0x3f, p[3], p[2], p[1], p[0]);
9233 	}
9234 
9235 	rc = sbuf_finish(sb);
9236 done:
9237 	sbuf_delete(sb);
9238 	free(buf, M_CXGBE);
9239 	return (rc);
9240 }
9241 
9242 static int
9243 sysctl_cim_qcfg(SYSCTL_HANDLER_ARGS)
9244 {
9245 	struct adapter *sc = arg1;
9246 	struct sbuf *sb;
9247 	int rc, i;
9248 	uint16_t base[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9249 	uint16_t size[CIM_NUM_IBQ + CIM_NUM_OBQ_T5];
9250 	uint16_t thres[CIM_NUM_IBQ];
9251 	uint32_t obq_wr[2 * CIM_NUM_OBQ_T5], *wr = obq_wr;
9252 	uint32_t stat[4 * (CIM_NUM_IBQ + CIM_NUM_OBQ_T5)], *p = stat;
9253 	u_int cim_num_obq, ibq_rdaddr, obq_rdaddr, nq;
9254 
9255 	cim_num_obq = sc->chip_params->cim_num_obq;
9256 	if (is_t4(sc)) {
9257 		ibq_rdaddr = A_UP_IBQ_0_RDADDR;
9258 		obq_rdaddr = A_UP_OBQ_0_REALADDR;
9259 	} else {
9260 		ibq_rdaddr = A_UP_IBQ_0_SHADOW_RDADDR;
9261 		obq_rdaddr = A_UP_OBQ_0_SHADOW_REALADDR;
9262 	}
9263 	nq = CIM_NUM_IBQ + cim_num_obq;
9264 
9265 	mtx_lock(&sc->reg_lock);
9266 	if (hw_off_limits(sc))
9267 		rc = ENXIO;
9268 	else {
9269 		rc = -t4_cim_read(sc, ibq_rdaddr, 4 * nq, stat);
9270 		if (rc == 0) {
9271 			rc = -t4_cim_read(sc, obq_rdaddr, 2 * cim_num_obq,
9272 			    obq_wr);
9273 			if (rc == 0)
9274 				t4_read_cimq_cfg(sc, base, size, thres);
9275 		}
9276 	}
9277 	mtx_unlock(&sc->reg_lock);
9278 	if (rc)
9279 		return (rc);
9280 
9281 	rc = sysctl_wire_old_buffer(req, 0);
9282 	if (rc != 0)
9283 		return (rc);
9284 
9285 	sb = sbuf_new_for_sysctl(NULL, NULL, PAGE_SIZE, req);
9286 	if (sb == NULL)
9287 		return (ENOMEM);
9288 
9289 	sbuf_printf(sb,
9290 	    "  Queue  Base  Size Thres  RdPtr WrPtr  SOP  EOP Avail");
9291 
9292 	for (i = 0; i < CIM_NUM_IBQ; i++, p += 4)
9293 		sbuf_printf(sb, "\n%7s %5x %5u %5u %6x  %4x %4u %4u %5u",
9294 		    qname[i], base[i], size[i], thres[i], G_IBQRDADDR(p[0]),
9295 		    G_IBQWRADDR(p[1]), G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9296 		    G_QUEREMFLITS(p[2]) * 16);
9297 	for ( ; i < nq; i++, p += 4, wr += 2)
9298 		sbuf_printf(sb, "\n%7s %5x %5u %12x  %4x %4u %4u %5u", qname[i],
9299 		    base[i], size[i], G_QUERDADDR(p[0]) & 0x3fff,
9300 		    wr[0] - base[i], G_QUESOPCNT(p[3]), G_QUEEOPCNT(p[3]),
9301 		    G_QUEREMFLITS(p[2]) * 16);
9302 
9303 	rc = sbuf_finish(sb);
9304 	sbuf_delete(sb);
9305 
9306 	return (rc);
9307 }
9308 
9309 static int
9310 sysctl_cpl_stats(SYSCTL_HANDLER_ARGS)
9311 {
9312 	struct adapter *sc = arg1;
9313 	struct sbuf *sb;
9314 	int rc;
9315 	struct tp_cpl_stats stats;
9316 
9317 	rc = sysctl_wire_old_buffer(req, 0);
9318 	if (rc != 0)
9319 		return (rc);
9320 
9321 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9322 	if (sb == NULL)
9323 		return (ENOMEM);
9324 
9325 	mtx_lock(&sc->reg_lock);
9326 	if (hw_off_limits(sc))
9327 		rc = ENXIO;
9328 	else
9329 		t4_tp_get_cpl_stats(sc, &stats, 0);
9330 	mtx_unlock(&sc->reg_lock);
9331 	if (rc)
9332 		goto done;
9333 
9334 	if (sc->chip_params->nchan > 2) {
9335 		sbuf_printf(sb, "                 channel 0  channel 1"
9336 		    "  channel 2  channel 3");
9337 		sbuf_printf(sb, "\nCPL requests:   %10u %10u %10u %10u",
9338 		    stats.req[0], stats.req[1], stats.req[2], stats.req[3]);
9339 		sbuf_printf(sb, "\nCPL responses:  %10u %10u %10u %10u",
9340 		    stats.rsp[0], stats.rsp[1], stats.rsp[2], stats.rsp[3]);
9341 	} else {
9342 		sbuf_printf(sb, "                 channel 0  channel 1");
9343 		sbuf_printf(sb, "\nCPL requests:   %10u %10u",
9344 		    stats.req[0], stats.req[1]);
9345 		sbuf_printf(sb, "\nCPL responses:  %10u %10u",
9346 		    stats.rsp[0], stats.rsp[1]);
9347 	}
9348 
9349 	rc = sbuf_finish(sb);
9350 done:
9351 	sbuf_delete(sb);
9352 	return (rc);
9353 }
9354 
9355 static int
9356 sysctl_ddp_stats(SYSCTL_HANDLER_ARGS)
9357 {
9358 	struct adapter *sc = arg1;
9359 	struct sbuf *sb;
9360 	int rc;
9361 	struct tp_usm_stats stats;
9362 
9363 	rc = sysctl_wire_old_buffer(req, 0);
9364 	if (rc != 0)
9365 		return(rc);
9366 
9367 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9368 	if (sb == NULL)
9369 		return (ENOMEM);
9370 
9371 	mtx_lock(&sc->reg_lock);
9372 	if (hw_off_limits(sc))
9373 		rc = ENXIO;
9374 	else
9375 		t4_get_usm_stats(sc, &stats, 1);
9376 	mtx_unlock(&sc->reg_lock);
9377 	if (rc == 0) {
9378 		sbuf_printf(sb, "Frames: %u\n", stats.frames);
9379 		sbuf_printf(sb, "Octets: %ju\n", stats.octets);
9380 		sbuf_printf(sb, "Drops:  %u", stats.drops);
9381 		rc = sbuf_finish(sb);
9382 	}
9383 	sbuf_delete(sb);
9384 
9385 	return (rc);
9386 }
9387 
9388 static int
9389 sysctl_tid_stats(SYSCTL_HANDLER_ARGS)
9390 {
9391 	struct adapter *sc = arg1;
9392 	struct sbuf *sb;
9393 	int rc;
9394 	struct tp_tid_stats stats;
9395 
9396 	rc = sysctl_wire_old_buffer(req, 0);
9397 	if (rc != 0)
9398 		return(rc);
9399 
9400 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9401 	if (sb == NULL)
9402 		return (ENOMEM);
9403 
9404 	mtx_lock(&sc->reg_lock);
9405 	if (hw_off_limits(sc))
9406 		rc = ENXIO;
9407 	else
9408 		t4_tp_get_tid_stats(sc, &stats, 1);
9409 	mtx_unlock(&sc->reg_lock);
9410 	if (rc == 0) {
9411 		sbuf_printf(sb, "Delete:     %u\n", stats.del);
9412 		sbuf_printf(sb, "Invalidate: %u\n", stats.inv);
9413 		sbuf_printf(sb, "Active:     %u\n", stats.act);
9414 		sbuf_printf(sb, "Passive:    %u", stats.pas);
9415 		rc = sbuf_finish(sb);
9416 	}
9417 	sbuf_delete(sb);
9418 
9419 	return (rc);
9420 }
9421 
9422 static const char * const devlog_level_strings[] = {
9423 	[FW_DEVLOG_LEVEL_EMERG]		= "EMERG",
9424 	[FW_DEVLOG_LEVEL_CRIT]		= "CRIT",
9425 	[FW_DEVLOG_LEVEL_ERR]		= "ERR",
9426 	[FW_DEVLOG_LEVEL_NOTICE]	= "NOTICE",
9427 	[FW_DEVLOG_LEVEL_INFO]		= "INFO",
9428 	[FW_DEVLOG_LEVEL_DEBUG]		= "DEBUG"
9429 };
9430 
9431 static const char * const devlog_facility_strings[] = {
9432 	[FW_DEVLOG_FACILITY_CORE]	= "CORE",
9433 	[FW_DEVLOG_FACILITY_CF]		= "CF",
9434 	[FW_DEVLOG_FACILITY_SCHED]	= "SCHED",
9435 	[FW_DEVLOG_FACILITY_TIMER]	= "TIMER",
9436 	[FW_DEVLOG_FACILITY_RES]	= "RES",
9437 	[FW_DEVLOG_FACILITY_HW]		= "HW",
9438 	[FW_DEVLOG_FACILITY_FLR]	= "FLR",
9439 	[FW_DEVLOG_FACILITY_DMAQ]	= "DMAQ",
9440 	[FW_DEVLOG_FACILITY_PHY]	= "PHY",
9441 	[FW_DEVLOG_FACILITY_MAC]	= "MAC",
9442 	[FW_DEVLOG_FACILITY_PORT]	= "PORT",
9443 	[FW_DEVLOG_FACILITY_VI]		= "VI",
9444 	[FW_DEVLOG_FACILITY_FILTER]	= "FILTER",
9445 	[FW_DEVLOG_FACILITY_ACL]	= "ACL",
9446 	[FW_DEVLOG_FACILITY_TM]		= "TM",
9447 	[FW_DEVLOG_FACILITY_QFC]	= "QFC",
9448 	[FW_DEVLOG_FACILITY_DCB]	= "DCB",
9449 	[FW_DEVLOG_FACILITY_ETH]	= "ETH",
9450 	[FW_DEVLOG_FACILITY_OFLD]	= "OFLD",
9451 	[FW_DEVLOG_FACILITY_RI]		= "RI",
9452 	[FW_DEVLOG_FACILITY_ISCSI]	= "ISCSI",
9453 	[FW_DEVLOG_FACILITY_FCOE]	= "FCOE",
9454 	[FW_DEVLOG_FACILITY_FOISCSI]	= "FOISCSI",
9455 	[FW_DEVLOG_FACILITY_FOFCOE]	= "FOFCOE",
9456 	[FW_DEVLOG_FACILITY_CHNET]	= "CHNET",
9457 };
9458 
9459 static int
9460 sbuf_devlog(struct adapter *sc, struct sbuf *sb, int flags)
9461 {
9462 	int i, j, rc, nentries, first = 0;
9463 	struct devlog_params *dparams = &sc->params.devlog;
9464 	struct fw_devlog_e *buf, *e;
9465 	uint64_t ftstamp = UINT64_MAX;
9466 
9467 	if (dparams->addr == 0)
9468 		return (ENXIO);
9469 
9470 	MPASS(flags == M_WAITOK || flags == M_NOWAIT);
9471 	buf = malloc(dparams->size, M_CXGBE, M_ZERO | flags);
9472 	if (buf == NULL)
9473 		return (ENOMEM);
9474 
9475 	mtx_lock(&sc->reg_lock);
9476 	if (hw_off_limits(sc))
9477 		rc = ENXIO;
9478 	else
9479 		rc = read_via_memwin(sc, 1, dparams->addr, (void *)buf,
9480 		    dparams->size);
9481 	mtx_unlock(&sc->reg_lock);
9482 	if (rc != 0)
9483 		goto done;
9484 
9485 	nentries = dparams->size / sizeof(struct fw_devlog_e);
9486 	for (i = 0; i < nentries; i++) {
9487 		e = &buf[i];
9488 
9489 		if (e->timestamp == 0)
9490 			break;	/* end */
9491 
9492 		e->timestamp = be64toh(e->timestamp);
9493 		e->seqno = be32toh(e->seqno);
9494 		for (j = 0; j < 8; j++)
9495 			e->params[j] = be32toh(e->params[j]);
9496 
9497 		if (e->timestamp < ftstamp) {
9498 			ftstamp = e->timestamp;
9499 			first = i;
9500 		}
9501 	}
9502 
9503 	if (buf[first].timestamp == 0)
9504 		goto done;	/* nothing in the log */
9505 
9506 	sbuf_printf(sb, "%10s  %15s  %8s  %8s  %s\n",
9507 	    "Seq#", "Tstamp", "Level", "Facility", "Message");
9508 
9509 	i = first;
9510 	do {
9511 		e = &buf[i];
9512 		if (e->timestamp == 0)
9513 			break;	/* end */
9514 
9515 		sbuf_printf(sb, "%10d  %15ju  %8s  %8s  ",
9516 		    e->seqno, e->timestamp,
9517 		    (e->level < nitems(devlog_level_strings) ?
9518 			devlog_level_strings[e->level] : "UNKNOWN"),
9519 		    (e->facility < nitems(devlog_facility_strings) ?
9520 			devlog_facility_strings[e->facility] : "UNKNOWN"));
9521 		sbuf_printf(sb, e->fmt, e->params[0], e->params[1],
9522 		    e->params[2], e->params[3], e->params[4],
9523 		    e->params[5], e->params[6], e->params[7]);
9524 
9525 		if (++i == nentries)
9526 			i = 0;
9527 	} while (i != first);
9528 done:
9529 	free(buf, M_CXGBE);
9530 	return (rc);
9531 }
9532 
9533 static int
9534 sysctl_devlog(SYSCTL_HANDLER_ARGS)
9535 {
9536 	struct adapter *sc = arg1;
9537 	int rc;
9538 	struct sbuf *sb;
9539 
9540 	rc = sysctl_wire_old_buffer(req, 0);
9541 	if (rc != 0)
9542 		return (rc);
9543 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9544 	if (sb == NULL)
9545 		return (ENOMEM);
9546 
9547 	rc = sbuf_devlog(sc, sb, M_WAITOK);
9548 	if (rc == 0)
9549 		rc = sbuf_finish(sb);
9550 	sbuf_delete(sb);
9551 	return (rc);
9552 }
9553 
9554 static void
9555 dump_devlog(struct adapter *sc)
9556 {
9557 	int rc;
9558 	struct sbuf sb;
9559 
9560 	if (sbuf_new(&sb, NULL, 4096, SBUF_AUTOEXTEND) != &sb) {
9561 		log(LOG_DEBUG, "%s: failed to generate devlog dump.\n",
9562 		    device_get_nameunit(sc->dev));
9563 		return;
9564 	}
9565 	rc = sbuf_devlog(sc, &sb, M_WAITOK);
9566 	if (rc == 0) {
9567 		rc = sbuf_finish(&sb);
9568 		if (rc == 0) {
9569 			log(LOG_DEBUG, "%s: device log follows.\n%s",
9570 			    device_get_nameunit(sc->dev), sbuf_data(&sb));
9571 		}
9572 	}
9573 	sbuf_delete(&sb);
9574 }
9575 
9576 static int
9577 sysctl_fcoe_stats(SYSCTL_HANDLER_ARGS)
9578 {
9579 	struct adapter *sc = arg1;
9580 	struct sbuf *sb;
9581 	int rc;
9582 	struct tp_fcoe_stats stats[MAX_NCHAN];
9583 	int i, nchan = sc->chip_params->nchan;
9584 
9585 	rc = sysctl_wire_old_buffer(req, 0);
9586 	if (rc != 0)
9587 		return (rc);
9588 
9589 	mtx_lock(&sc->reg_lock);
9590 	if (hw_off_limits(sc))
9591 		rc = ENXIO;
9592 	else {
9593 		for (i = 0; i < nchan; i++)
9594 			t4_get_fcoe_stats(sc, i, &stats[i], 1);
9595 	}
9596 	mtx_unlock(&sc->reg_lock);
9597 	if (rc != 0)
9598 		return (rc);
9599 
9600 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
9601 	if (sb == NULL)
9602 		return (ENOMEM);
9603 
9604 	if (nchan > 2) {
9605 		sbuf_printf(sb, "                   channel 0        channel 1"
9606 		    "        channel 2        channel 3");
9607 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju %16ju %16ju",
9608 		    stats[0].octets_ddp, stats[1].octets_ddp,
9609 		    stats[2].octets_ddp, stats[3].octets_ddp);
9610 		sbuf_printf(sb, "\nframesDDP:  %16u %16u %16u %16u",
9611 		    stats[0].frames_ddp, stats[1].frames_ddp,
9612 		    stats[2].frames_ddp, stats[3].frames_ddp);
9613 		sbuf_printf(sb, "\nframesDrop: %16u %16u %16u %16u",
9614 		    stats[0].frames_drop, stats[1].frames_drop,
9615 		    stats[2].frames_drop, stats[3].frames_drop);
9616 	} else {
9617 		sbuf_printf(sb, "                   channel 0        channel 1");
9618 		sbuf_printf(sb, "\noctetsDDP:  %16ju %16ju",
9619 		    stats[0].octets_ddp, stats[1].octets_ddp);
9620 		sbuf_printf(sb, "\nframesDDP:  %16u %16u",
9621 		    stats[0].frames_ddp, stats[1].frames_ddp);
9622 		sbuf_printf(sb, "\nframesDrop: %16u %16u",
9623 		    stats[0].frames_drop, stats[1].frames_drop);
9624 	}
9625 
9626 	rc = sbuf_finish(sb);
9627 	sbuf_delete(sb);
9628 
9629 	return (rc);
9630 }
9631 
9632 static int
9633 sysctl_hw_sched(SYSCTL_HANDLER_ARGS)
9634 {
9635 	struct adapter *sc = arg1;
9636 	struct sbuf *sb;
9637 	int rc, i;
9638 	unsigned int map, kbps, ipg, mode;
9639 	unsigned int pace_tab[NTX_SCHED];
9640 
9641 	rc = sysctl_wire_old_buffer(req, 0);
9642 	if (rc != 0)
9643 		return (rc);
9644 
9645 	sb = sbuf_new_for_sysctl(NULL, NULL, 512, req);
9646 	if (sb == NULL)
9647 		return (ENOMEM);
9648 
9649 	mtx_lock(&sc->reg_lock);
9650 	if (hw_off_limits(sc)) {
9651 		rc = ENXIO;
9652 		goto done;
9653 	}
9654 
9655 	map = t4_read_reg(sc, A_TP_TX_MOD_QUEUE_REQ_MAP);
9656 	mode = G_TIMERMODE(t4_read_reg(sc, A_TP_MOD_CONFIG));
9657 	t4_read_pace_tbl(sc, pace_tab);
9658 
9659 	sbuf_printf(sb, "Scheduler  Mode   Channel  Rate (Kbps)   "
9660 	    "Class IPG (0.1 ns)   Flow IPG (us)");
9661 
9662 	for (i = 0; i < NTX_SCHED; ++i, map >>= 2) {
9663 		t4_get_tx_sched(sc, i, &kbps, &ipg, 1);
9664 		sbuf_printf(sb, "\n    %u      %-5s     %u     ", i,
9665 		    (mode & (1 << i)) ? "flow" : "class", map & 3);
9666 		if (kbps)
9667 			sbuf_printf(sb, "%9u     ", kbps);
9668 		else
9669 			sbuf_printf(sb, " disabled     ");
9670 
9671 		if (ipg)
9672 			sbuf_printf(sb, "%13u        ", ipg);
9673 		else
9674 			sbuf_printf(sb, "     disabled        ");
9675 
9676 		if (pace_tab[i])
9677 			sbuf_printf(sb, "%10u", pace_tab[i]);
9678 		else
9679 			sbuf_printf(sb, "  disabled");
9680 	}
9681 	rc = sbuf_finish(sb);
9682 done:
9683 	mtx_unlock(&sc->reg_lock);
9684 	sbuf_delete(sb);
9685 	return (rc);
9686 }
9687 
9688 static int
9689 sysctl_lb_stats(SYSCTL_HANDLER_ARGS)
9690 {
9691 	struct adapter *sc = arg1;
9692 	struct sbuf *sb;
9693 	int rc, i, j;
9694 	uint64_t *p0, *p1;
9695 	struct lb_port_stats s[2];
9696 	static const char *stat_name[] = {
9697 		"OctetsOK:", "FramesOK:", "BcastFrames:", "McastFrames:",
9698 		"UcastFrames:", "ErrorFrames:", "Frames64:", "Frames65To127:",
9699 		"Frames128To255:", "Frames256To511:", "Frames512To1023:",
9700 		"Frames1024To1518:", "Frames1519ToMax:", "FramesDropped:",
9701 		"BG0FramesDropped:", "BG1FramesDropped:", "BG2FramesDropped:",
9702 		"BG3FramesDropped:", "BG0FramesTrunc:", "BG1FramesTrunc:",
9703 		"BG2FramesTrunc:", "BG3FramesTrunc:"
9704 	};
9705 
9706 	rc = sysctl_wire_old_buffer(req, 0);
9707 	if (rc != 0)
9708 		return (rc);
9709 
9710 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9711 	if (sb == NULL)
9712 		return (ENOMEM);
9713 
9714 	memset(s, 0, sizeof(s));
9715 
9716 	for (i = 0; i < sc->chip_params->nchan; i += 2) {
9717 		mtx_lock(&sc->reg_lock);
9718 		if (hw_off_limits(sc))
9719 			rc = ENXIO;
9720 		else {
9721 			t4_get_lb_stats(sc, i, &s[0]);
9722 			t4_get_lb_stats(sc, i + 1, &s[1]);
9723 		}
9724 		mtx_unlock(&sc->reg_lock);
9725 		if (rc != 0)
9726 			break;
9727 
9728 		p0 = &s[0].octets;
9729 		p1 = &s[1].octets;
9730 		sbuf_printf(sb, "%s                       Loopback %u"
9731 		    "           Loopback %u", i == 0 ? "" : "\n", i, i + 1);
9732 
9733 		for (j = 0; j < nitems(stat_name); j++)
9734 			sbuf_printf(sb, "\n%-17s %20ju %20ju", stat_name[j],
9735 				   *p0++, *p1++);
9736 	}
9737 
9738 	rc = sbuf_finish(sb);
9739 	sbuf_delete(sb);
9740 
9741 	return (rc);
9742 }
9743 
9744 static int
9745 sysctl_linkdnrc(SYSCTL_HANDLER_ARGS)
9746 {
9747 	int rc = 0;
9748 	struct port_info *pi = arg1;
9749 	struct link_config *lc = &pi->link_cfg;
9750 	struct sbuf *sb;
9751 
9752 	rc = sysctl_wire_old_buffer(req, 0);
9753 	if (rc != 0)
9754 		return(rc);
9755 	sb = sbuf_new_for_sysctl(NULL, NULL, 64, req);
9756 	if (sb == NULL)
9757 		return (ENOMEM);
9758 
9759 	if (lc->link_ok || lc->link_down_rc == 255)
9760 		sbuf_printf(sb, "n/a");
9761 	else
9762 		sbuf_printf(sb, "%s", t4_link_down_rc_str(lc->link_down_rc));
9763 
9764 	rc = sbuf_finish(sb);
9765 	sbuf_delete(sb);
9766 
9767 	return (rc);
9768 }
9769 
9770 struct mem_desc {
9771 	u_int base;
9772 	u_int limit;
9773 	u_int idx;
9774 };
9775 
9776 static int
9777 mem_desc_cmp(const void *a, const void *b)
9778 {
9779 	const u_int v1 = ((const struct mem_desc *)a)->base;
9780 	const u_int v2 = ((const struct mem_desc *)b)->base;
9781 
9782 	if (v1 < v2)
9783 		return (-1);
9784 	else if (v1 > v2)
9785 		return (1);
9786 
9787 	return (0);
9788 }
9789 
9790 static void
9791 mem_region_show(struct sbuf *sb, const char *name, unsigned int from,
9792     unsigned int to)
9793 {
9794 	unsigned int size;
9795 
9796 	if (from == to)
9797 		return;
9798 
9799 	size = to - from + 1;
9800 	if (size == 0)
9801 		return;
9802 
9803 	/* XXX: need humanize_number(3) in libkern for a more readable 'size' */
9804 	sbuf_printf(sb, "%-15s %#x-%#x [%u]\n", name, from, to, size);
9805 }
9806 
9807 static int
9808 sysctl_meminfo(SYSCTL_HANDLER_ARGS)
9809 {
9810 	struct adapter *sc = arg1;
9811 	struct sbuf *sb;
9812 	int rc, i, n;
9813 	uint32_t lo, hi, used, free, alloc;
9814 	static const char *memory[] = {
9815 		"EDC0:", "EDC1:", "MC:", "MC0:", "MC1:", "HMA:"
9816 	};
9817 	static const char *region[] = {
9818 		"DBQ contexts:", "IMSG contexts:", "FLM cache:", "TCBs:",
9819 		"Pstructs:", "Timers:", "Rx FL:", "Tx FL:", "Pstruct FL:",
9820 		"Tx payload:", "Rx payload:", "LE hash:", "iSCSI region:",
9821 		"TDDP region:", "TPT region:", "STAG region:", "RQ region:",
9822 		"RQUDP region:", "PBL region:", "TXPBL region:",
9823 		"TLSKey region:", "DBVFIFO region:", "ULPRX state:",
9824 		"ULPTX state:", "On-chip queues:",
9825 	};
9826 	struct mem_desc avail[4];
9827 	struct mem_desc mem[nitems(region) + 3];	/* up to 3 holes */
9828 	struct mem_desc *md = mem;
9829 
9830 	rc = sysctl_wire_old_buffer(req, 0);
9831 	if (rc != 0)
9832 		return (rc);
9833 
9834 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
9835 	if (sb == NULL)
9836 		return (ENOMEM);
9837 
9838 	for (i = 0; i < nitems(mem); i++) {
9839 		mem[i].limit = 0;
9840 		mem[i].idx = i;
9841 	}
9842 
9843 	mtx_lock(&sc->reg_lock);
9844 	if (hw_off_limits(sc)) {
9845 		rc = ENXIO;
9846 		goto done;
9847 	}
9848 
9849 	/* Find and sort the populated memory ranges */
9850 	i = 0;
9851 	lo = t4_read_reg(sc, A_MA_TARGET_MEM_ENABLE);
9852 	if (lo & F_EDRAM0_ENABLE) {
9853 		hi = t4_read_reg(sc, A_MA_EDRAM0_BAR);
9854 		avail[i].base = G_EDRAM0_BASE(hi) << 20;
9855 		avail[i].limit = avail[i].base + (G_EDRAM0_SIZE(hi) << 20);
9856 		avail[i].idx = 0;
9857 		i++;
9858 	}
9859 	if (lo & F_EDRAM1_ENABLE) {
9860 		hi = t4_read_reg(sc, A_MA_EDRAM1_BAR);
9861 		avail[i].base = G_EDRAM1_BASE(hi) << 20;
9862 		avail[i].limit = avail[i].base + (G_EDRAM1_SIZE(hi) << 20);
9863 		avail[i].idx = 1;
9864 		i++;
9865 	}
9866 	if (lo & F_EXT_MEM_ENABLE) {
9867 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY_BAR);
9868 		avail[i].base = G_EXT_MEM_BASE(hi) << 20;
9869 		avail[i].limit = avail[i].base + (G_EXT_MEM_SIZE(hi) << 20);
9870 		avail[i].idx = is_t5(sc) ? 3 : 2;	/* Call it MC0 for T5 */
9871 		i++;
9872 	}
9873 	if (is_t5(sc) && lo & F_EXT_MEM1_ENABLE) {
9874 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9875 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9876 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9877 		avail[i].idx = 4;
9878 		i++;
9879 	}
9880 	if (is_t6(sc) && lo & F_HMA_MUX) {
9881 		hi = t4_read_reg(sc, A_MA_EXT_MEMORY1_BAR);
9882 		avail[i].base = G_EXT_MEM1_BASE(hi) << 20;
9883 		avail[i].limit = avail[i].base + (G_EXT_MEM1_SIZE(hi) << 20);
9884 		avail[i].idx = 5;
9885 		i++;
9886 	}
9887 	MPASS(i <= nitems(avail));
9888 	if (!i)                                    /* no memory available */
9889 		goto done;
9890 	qsort(avail, i, sizeof(struct mem_desc), mem_desc_cmp);
9891 
9892 	(md++)->base = t4_read_reg(sc, A_SGE_DBQ_CTXT_BADDR);
9893 	(md++)->base = t4_read_reg(sc, A_SGE_IMSG_CTXT_BADDR);
9894 	(md++)->base = t4_read_reg(sc, A_SGE_FLM_CACHE_BADDR);
9895 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
9896 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_BASE);
9897 	(md++)->base = t4_read_reg(sc, A_TP_CMM_TIMER_BASE);
9898 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_RX_FLST_BASE);
9899 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_TX_FLST_BASE);
9900 	(md++)->base = t4_read_reg(sc, A_TP_CMM_MM_PS_FLST_BASE);
9901 
9902 	/* the next few have explicit upper bounds */
9903 	md->base = t4_read_reg(sc, A_TP_PMM_TX_BASE);
9904 	md->limit = md->base - 1 +
9905 		    t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE) *
9906 		    G_PMTXMAXPAGE(t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE));
9907 	md++;
9908 
9909 	md->base = t4_read_reg(sc, A_TP_PMM_RX_BASE);
9910 	md->limit = md->base - 1 +
9911 		    t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) *
9912 		    G_PMRXMAXPAGE(t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE));
9913 	md++;
9914 
9915 	if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
9916 		if (chip_id(sc) <= CHELSIO_T5)
9917 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TID_BASE);
9918 		else
9919 			md->base = t4_read_reg(sc, A_LE_DB_HASH_TBL_BASE_ADDR);
9920 		md->limit = 0;
9921 	} else {
9922 		md->base = 0;
9923 		md->idx = nitems(region);  /* hide it */
9924 	}
9925 	md++;
9926 
9927 #define ulp_region(reg) \
9928 	md->base = t4_read_reg(sc, A_ULP_ ## reg ## _LLIMIT);\
9929 	(md++)->limit = t4_read_reg(sc, A_ULP_ ## reg ## _ULIMIT)
9930 
9931 	ulp_region(RX_ISCSI);
9932 	ulp_region(RX_TDDP);
9933 	ulp_region(TX_TPT);
9934 	ulp_region(RX_STAG);
9935 	ulp_region(RX_RQ);
9936 	ulp_region(RX_RQUDP);
9937 	ulp_region(RX_PBL);
9938 	ulp_region(TX_PBL);
9939 	if (sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS) {
9940 		ulp_region(RX_TLS_KEY);
9941 	}
9942 #undef ulp_region
9943 
9944 	md->base = 0;
9945 	if (is_t4(sc))
9946 		md->idx = nitems(region);
9947 	else {
9948 		uint32_t size = 0;
9949 		uint32_t sge_ctrl = t4_read_reg(sc, A_SGE_CONTROL2);
9950 		uint32_t fifo_size = t4_read_reg(sc, A_SGE_DBVFIFO_SIZE);
9951 
9952 		if (is_t5(sc)) {
9953 			if (sge_ctrl & F_VFIFO_ENABLE)
9954 				size = fifo_size << 2;
9955 		} else
9956 			size = G_T6_DBVFIFO_SIZE(fifo_size) << 6;
9957 
9958 		if (size) {
9959 			md->base = t4_read_reg(sc, A_SGE_DBVFIFO_BADDR);
9960 			md->limit = md->base + size - 1;
9961 		} else
9962 			md->idx = nitems(region);
9963 	}
9964 	md++;
9965 
9966 	md->base = t4_read_reg(sc, A_ULP_RX_CTX_BASE);
9967 	md->limit = 0;
9968 	md++;
9969 	md->base = t4_read_reg(sc, A_ULP_TX_ERR_TABLE_BASE);
9970 	md->limit = 0;
9971 	md++;
9972 
9973 	md->base = sc->vres.ocq.start;
9974 	if (sc->vres.ocq.size)
9975 		md->limit = md->base + sc->vres.ocq.size - 1;
9976 	else
9977 		md->idx = nitems(region);  /* hide it */
9978 	md++;
9979 
9980 	/* add any address-space holes, there can be up to 3 */
9981 	for (n = 0; n < i - 1; n++)
9982 		if (avail[n].limit < avail[n + 1].base)
9983 			(md++)->base = avail[n].limit;
9984 	if (avail[n].limit)
9985 		(md++)->base = avail[n].limit;
9986 
9987 	n = md - mem;
9988 	MPASS(n <= nitems(mem));
9989 	qsort(mem, n, sizeof(struct mem_desc), mem_desc_cmp);
9990 
9991 	for (lo = 0; lo < i; lo++)
9992 		mem_region_show(sb, memory[avail[lo].idx], avail[lo].base,
9993 				avail[lo].limit - 1);
9994 
9995 	sbuf_printf(sb, "\n");
9996 	for (i = 0; i < n; i++) {
9997 		if (mem[i].idx >= nitems(region))
9998 			continue;                        /* skip holes */
9999 		if (!mem[i].limit)
10000 			mem[i].limit = i < n - 1 ? mem[i + 1].base - 1 : ~0;
10001 		mem_region_show(sb, region[mem[i].idx], mem[i].base,
10002 				mem[i].limit);
10003 	}
10004 
10005 	sbuf_printf(sb, "\n");
10006 	lo = t4_read_reg(sc, A_CIM_SDRAM_BASE_ADDR);
10007 	hi = t4_read_reg(sc, A_CIM_SDRAM_ADDR_SIZE) + lo - 1;
10008 	mem_region_show(sb, "uP RAM:", lo, hi);
10009 
10010 	lo = t4_read_reg(sc, A_CIM_EXTMEM2_BASE_ADDR);
10011 	hi = t4_read_reg(sc, A_CIM_EXTMEM2_ADDR_SIZE) + lo - 1;
10012 	mem_region_show(sb, "uP Extmem2:", lo, hi);
10013 
10014 	lo = t4_read_reg(sc, A_TP_PMM_RX_MAX_PAGE);
10015 	for (i = 0, free = 0; i < 2; i++)
10016 		free += G_FREERXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_RX_CNT));
10017 	sbuf_printf(sb, "\n%u Rx pages (%u free) of size %uKiB for %u channels\n",
10018 		   G_PMRXMAXPAGE(lo), free,
10019 		   t4_read_reg(sc, A_TP_PMM_RX_PAGE_SIZE) >> 10,
10020 		   (lo & F_PMRXNUMCHN) ? 2 : 1);
10021 
10022 	lo = t4_read_reg(sc, A_TP_PMM_TX_MAX_PAGE);
10023 	hi = t4_read_reg(sc, A_TP_PMM_TX_PAGE_SIZE);
10024 	for (i = 0, free = 0; i < 4; i++)
10025 		free += G_FREETXPAGECOUNT(t4_read_reg(sc, A_TP_FLM_FREE_TX_CNT));
10026 	sbuf_printf(sb, "%u Tx pages (%u free) of size %u%ciB for %u channels\n",
10027 		   G_PMTXMAXPAGE(lo), free,
10028 		   hi >= (1 << 20) ? (hi >> 20) : (hi >> 10),
10029 		   hi >= (1 << 20) ? 'M' : 'K', 1 << G_PMTXNUMCHN(lo));
10030 	sbuf_printf(sb, "%u p-structs (%u free)\n",
10031 		   t4_read_reg(sc, A_TP_CMM_MM_MAX_PSTRUCT),
10032 		   G_FREEPSTRUCTCOUNT(t4_read_reg(sc, A_TP_FLM_FREE_PS_CNT)));
10033 
10034 	for (i = 0; i < 4; i++) {
10035 		if (chip_id(sc) > CHELSIO_T5)
10036 			lo = t4_read_reg(sc, A_MPS_RX_MAC_BG_PG_CNT0 + i * 4);
10037 		else
10038 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV0 + i * 4);
10039 		if (is_t5(sc)) {
10040 			used = G_T5_USED(lo);
10041 			alloc = G_T5_ALLOC(lo);
10042 		} else {
10043 			used = G_USED(lo);
10044 			alloc = G_ALLOC(lo);
10045 		}
10046 		/* For T6 these are MAC buffer groups */
10047 		sbuf_printf(sb, "\nPort %d using %u pages out of %u allocated",
10048 		    i, used, alloc);
10049 	}
10050 	for (i = 0; i < sc->chip_params->nchan; i++) {
10051 		if (chip_id(sc) > CHELSIO_T5)
10052 			lo = t4_read_reg(sc, A_MPS_RX_LPBK_BG_PG_CNT0 + i * 4);
10053 		else
10054 			lo = t4_read_reg(sc, A_MPS_RX_PG_RSV4 + i * 4);
10055 		if (is_t5(sc)) {
10056 			used = G_T5_USED(lo);
10057 			alloc = G_T5_ALLOC(lo);
10058 		} else {
10059 			used = G_USED(lo);
10060 			alloc = G_ALLOC(lo);
10061 		}
10062 		/* For T6 these are MAC buffer groups */
10063 		sbuf_printf(sb,
10064 		    "\nLoopback %d using %u pages out of %u allocated",
10065 		    i, used, alloc);
10066 	}
10067 done:
10068 	mtx_unlock(&sc->reg_lock);
10069 	if (rc == 0)
10070 		rc = sbuf_finish(sb);
10071 	sbuf_delete(sb);
10072 	return (rc);
10073 }
10074 
10075 static inline void
10076 tcamxy2valmask(uint64_t x, uint64_t y, uint8_t *addr, uint64_t *mask)
10077 {
10078 	*mask = x | y;
10079 	y = htobe64(y);
10080 	memcpy(addr, (char *)&y + 2, ETHER_ADDR_LEN);
10081 }
10082 
10083 static int
10084 sysctl_mps_tcam(SYSCTL_HANDLER_ARGS)
10085 {
10086 	struct adapter *sc = arg1;
10087 	struct sbuf *sb;
10088 	int rc, i;
10089 
10090 	MPASS(chip_id(sc) <= CHELSIO_T5);
10091 
10092 	rc = sysctl_wire_old_buffer(req, 0);
10093 	if (rc != 0)
10094 		return (rc);
10095 
10096 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10097 	if (sb == NULL)
10098 		return (ENOMEM);
10099 
10100 	sbuf_printf(sb,
10101 	    "Idx  Ethernet address     Mask     Vld Ports PF"
10102 	    "  VF              Replication             P0 P1 P2 P3  ML");
10103 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10104 		uint64_t tcamx, tcamy, mask;
10105 		uint32_t cls_lo, cls_hi;
10106 		uint8_t addr[ETHER_ADDR_LEN];
10107 
10108 		mtx_lock(&sc->reg_lock);
10109 		if (hw_off_limits(sc))
10110 			rc = ENXIO;
10111 		else {
10112 			tcamy = t4_read_reg64(sc, MPS_CLS_TCAM_Y_L(i));
10113 			tcamx = t4_read_reg64(sc, MPS_CLS_TCAM_X_L(i));
10114 		}
10115 		mtx_unlock(&sc->reg_lock);
10116 		if (rc != 0)
10117 			break;
10118 		if (tcamx & tcamy)
10119 			continue;
10120 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10121 		mtx_lock(&sc->reg_lock);
10122 		if (hw_off_limits(sc))
10123 			rc = ENXIO;
10124 		else {
10125 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10126 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10127 		}
10128 		mtx_unlock(&sc->reg_lock);
10129 		if (rc != 0)
10130 			break;
10131 		sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x %012jx"
10132 			   "  %c   %#x%4u%4d", i, addr[0], addr[1], addr[2],
10133 			   addr[3], addr[4], addr[5], (uintmax_t)mask,
10134 			   (cls_lo & F_SRAM_VLD) ? 'Y' : 'N',
10135 			   G_PORTMAP(cls_hi), G_PF(cls_lo),
10136 			   (cls_lo & F_VF_VALID) ? G_VF(cls_lo) : -1);
10137 
10138 		if (cls_lo & F_REPLICATE) {
10139 			struct fw_ldst_cmd ldst_cmd;
10140 
10141 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10142 			ldst_cmd.op_to_addrspace =
10143 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10144 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10145 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10146 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10147 			ldst_cmd.u.mps.rplc.fid_idx =
10148 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10149 				V_FW_LDST_CMD_IDX(i));
10150 
10151 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10152 			    "t4mps");
10153 			if (rc)
10154 				break;
10155 			if (hw_off_limits(sc))
10156 				rc = ENXIO;
10157 			else
10158 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10159 				    sizeof(ldst_cmd), &ldst_cmd);
10160 			end_synchronized_op(sc, 0);
10161 			if (rc != 0)
10162 				break;
10163 			else {
10164 				sbuf_printf(sb, " %08x %08x %08x %08x",
10165 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10166 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10167 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10168 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10169 			}
10170 		} else
10171 			sbuf_printf(sb, "%36s", "");
10172 
10173 		sbuf_printf(sb, "%4u%3u%3u%3u %#3x", G_SRAM_PRIO0(cls_lo),
10174 		    G_SRAM_PRIO1(cls_lo), G_SRAM_PRIO2(cls_lo),
10175 		    G_SRAM_PRIO3(cls_lo), (cls_lo >> S_MULTILISTEN0) & 0xf);
10176 	}
10177 
10178 	if (rc)
10179 		(void) sbuf_finish(sb);
10180 	else
10181 		rc = sbuf_finish(sb);
10182 	sbuf_delete(sb);
10183 
10184 	return (rc);
10185 }
10186 
10187 static int
10188 sysctl_mps_tcam_t6(SYSCTL_HANDLER_ARGS)
10189 {
10190 	struct adapter *sc = arg1;
10191 	struct sbuf *sb;
10192 	int rc, i;
10193 
10194 	MPASS(chip_id(sc) > CHELSIO_T5);
10195 
10196 	rc = sysctl_wire_old_buffer(req, 0);
10197 	if (rc != 0)
10198 		return (rc);
10199 
10200 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
10201 	if (sb == NULL)
10202 		return (ENOMEM);
10203 
10204 	sbuf_printf(sb, "Idx  Ethernet address     Mask       VNI   Mask"
10205 	    "   IVLAN Vld DIP_Hit   Lookup  Port Vld Ports PF  VF"
10206 	    "                           Replication"
10207 	    "                                    P0 P1 P2 P3  ML\n");
10208 
10209 	for (i = 0; i < sc->chip_params->mps_tcam_size; i++) {
10210 		uint8_t dip_hit, vlan_vld, lookup_type, port_num;
10211 		uint16_t ivlan;
10212 		uint64_t tcamx, tcamy, val, mask;
10213 		uint32_t cls_lo, cls_hi, ctl, data2, vnix, vniy;
10214 		uint8_t addr[ETHER_ADDR_LEN];
10215 
10216 		ctl = V_CTLREQID(1) | V_CTLCMDTYPE(0) | V_CTLXYBITSEL(0);
10217 		if (i < 256)
10218 			ctl |= V_CTLTCAMINDEX(i) | V_CTLTCAMSEL(0);
10219 		else
10220 			ctl |= V_CTLTCAMINDEX(i - 256) | V_CTLTCAMSEL(1);
10221 		mtx_lock(&sc->reg_lock);
10222 		if (hw_off_limits(sc))
10223 			rc = ENXIO;
10224 		else {
10225 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10226 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10227 			tcamy = G_DMACH(val) << 32;
10228 			tcamy |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10229 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10230 		}
10231 		mtx_unlock(&sc->reg_lock);
10232 		if (rc != 0)
10233 			break;
10234 
10235 		lookup_type = G_DATALKPTYPE(data2);
10236 		port_num = G_DATAPORTNUM(data2);
10237 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10238 			/* Inner header VNI */
10239 			vniy = ((data2 & F_DATAVIDH2) << 23) |
10240 				       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10241 			dip_hit = data2 & F_DATADIPHIT;
10242 			vlan_vld = 0;
10243 		} else {
10244 			vniy = 0;
10245 			dip_hit = 0;
10246 			vlan_vld = data2 & F_DATAVIDH2;
10247 			ivlan = G_VIDL(val);
10248 		}
10249 
10250 		ctl |= V_CTLXYBITSEL(1);
10251 		mtx_lock(&sc->reg_lock);
10252 		if (hw_off_limits(sc))
10253 			rc = ENXIO;
10254 		else {
10255 			t4_write_reg(sc, A_MPS_CLS_TCAM_DATA2_CTL, ctl);
10256 			val = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA1_REQ_ID1);
10257 			tcamx = G_DMACH(val) << 32;
10258 			tcamx |= t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA0_REQ_ID1);
10259 			data2 = t4_read_reg(sc, A_MPS_CLS_TCAM_RDATA2_REQ_ID1);
10260 		}
10261 		mtx_unlock(&sc->reg_lock);
10262 		if (rc != 0)
10263 			break;
10264 
10265 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10266 			/* Inner header VNI mask */
10267 			vnix = ((data2 & F_DATAVIDH2) << 23) |
10268 			       (G_DATAVIDH1(data2) << 16) | G_VIDL(val);
10269 		} else
10270 			vnix = 0;
10271 
10272 		if (tcamx & tcamy)
10273 			continue;
10274 		tcamxy2valmask(tcamx, tcamy, addr, &mask);
10275 
10276 		mtx_lock(&sc->reg_lock);
10277 		if (hw_off_limits(sc))
10278 			rc = ENXIO;
10279 		else {
10280 			cls_lo = t4_read_reg(sc, MPS_CLS_SRAM_L(i));
10281 			cls_hi = t4_read_reg(sc, MPS_CLS_SRAM_H(i));
10282 		}
10283 		mtx_unlock(&sc->reg_lock);
10284 		if (rc != 0)
10285 			break;
10286 
10287 		if (lookup_type && lookup_type != M_DATALKPTYPE) {
10288 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10289 			    "%012jx %06x %06x    -    -   %3c"
10290 			    "        I  %4x   %3c   %#x%4u%4d", i, addr[0],
10291 			    addr[1], addr[2], addr[3], addr[4], addr[5],
10292 			    (uintmax_t)mask, vniy, vnix, dip_hit ? 'Y' : 'N',
10293 			    port_num, cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10294 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10295 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10296 		} else {
10297 			sbuf_printf(sb, "\n%3u %02x:%02x:%02x:%02x:%02x:%02x "
10298 			    "%012jx    -       -   ", i, addr[0], addr[1],
10299 			    addr[2], addr[3], addr[4], addr[5],
10300 			    (uintmax_t)mask);
10301 
10302 			if (vlan_vld)
10303 				sbuf_printf(sb, "%4u   Y     ", ivlan);
10304 			else
10305 				sbuf_printf(sb, "  -    N     ");
10306 
10307 			sbuf_printf(sb, "-      %3c  %4x   %3c   %#x%4u%4d",
10308 			    lookup_type ? 'I' : 'O', port_num,
10309 			    cls_lo & F_T6_SRAM_VLD ? 'Y' : 'N',
10310 			    G_PORTMAP(cls_hi), G_T6_PF(cls_lo),
10311 			    cls_lo & F_T6_VF_VALID ? G_T6_VF(cls_lo) : -1);
10312 		}
10313 
10314 
10315 		if (cls_lo & F_T6_REPLICATE) {
10316 			struct fw_ldst_cmd ldst_cmd;
10317 
10318 			memset(&ldst_cmd, 0, sizeof(ldst_cmd));
10319 			ldst_cmd.op_to_addrspace =
10320 			    htobe32(V_FW_CMD_OP(FW_LDST_CMD) |
10321 				F_FW_CMD_REQUEST | F_FW_CMD_READ |
10322 				V_FW_LDST_CMD_ADDRSPACE(FW_LDST_ADDRSPC_MPS));
10323 			ldst_cmd.cycles_to_len16 = htobe32(FW_LEN16(ldst_cmd));
10324 			ldst_cmd.u.mps.rplc.fid_idx =
10325 			    htobe16(V_FW_LDST_CMD_FID(FW_LDST_MPS_RPLC) |
10326 				V_FW_LDST_CMD_IDX(i));
10327 
10328 			rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK,
10329 			    "t6mps");
10330 			if (rc)
10331 				break;
10332 			if (hw_off_limits(sc))
10333 				rc = ENXIO;
10334 			else
10335 				rc = -t4_wr_mbox(sc, sc->mbox, &ldst_cmd,
10336 				    sizeof(ldst_cmd), &ldst_cmd);
10337 			end_synchronized_op(sc, 0);
10338 			if (rc != 0)
10339 				break;
10340 			else {
10341 				sbuf_printf(sb, " %08x %08x %08x %08x"
10342 				    " %08x %08x %08x %08x",
10343 				    be32toh(ldst_cmd.u.mps.rplc.rplc255_224),
10344 				    be32toh(ldst_cmd.u.mps.rplc.rplc223_192),
10345 				    be32toh(ldst_cmd.u.mps.rplc.rplc191_160),
10346 				    be32toh(ldst_cmd.u.mps.rplc.rplc159_128),
10347 				    be32toh(ldst_cmd.u.mps.rplc.rplc127_96),
10348 				    be32toh(ldst_cmd.u.mps.rplc.rplc95_64),
10349 				    be32toh(ldst_cmd.u.mps.rplc.rplc63_32),
10350 				    be32toh(ldst_cmd.u.mps.rplc.rplc31_0));
10351 			}
10352 		} else
10353 			sbuf_printf(sb, "%72s", "");
10354 
10355 		sbuf_printf(sb, "%4u%3u%3u%3u %#x",
10356 		    G_T6_SRAM_PRIO0(cls_lo), G_T6_SRAM_PRIO1(cls_lo),
10357 		    G_T6_SRAM_PRIO2(cls_lo), G_T6_SRAM_PRIO3(cls_lo),
10358 		    (cls_lo >> S_T6_MULTILISTEN0) & 0xf);
10359 	}
10360 
10361 	if (rc)
10362 		(void) sbuf_finish(sb);
10363 	else
10364 		rc = sbuf_finish(sb);
10365 	sbuf_delete(sb);
10366 
10367 	return (rc);
10368 }
10369 
10370 static int
10371 sysctl_path_mtus(SYSCTL_HANDLER_ARGS)
10372 {
10373 	struct adapter *sc = arg1;
10374 	struct sbuf *sb;
10375 	int rc;
10376 	uint16_t mtus[NMTUS];
10377 
10378 	rc = sysctl_wire_old_buffer(req, 0);
10379 	if (rc != 0)
10380 		return (rc);
10381 
10382 	mtx_lock(&sc->reg_lock);
10383 	if (hw_off_limits(sc))
10384 		rc = ENXIO;
10385 	else
10386 		t4_read_mtu_tbl(sc, mtus, NULL);
10387 	mtx_unlock(&sc->reg_lock);
10388 	if (rc != 0)
10389 		return (rc);
10390 
10391 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10392 	if (sb == NULL)
10393 		return (ENOMEM);
10394 
10395 	sbuf_printf(sb, "%u %u %u %u %u %u %u %u %u %u %u %u %u %u %u %u",
10396 	    mtus[0], mtus[1], mtus[2], mtus[3], mtus[4], mtus[5], mtus[6],
10397 	    mtus[7], mtus[8], mtus[9], mtus[10], mtus[11], mtus[12], mtus[13],
10398 	    mtus[14], mtus[15]);
10399 
10400 	rc = sbuf_finish(sb);
10401 	sbuf_delete(sb);
10402 
10403 	return (rc);
10404 }
10405 
10406 static int
10407 sysctl_pm_stats(SYSCTL_HANDLER_ARGS)
10408 {
10409 	struct adapter *sc = arg1;
10410 	struct sbuf *sb;
10411 	int rc, i;
10412 	uint32_t tx_cnt[MAX_PM_NSTATS], rx_cnt[MAX_PM_NSTATS];
10413 	uint64_t tx_cyc[MAX_PM_NSTATS], rx_cyc[MAX_PM_NSTATS];
10414 	static const char *tx_stats[MAX_PM_NSTATS] = {
10415 		"Read:", "Write bypass:", "Write mem:", "Bypass + mem:",
10416 		"Tx FIFO wait", NULL, "Tx latency"
10417 	};
10418 	static const char *rx_stats[MAX_PM_NSTATS] = {
10419 		"Read:", "Write bypass:", "Write mem:", "Flush:",
10420 		"Rx FIFO wait", NULL, "Rx latency"
10421 	};
10422 
10423 	rc = sysctl_wire_old_buffer(req, 0);
10424 	if (rc != 0)
10425 		return (rc);
10426 
10427 	mtx_lock(&sc->reg_lock);
10428 	if (hw_off_limits(sc))
10429 		rc = ENXIO;
10430 	else {
10431 		t4_pmtx_get_stats(sc, tx_cnt, tx_cyc);
10432 		t4_pmrx_get_stats(sc, rx_cnt, rx_cyc);
10433 	}
10434 	mtx_unlock(&sc->reg_lock);
10435 	if (rc != 0)
10436 		return (rc);
10437 
10438 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10439 	if (sb == NULL)
10440 		return (ENOMEM);
10441 
10442 	sbuf_printf(sb, "                Tx pcmds             Tx bytes");
10443 	for (i = 0; i < 4; i++) {
10444 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10445 		    tx_cyc[i]);
10446 	}
10447 
10448 	sbuf_printf(sb, "\n                Rx pcmds             Rx bytes");
10449 	for (i = 0; i < 4; i++) {
10450 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10451 		    rx_cyc[i]);
10452 	}
10453 
10454 	if (chip_id(sc) > CHELSIO_T5) {
10455 		sbuf_printf(sb,
10456 		    "\n              Total wait      Total occupancy");
10457 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10458 		    tx_cyc[i]);
10459 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10460 		    rx_cyc[i]);
10461 
10462 		i += 2;
10463 		MPASS(i < nitems(tx_stats));
10464 
10465 		sbuf_printf(sb,
10466 		    "\n                   Reads           Total wait");
10467 		sbuf_printf(sb, "\n%-13s %10u %20ju", tx_stats[i], tx_cnt[i],
10468 		    tx_cyc[i]);
10469 		sbuf_printf(sb, "\n%-13s %10u %20ju", rx_stats[i], rx_cnt[i],
10470 		    rx_cyc[i]);
10471 	}
10472 
10473 	rc = sbuf_finish(sb);
10474 	sbuf_delete(sb);
10475 
10476 	return (rc);
10477 }
10478 
10479 static int
10480 sysctl_rdma_stats(SYSCTL_HANDLER_ARGS)
10481 {
10482 	struct adapter *sc = arg1;
10483 	struct sbuf *sb;
10484 	int rc;
10485 	struct tp_rdma_stats stats;
10486 
10487 	rc = sysctl_wire_old_buffer(req, 0);
10488 	if (rc != 0)
10489 		return (rc);
10490 
10491 	mtx_lock(&sc->reg_lock);
10492 	if (hw_off_limits(sc))
10493 		rc = ENXIO;
10494 	else
10495 		t4_tp_get_rdma_stats(sc, &stats, 0);
10496 	mtx_unlock(&sc->reg_lock);
10497 	if (rc != 0)
10498 		return (rc);
10499 
10500 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10501 	if (sb == NULL)
10502 		return (ENOMEM);
10503 
10504 	sbuf_printf(sb, "NoRQEModDefferals: %u\n", stats.rqe_dfr_mod);
10505 	sbuf_printf(sb, "NoRQEPktDefferals: %u", stats.rqe_dfr_pkt);
10506 
10507 	rc = sbuf_finish(sb);
10508 	sbuf_delete(sb);
10509 
10510 	return (rc);
10511 }
10512 
10513 static int
10514 sysctl_tcp_stats(SYSCTL_HANDLER_ARGS)
10515 {
10516 	struct adapter *sc = arg1;
10517 	struct sbuf *sb;
10518 	int rc;
10519 	struct tp_tcp_stats v4, v6;
10520 
10521 	rc = sysctl_wire_old_buffer(req, 0);
10522 	if (rc != 0)
10523 		return (rc);
10524 
10525 	mtx_lock(&sc->reg_lock);
10526 	if (hw_off_limits(sc))
10527 		rc = ENXIO;
10528 	else
10529 		t4_tp_get_tcp_stats(sc, &v4, &v6, 0);
10530 	mtx_unlock(&sc->reg_lock);
10531 	if (rc != 0)
10532 		return (rc);
10533 
10534 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10535 	if (sb == NULL)
10536 		return (ENOMEM);
10537 
10538 	sbuf_printf(sb,
10539 	    "                                IP                 IPv6\n");
10540 	sbuf_printf(sb, "OutRsts:      %20u %20u\n",
10541 	    v4.tcp_out_rsts, v6.tcp_out_rsts);
10542 	sbuf_printf(sb, "InSegs:       %20ju %20ju\n",
10543 	    v4.tcp_in_segs, v6.tcp_in_segs);
10544 	sbuf_printf(sb, "OutSegs:      %20ju %20ju\n",
10545 	    v4.tcp_out_segs, v6.tcp_out_segs);
10546 	sbuf_printf(sb, "RetransSegs:  %20ju %20ju",
10547 	    v4.tcp_retrans_segs, v6.tcp_retrans_segs);
10548 
10549 	rc = sbuf_finish(sb);
10550 	sbuf_delete(sb);
10551 
10552 	return (rc);
10553 }
10554 
10555 static int
10556 sysctl_tids(SYSCTL_HANDLER_ARGS)
10557 {
10558 	struct adapter *sc = arg1;
10559 	struct sbuf *sb;
10560 	int rc;
10561 	uint32_t x, y;
10562 	struct tid_info *t = &sc->tids;
10563 
10564 	rc = sysctl_wire_old_buffer(req, 0);
10565 	if (rc != 0)
10566 		return (rc);
10567 
10568 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10569 	if (sb == NULL)
10570 		return (ENOMEM);
10571 
10572 	if (t->natids) {
10573 		sbuf_printf(sb, "ATID range: 0-%u, in use: %u\n", t->natids - 1,
10574 		    t->atids_in_use);
10575 	}
10576 
10577 	if (t->nhpftids) {
10578 		sbuf_printf(sb, "HPFTID range: %u-%u, in use: %u\n",
10579 		    t->hpftid_base, t->hpftid_end, t->hpftids_in_use);
10580 	}
10581 
10582 	if (t->ntids) {
10583 		bool hashen = false;
10584 
10585 		mtx_lock(&sc->reg_lock);
10586 		if (hw_off_limits(sc))
10587 			rc = ENXIO;
10588 		else if (t4_read_reg(sc, A_LE_DB_CONFIG) & F_HASHEN) {
10589 			hashen = true;
10590 			if (chip_id(sc) <= CHELSIO_T5) {
10591 				x = t4_read_reg(sc, A_LE_DB_SERVER_INDEX) / 4;
10592 				y = t4_read_reg(sc, A_LE_DB_TID_HASHBASE) / 4;
10593 			} else {
10594 				x = t4_read_reg(sc, A_LE_DB_SRVR_START_INDEX);
10595 				y = t4_read_reg(sc, A_T6_LE_DB_HASH_TID_BASE);
10596 			}
10597 		}
10598 		mtx_unlock(&sc->reg_lock);
10599 		if (rc != 0)
10600 			goto done;
10601 
10602 		sbuf_printf(sb, "TID range: ");
10603 		if (hashen) {
10604 			if (x)
10605 				sbuf_printf(sb, "%u-%u, ", t->tid_base, x - 1);
10606 			sbuf_printf(sb, "%u-%u", y, t->ntids - 1);
10607 		} else {
10608 			sbuf_printf(sb, "%u-%u", t->tid_base, t->tid_base +
10609 			    t->ntids - 1);
10610 		}
10611 		sbuf_printf(sb, ", in use: %u\n",
10612 		    atomic_load_acq_int(&t->tids_in_use));
10613 	}
10614 
10615 	if (t->nstids) {
10616 		sbuf_printf(sb, "STID range: %u-%u, in use: %u\n", t->stid_base,
10617 		    t->stid_base + t->nstids - 1, t->stids_in_use);
10618 	}
10619 
10620 	if (t->nftids) {
10621 		sbuf_printf(sb, "FTID range: %u-%u, in use: %u\n", t->ftid_base,
10622 		    t->ftid_end, t->ftids_in_use);
10623 	}
10624 
10625 	if (t->netids) {
10626 		sbuf_printf(sb, "ETID range: %u-%u, in use: %u\n", t->etid_base,
10627 		    t->etid_base + t->netids - 1, t->etids_in_use);
10628 	}
10629 
10630 	mtx_lock(&sc->reg_lock);
10631 	if (hw_off_limits(sc))
10632 		rc = ENXIO;
10633 	else {
10634 		x = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV4);
10635 		y = t4_read_reg(sc, A_LE_DB_ACT_CNT_IPV6);
10636 	}
10637 	mtx_unlock(&sc->reg_lock);
10638 	if (rc != 0)
10639 		goto done;
10640 	sbuf_printf(sb, "HW TID usage: %u IP users, %u IPv6 users", x, y);
10641 done:
10642 	if (rc == 0)
10643 		rc = sbuf_finish(sb);
10644 	else
10645 		(void)sbuf_finish(sb);
10646 	sbuf_delete(sb);
10647 
10648 	return (rc);
10649 }
10650 
10651 static int
10652 sysctl_tp_err_stats(SYSCTL_HANDLER_ARGS)
10653 {
10654 	struct adapter *sc = arg1;
10655 	struct sbuf *sb;
10656 	int rc;
10657 	struct tp_err_stats stats;
10658 
10659 	rc = sysctl_wire_old_buffer(req, 0);
10660 	if (rc != 0)
10661 		return (rc);
10662 
10663 	mtx_lock(&sc->reg_lock);
10664 	if (hw_off_limits(sc))
10665 		rc = ENXIO;
10666 	else
10667 		t4_tp_get_err_stats(sc, &stats, 0);
10668 	mtx_unlock(&sc->reg_lock);
10669 	if (rc != 0)
10670 		return (rc);
10671 
10672 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10673 	if (sb == NULL)
10674 		return (ENOMEM);
10675 
10676 	if (sc->chip_params->nchan > 2) {
10677 		sbuf_printf(sb, "                 channel 0  channel 1"
10678 		    "  channel 2  channel 3\n");
10679 		sbuf_printf(sb, "macInErrs:      %10u %10u %10u %10u\n",
10680 		    stats.mac_in_errs[0], stats.mac_in_errs[1],
10681 		    stats.mac_in_errs[2], stats.mac_in_errs[3]);
10682 		sbuf_printf(sb, "hdrInErrs:      %10u %10u %10u %10u\n",
10683 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1],
10684 		    stats.hdr_in_errs[2], stats.hdr_in_errs[3]);
10685 		sbuf_printf(sb, "tcpInErrs:      %10u %10u %10u %10u\n",
10686 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1],
10687 		    stats.tcp_in_errs[2], stats.tcp_in_errs[3]);
10688 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u %10u %10u\n",
10689 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1],
10690 		    stats.tcp6_in_errs[2], stats.tcp6_in_errs[3]);
10691 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u %10u %10u\n",
10692 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1],
10693 		    stats.tnl_cong_drops[2], stats.tnl_cong_drops[3]);
10694 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u %10u %10u\n",
10695 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1],
10696 		    stats.tnl_tx_drops[2], stats.tnl_tx_drops[3]);
10697 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u %10u %10u\n",
10698 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1],
10699 		    stats.ofld_vlan_drops[2], stats.ofld_vlan_drops[3]);
10700 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u %10u %10u\n\n",
10701 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1],
10702 		    stats.ofld_chan_drops[2], stats.ofld_chan_drops[3]);
10703 	} else {
10704 		sbuf_printf(sb, "                 channel 0  channel 1\n");
10705 		sbuf_printf(sb, "macInErrs:      %10u %10u\n",
10706 		    stats.mac_in_errs[0], stats.mac_in_errs[1]);
10707 		sbuf_printf(sb, "hdrInErrs:      %10u %10u\n",
10708 		    stats.hdr_in_errs[0], stats.hdr_in_errs[1]);
10709 		sbuf_printf(sb, "tcpInErrs:      %10u %10u\n",
10710 		    stats.tcp_in_errs[0], stats.tcp_in_errs[1]);
10711 		sbuf_printf(sb, "tcp6InErrs:     %10u %10u\n",
10712 		    stats.tcp6_in_errs[0], stats.tcp6_in_errs[1]);
10713 		sbuf_printf(sb, "tnlCongDrops:   %10u %10u\n",
10714 		    stats.tnl_cong_drops[0], stats.tnl_cong_drops[1]);
10715 		sbuf_printf(sb, "tnlTxDrops:     %10u %10u\n",
10716 		    stats.tnl_tx_drops[0], stats.tnl_tx_drops[1]);
10717 		sbuf_printf(sb, "ofldVlanDrops:  %10u %10u\n",
10718 		    stats.ofld_vlan_drops[0], stats.ofld_vlan_drops[1]);
10719 		sbuf_printf(sb, "ofldChanDrops:  %10u %10u\n\n",
10720 		    stats.ofld_chan_drops[0], stats.ofld_chan_drops[1]);
10721 	}
10722 
10723 	sbuf_printf(sb, "ofldNoNeigh:    %u\nofldCongDefer:  %u",
10724 	    stats.ofld_no_neigh, stats.ofld_cong_defer);
10725 
10726 	rc = sbuf_finish(sb);
10727 	sbuf_delete(sb);
10728 
10729 	return (rc);
10730 }
10731 
10732 static int
10733 sysctl_tnl_stats(SYSCTL_HANDLER_ARGS)
10734 {
10735 	struct adapter *sc = arg1;
10736 	struct sbuf *sb;
10737 	int rc;
10738 	struct tp_tnl_stats stats;
10739 
10740 	rc = sysctl_wire_old_buffer(req, 0);
10741 	if (rc != 0)
10742 		return(rc);
10743 
10744 	mtx_lock(&sc->reg_lock);
10745 	if (hw_off_limits(sc))
10746 		rc = ENXIO;
10747 	else
10748 		t4_tp_get_tnl_stats(sc, &stats, 1);
10749 	mtx_unlock(&sc->reg_lock);
10750 	if (rc != 0)
10751 		return (rc);
10752 
10753 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
10754 	if (sb == NULL)
10755 		return (ENOMEM);
10756 
10757 	if (sc->chip_params->nchan > 2) {
10758 		sbuf_printf(sb, "           channel 0  channel 1"
10759 		    "  channel 2  channel 3\n");
10760 		sbuf_printf(sb, "OutPkts:  %10u %10u %10u %10u\n",
10761 		    stats.out_pkt[0], stats.out_pkt[1],
10762 		    stats.out_pkt[2], stats.out_pkt[3]);
10763 		sbuf_printf(sb, "InPkts:   %10u %10u %10u %10u",
10764 		    stats.in_pkt[0], stats.in_pkt[1],
10765 		    stats.in_pkt[2], stats.in_pkt[3]);
10766 	} else {
10767 		sbuf_printf(sb, "           channel 0  channel 1\n");
10768 		sbuf_printf(sb, "OutPkts:  %10u %10u\n",
10769 		    stats.out_pkt[0], stats.out_pkt[1]);
10770 		sbuf_printf(sb, "InPkts:   %10u %10u",
10771 		    stats.in_pkt[0], stats.in_pkt[1]);
10772 	}
10773 
10774 	rc = sbuf_finish(sb);
10775 	sbuf_delete(sb);
10776 
10777 	return (rc);
10778 }
10779 
10780 static int
10781 sysctl_tp_la_mask(SYSCTL_HANDLER_ARGS)
10782 {
10783 	struct adapter *sc = arg1;
10784 	struct tp_params *tpp = &sc->params.tp;
10785 	u_int mask;
10786 	int rc;
10787 
10788 	mask = tpp->la_mask >> 16;
10789 	rc = sysctl_handle_int(oidp, &mask, 0, req);
10790 	if (rc != 0 || req->newptr == NULL)
10791 		return (rc);
10792 	if (mask > 0xffff)
10793 		return (EINVAL);
10794 	mtx_lock(&sc->reg_lock);
10795 	if (hw_off_limits(sc))
10796 		rc = ENXIO;
10797 	else {
10798 		tpp->la_mask = mask << 16;
10799 		t4_set_reg_field(sc, A_TP_DBG_LA_CONFIG, 0xffff0000U,
10800 		    tpp->la_mask);
10801 	}
10802 	mtx_unlock(&sc->reg_lock);
10803 
10804 	return (rc);
10805 }
10806 
10807 struct field_desc {
10808 	const char *name;
10809 	u_int start;
10810 	u_int width;
10811 };
10812 
10813 static void
10814 field_desc_show(struct sbuf *sb, uint64_t v, const struct field_desc *f)
10815 {
10816 	char buf[32];
10817 	int line_size = 0;
10818 
10819 	while (f->name) {
10820 		uint64_t mask = (1ULL << f->width) - 1;
10821 		int len = snprintf(buf, sizeof(buf), "%s: %ju", f->name,
10822 		    ((uintmax_t)v >> f->start) & mask);
10823 
10824 		if (line_size + len >= 79) {
10825 			line_size = 8;
10826 			sbuf_printf(sb, "\n        ");
10827 		}
10828 		sbuf_printf(sb, "%s ", buf);
10829 		line_size += len + 1;
10830 		f++;
10831 	}
10832 	sbuf_printf(sb, "\n");
10833 }
10834 
10835 static const struct field_desc tp_la0[] = {
10836 	{ "RcfOpCodeOut", 60, 4 },
10837 	{ "State", 56, 4 },
10838 	{ "WcfState", 52, 4 },
10839 	{ "RcfOpcSrcOut", 50, 2 },
10840 	{ "CRxError", 49, 1 },
10841 	{ "ERxError", 48, 1 },
10842 	{ "SanityFailed", 47, 1 },
10843 	{ "SpuriousMsg", 46, 1 },
10844 	{ "FlushInputMsg", 45, 1 },
10845 	{ "FlushInputCpl", 44, 1 },
10846 	{ "RssUpBit", 43, 1 },
10847 	{ "RssFilterHit", 42, 1 },
10848 	{ "Tid", 32, 10 },
10849 	{ "InitTcb", 31, 1 },
10850 	{ "LineNumber", 24, 7 },
10851 	{ "Emsg", 23, 1 },
10852 	{ "EdataOut", 22, 1 },
10853 	{ "Cmsg", 21, 1 },
10854 	{ "CdataOut", 20, 1 },
10855 	{ "EreadPdu", 19, 1 },
10856 	{ "CreadPdu", 18, 1 },
10857 	{ "TunnelPkt", 17, 1 },
10858 	{ "RcfPeerFin", 16, 1 },
10859 	{ "RcfReasonOut", 12, 4 },
10860 	{ "TxCchannel", 10, 2 },
10861 	{ "RcfTxChannel", 8, 2 },
10862 	{ "RxEchannel", 6, 2 },
10863 	{ "RcfRxChannel", 5, 1 },
10864 	{ "RcfDataOutSrdy", 4, 1 },
10865 	{ "RxDvld", 3, 1 },
10866 	{ "RxOoDvld", 2, 1 },
10867 	{ "RxCongestion", 1, 1 },
10868 	{ "TxCongestion", 0, 1 },
10869 	{ NULL }
10870 };
10871 
10872 static const struct field_desc tp_la1[] = {
10873 	{ "CplCmdIn", 56, 8 },
10874 	{ "CplCmdOut", 48, 8 },
10875 	{ "ESynOut", 47, 1 },
10876 	{ "EAckOut", 46, 1 },
10877 	{ "EFinOut", 45, 1 },
10878 	{ "ERstOut", 44, 1 },
10879 	{ "SynIn", 43, 1 },
10880 	{ "AckIn", 42, 1 },
10881 	{ "FinIn", 41, 1 },
10882 	{ "RstIn", 40, 1 },
10883 	{ "DataIn", 39, 1 },
10884 	{ "DataInVld", 38, 1 },
10885 	{ "PadIn", 37, 1 },
10886 	{ "RxBufEmpty", 36, 1 },
10887 	{ "RxDdp", 35, 1 },
10888 	{ "RxFbCongestion", 34, 1 },
10889 	{ "TxFbCongestion", 33, 1 },
10890 	{ "TxPktSumSrdy", 32, 1 },
10891 	{ "RcfUlpType", 28, 4 },
10892 	{ "Eread", 27, 1 },
10893 	{ "Ebypass", 26, 1 },
10894 	{ "Esave", 25, 1 },
10895 	{ "Static0", 24, 1 },
10896 	{ "Cread", 23, 1 },
10897 	{ "Cbypass", 22, 1 },
10898 	{ "Csave", 21, 1 },
10899 	{ "CPktOut", 20, 1 },
10900 	{ "RxPagePoolFull", 18, 2 },
10901 	{ "RxLpbkPkt", 17, 1 },
10902 	{ "TxLpbkPkt", 16, 1 },
10903 	{ "RxVfValid", 15, 1 },
10904 	{ "SynLearned", 14, 1 },
10905 	{ "SetDelEntry", 13, 1 },
10906 	{ "SetInvEntry", 12, 1 },
10907 	{ "CpcmdDvld", 11, 1 },
10908 	{ "CpcmdSave", 10, 1 },
10909 	{ "RxPstructsFull", 8, 2 },
10910 	{ "EpcmdDvld", 7, 1 },
10911 	{ "EpcmdFlush", 6, 1 },
10912 	{ "EpcmdTrimPrefix", 5, 1 },
10913 	{ "EpcmdTrimPostfix", 4, 1 },
10914 	{ "ERssIp4Pkt", 3, 1 },
10915 	{ "ERssIp6Pkt", 2, 1 },
10916 	{ "ERssTcpUdpPkt", 1, 1 },
10917 	{ "ERssFceFipPkt", 0, 1 },
10918 	{ NULL }
10919 };
10920 
10921 static const struct field_desc tp_la2[] = {
10922 	{ "CplCmdIn", 56, 8 },
10923 	{ "MpsVfVld", 55, 1 },
10924 	{ "MpsPf", 52, 3 },
10925 	{ "MpsVf", 44, 8 },
10926 	{ "SynIn", 43, 1 },
10927 	{ "AckIn", 42, 1 },
10928 	{ "FinIn", 41, 1 },
10929 	{ "RstIn", 40, 1 },
10930 	{ "DataIn", 39, 1 },
10931 	{ "DataInVld", 38, 1 },
10932 	{ "PadIn", 37, 1 },
10933 	{ "RxBufEmpty", 36, 1 },
10934 	{ "RxDdp", 35, 1 },
10935 	{ "RxFbCongestion", 34, 1 },
10936 	{ "TxFbCongestion", 33, 1 },
10937 	{ "TxPktSumSrdy", 32, 1 },
10938 	{ "RcfUlpType", 28, 4 },
10939 	{ "Eread", 27, 1 },
10940 	{ "Ebypass", 26, 1 },
10941 	{ "Esave", 25, 1 },
10942 	{ "Static0", 24, 1 },
10943 	{ "Cread", 23, 1 },
10944 	{ "Cbypass", 22, 1 },
10945 	{ "Csave", 21, 1 },
10946 	{ "CPktOut", 20, 1 },
10947 	{ "RxPagePoolFull", 18, 2 },
10948 	{ "RxLpbkPkt", 17, 1 },
10949 	{ "TxLpbkPkt", 16, 1 },
10950 	{ "RxVfValid", 15, 1 },
10951 	{ "SynLearned", 14, 1 },
10952 	{ "SetDelEntry", 13, 1 },
10953 	{ "SetInvEntry", 12, 1 },
10954 	{ "CpcmdDvld", 11, 1 },
10955 	{ "CpcmdSave", 10, 1 },
10956 	{ "RxPstructsFull", 8, 2 },
10957 	{ "EpcmdDvld", 7, 1 },
10958 	{ "EpcmdFlush", 6, 1 },
10959 	{ "EpcmdTrimPrefix", 5, 1 },
10960 	{ "EpcmdTrimPostfix", 4, 1 },
10961 	{ "ERssIp4Pkt", 3, 1 },
10962 	{ "ERssIp6Pkt", 2, 1 },
10963 	{ "ERssTcpUdpPkt", 1, 1 },
10964 	{ "ERssFceFipPkt", 0, 1 },
10965 	{ NULL }
10966 };
10967 
10968 static void
10969 tp_la_show(struct sbuf *sb, uint64_t *p, int idx)
10970 {
10971 
10972 	field_desc_show(sb, *p, tp_la0);
10973 }
10974 
10975 static void
10976 tp_la_show2(struct sbuf *sb, uint64_t *p, int idx)
10977 {
10978 
10979 	if (idx)
10980 		sbuf_printf(sb, "\n");
10981 	field_desc_show(sb, p[0], tp_la0);
10982 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10983 		field_desc_show(sb, p[1], tp_la0);
10984 }
10985 
10986 static void
10987 tp_la_show3(struct sbuf *sb, uint64_t *p, int idx)
10988 {
10989 
10990 	if (idx)
10991 		sbuf_printf(sb, "\n");
10992 	field_desc_show(sb, p[0], tp_la0);
10993 	if (idx < (TPLA_SIZE / 2 - 1) || p[1] != ~0ULL)
10994 		field_desc_show(sb, p[1], (p[0] & (1 << 17)) ? tp_la2 : tp_la1);
10995 }
10996 
10997 static int
10998 sysctl_tp_la(SYSCTL_HANDLER_ARGS)
10999 {
11000 	struct adapter *sc = arg1;
11001 	struct sbuf *sb;
11002 	uint64_t *buf, *p;
11003 	int rc;
11004 	u_int i, inc;
11005 	void (*show_func)(struct sbuf *, uint64_t *, int);
11006 
11007 	rc = sysctl_wire_old_buffer(req, 0);
11008 	if (rc != 0)
11009 		return (rc);
11010 
11011 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11012 	if (sb == NULL)
11013 		return (ENOMEM);
11014 
11015 	buf = malloc(TPLA_SIZE * sizeof(uint64_t), M_CXGBE, M_ZERO | M_WAITOK);
11016 
11017 	mtx_lock(&sc->reg_lock);
11018 	if (hw_off_limits(sc))
11019 		rc = ENXIO;
11020 	else {
11021 		t4_tp_read_la(sc, buf, NULL);
11022 		switch (G_DBGLAMODE(t4_read_reg(sc, A_TP_DBG_LA_CONFIG))) {
11023 		case 2:
11024 			inc = 2;
11025 			show_func = tp_la_show2;
11026 			break;
11027 		case 3:
11028 			inc = 2;
11029 			show_func = tp_la_show3;
11030 			break;
11031 		default:
11032 			inc = 1;
11033 			show_func = tp_la_show;
11034 		}
11035 	}
11036 	mtx_unlock(&sc->reg_lock);
11037 	if (rc != 0)
11038 		goto done;
11039 
11040 	p = buf;
11041 	for (i = 0; i < TPLA_SIZE / inc; i++, p += inc)
11042 		(*show_func)(sb, p, i);
11043 	rc = sbuf_finish(sb);
11044 done:
11045 	sbuf_delete(sb);
11046 	free(buf, M_CXGBE);
11047 	return (rc);
11048 }
11049 
11050 static int
11051 sysctl_tx_rate(SYSCTL_HANDLER_ARGS)
11052 {
11053 	struct adapter *sc = arg1;
11054 	struct sbuf *sb;
11055 	int rc;
11056 	u64 nrate[MAX_NCHAN], orate[MAX_NCHAN];
11057 
11058 	rc = sysctl_wire_old_buffer(req, 0);
11059 	if (rc != 0)
11060 		return (rc);
11061 
11062 	mtx_lock(&sc->reg_lock);
11063 	if (hw_off_limits(sc))
11064 		rc = ENXIO;
11065 	else
11066 		t4_get_chan_txrate(sc, nrate, orate);
11067 	mtx_unlock(&sc->reg_lock);
11068 	if (rc != 0)
11069 		return (rc);
11070 
11071 	sb = sbuf_new_for_sysctl(NULL, NULL, 256, req);
11072 	if (sb == NULL)
11073 		return (ENOMEM);
11074 
11075 	if (sc->chip_params->nchan > 2) {
11076 		sbuf_printf(sb, "              channel 0   channel 1"
11077 		    "   channel 2   channel 3\n");
11078 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju  %10ju  %10ju\n",
11079 		    nrate[0], nrate[1], nrate[2], nrate[3]);
11080 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju  %10ju  %10ju",
11081 		    orate[0], orate[1], orate[2], orate[3]);
11082 	} else {
11083 		sbuf_printf(sb, "              channel 0   channel 1\n");
11084 		sbuf_printf(sb, "NIC B/s:     %10ju  %10ju\n",
11085 		    nrate[0], nrate[1]);
11086 		sbuf_printf(sb, "Offload B/s: %10ju  %10ju",
11087 		    orate[0], orate[1]);
11088 	}
11089 
11090 	rc = sbuf_finish(sb);
11091 	sbuf_delete(sb);
11092 
11093 	return (rc);
11094 }
11095 
11096 static int
11097 sysctl_ulprx_la(SYSCTL_HANDLER_ARGS)
11098 {
11099 	struct adapter *sc = arg1;
11100 	struct sbuf *sb;
11101 	uint32_t *buf, *p;
11102 	int rc, i;
11103 
11104 	rc = sysctl_wire_old_buffer(req, 0);
11105 	if (rc != 0)
11106 		return (rc);
11107 
11108 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11109 	if (sb == NULL)
11110 		return (ENOMEM);
11111 
11112 	buf = malloc(ULPRX_LA_SIZE * 8 * sizeof(uint32_t), M_CXGBE,
11113 	    M_ZERO | M_WAITOK);
11114 
11115 	mtx_lock(&sc->reg_lock);
11116 	if (hw_off_limits(sc))
11117 		rc = ENXIO;
11118 	else
11119 		t4_ulprx_read_la(sc, buf);
11120 	mtx_unlock(&sc->reg_lock);
11121 	if (rc != 0)
11122 		goto done;
11123 
11124 	p = buf;
11125 	sbuf_printf(sb, "      Pcmd        Type   Message"
11126 	    "                Data");
11127 	for (i = 0; i < ULPRX_LA_SIZE; i++, p += 8) {
11128 		sbuf_printf(sb, "\n%08x%08x  %4x  %08x  %08x%08x%08x%08x",
11129 		    p[1], p[0], p[2], p[3], p[7], p[6], p[5], p[4]);
11130 	}
11131 	rc = sbuf_finish(sb);
11132 done:
11133 	sbuf_delete(sb);
11134 	free(buf, M_CXGBE);
11135 	return (rc);
11136 }
11137 
11138 static int
11139 sysctl_wcwr_stats(SYSCTL_HANDLER_ARGS)
11140 {
11141 	struct adapter *sc = arg1;
11142 	struct sbuf *sb;
11143 	int rc;
11144 	uint32_t cfg, s1, s2;
11145 
11146 	MPASS(chip_id(sc) >= CHELSIO_T5);
11147 
11148 	rc = sysctl_wire_old_buffer(req, 0);
11149 	if (rc != 0)
11150 		return (rc);
11151 
11152 	mtx_lock(&sc->reg_lock);
11153 	if (hw_off_limits(sc))
11154 		rc = ENXIO;
11155 	else {
11156 		cfg = t4_read_reg(sc, A_SGE_STAT_CFG);
11157 		s1 = t4_read_reg(sc, A_SGE_STAT_TOTAL);
11158 		s2 = t4_read_reg(sc, A_SGE_STAT_MATCH);
11159 	}
11160 	mtx_unlock(&sc->reg_lock);
11161 	if (rc != 0)
11162 		return (rc);
11163 
11164 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11165 	if (sb == NULL)
11166 		return (ENOMEM);
11167 
11168 	if (G_STATSOURCE_T5(cfg) == 7) {
11169 		int mode;
11170 
11171 		mode = is_t5(sc) ? G_STATMODE(cfg) : G_T6_STATMODE(cfg);
11172 		if (mode == 0)
11173 			sbuf_printf(sb, "total %d, incomplete %d", s1, s2);
11174 		else if (mode == 1)
11175 			sbuf_printf(sb, "total %d, data overflow %d", s1, s2);
11176 		else
11177 			sbuf_printf(sb, "unknown mode %d", mode);
11178 	}
11179 	rc = sbuf_finish(sb);
11180 	sbuf_delete(sb);
11181 
11182 	return (rc);
11183 }
11184 
11185 static int
11186 sysctl_cpus(SYSCTL_HANDLER_ARGS)
11187 {
11188 	struct adapter *sc = arg1;
11189 	enum cpu_sets op = arg2;
11190 	cpuset_t cpuset;
11191 	struct sbuf *sb;
11192 	int i, rc;
11193 
11194 	MPASS(op == LOCAL_CPUS || op == INTR_CPUS);
11195 
11196 	CPU_ZERO(&cpuset);
11197 	rc = bus_get_cpus(sc->dev, op, sizeof(cpuset), &cpuset);
11198 	if (rc != 0)
11199 		return (rc);
11200 
11201 	rc = sysctl_wire_old_buffer(req, 0);
11202 	if (rc != 0)
11203 		return (rc);
11204 
11205 	sb = sbuf_new_for_sysctl(NULL, NULL, 4096, req);
11206 	if (sb == NULL)
11207 		return (ENOMEM);
11208 
11209 	CPU_FOREACH(i)
11210 		sbuf_printf(sb, "%d ", i);
11211 	rc = sbuf_finish(sb);
11212 	sbuf_delete(sb);
11213 
11214 	return (rc);
11215 }
11216 
11217 static int
11218 sysctl_reset(SYSCTL_HANDLER_ARGS)
11219 {
11220 	struct adapter *sc = arg1;
11221 	u_int val;
11222 	int rc;
11223 
11224 	val = atomic_load_int(&sc->num_resets);
11225 	rc = sysctl_handle_int(oidp, &val, 0, req);
11226 	if (rc != 0 || req->newptr == NULL)
11227 		return (rc);
11228 
11229 	if (val == 0) {
11230 		/* Zero out the counter that tracks reset. */
11231 		atomic_store_int(&sc->num_resets, 0);
11232 		return (0);
11233 	}
11234 
11235 	if (val != 1)
11236 		return (EINVAL);	/* 0 or 1 are the only legal values */
11237 
11238 	if (hw_off_limits(sc))		/* harmless race */
11239 		return (EALREADY);
11240 
11241 	taskqueue_enqueue(reset_tq, &sc->reset_task);
11242 	return (0);
11243 }
11244 
11245 #ifdef TCP_OFFLOAD
11246 static int
11247 sysctl_tls(SYSCTL_HANDLER_ARGS)
11248 {
11249 	struct adapter *sc = arg1;
11250 	int i, j, v, rc;
11251 	struct vi_info *vi;
11252 
11253 	v = sc->tt.tls;
11254 	rc = sysctl_handle_int(oidp, &v, 0, req);
11255 	if (rc != 0 || req->newptr == NULL)
11256 		return (rc);
11257 
11258 	if (v != 0 && !(sc->cryptocaps & FW_CAPS_CONFIG_TLSKEYS))
11259 		return (ENOTSUP);
11260 
11261 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4stls");
11262 	if (rc)
11263 		return (rc);
11264 	if (hw_off_limits(sc))
11265 		rc = ENXIO;
11266 	else {
11267 		sc->tt.tls = !!v;
11268 		for_each_port(sc, i) {
11269 			for_each_vi(sc->port[i], j, vi) {
11270 				if (vi->flags & VI_INIT_DONE)
11271 					t4_update_fl_bufsize(vi->ifp);
11272 			}
11273 		}
11274 	}
11275 	end_synchronized_op(sc, 0);
11276 
11277 	return (rc);
11278 
11279 }
11280 
11281 static void
11282 unit_conv(char *buf, size_t len, u_int val, u_int factor)
11283 {
11284 	u_int rem = val % factor;
11285 
11286 	if (rem == 0)
11287 		snprintf(buf, len, "%u", val / factor);
11288 	else {
11289 		while (rem % 10 == 0)
11290 			rem /= 10;
11291 		snprintf(buf, len, "%u.%u", val / factor, rem);
11292 	}
11293 }
11294 
11295 static int
11296 sysctl_tp_tick(SYSCTL_HANDLER_ARGS)
11297 {
11298 	struct adapter *sc = arg1;
11299 	char buf[16];
11300 	u_int res, re;
11301 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11302 
11303 	mtx_lock(&sc->reg_lock);
11304 	if (hw_off_limits(sc))
11305 		res = (u_int)-1;
11306 	else
11307 		res = t4_read_reg(sc, A_TP_TIMER_RESOLUTION);
11308 	mtx_unlock(&sc->reg_lock);
11309 	if (res == (u_int)-1)
11310 		return (ENXIO);
11311 
11312 	switch (arg2) {
11313 	case 0:
11314 		/* timer_tick */
11315 		re = G_TIMERRESOLUTION(res);
11316 		break;
11317 	case 1:
11318 		/* TCP timestamp tick */
11319 		re = G_TIMESTAMPRESOLUTION(res);
11320 		break;
11321 	case 2:
11322 		/* DACK tick */
11323 		re = G_DELAYEDACKRESOLUTION(res);
11324 		break;
11325 	default:
11326 		return (EDOOFUS);
11327 	}
11328 
11329 	unit_conv(buf, sizeof(buf), (cclk_ps << re), 1000000);
11330 
11331 	return (sysctl_handle_string(oidp, buf, sizeof(buf), req));
11332 }
11333 
11334 static int
11335 sysctl_tp_dack_timer(SYSCTL_HANDLER_ARGS)
11336 {
11337 	struct adapter *sc = arg1;
11338 	int rc;
11339 	u_int dack_tmr, dack_re, v;
11340 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11341 
11342 	mtx_lock(&sc->reg_lock);
11343 	if (hw_off_limits(sc))
11344 		rc = ENXIO;
11345 	else {
11346 		rc = 0;
11347 		dack_re = G_DELAYEDACKRESOLUTION(t4_read_reg(sc,
11348 		    A_TP_TIMER_RESOLUTION));
11349 		dack_tmr = t4_read_reg(sc, A_TP_DACK_TIMER);
11350 	}
11351 	mtx_unlock(&sc->reg_lock);
11352 	if (rc != 0)
11353 		return (rc);
11354 
11355 	v = ((cclk_ps << dack_re) / 1000000) * dack_tmr;
11356 
11357 	return (sysctl_handle_int(oidp, &v, 0, req));
11358 }
11359 
11360 static int
11361 sysctl_tp_timer(SYSCTL_HANDLER_ARGS)
11362 {
11363 	struct adapter *sc = arg1;
11364 	int rc, reg = arg2;
11365 	u_int tre;
11366 	u_long tp_tick_us, v;
11367 	u_int cclk_ps = 1000000000 / sc->params.vpd.cclk;
11368 
11369 	MPASS(reg == A_TP_RXT_MIN || reg == A_TP_RXT_MAX ||
11370 	    reg == A_TP_PERS_MIN  || reg == A_TP_PERS_MAX ||
11371 	    reg == A_TP_KEEP_IDLE || reg == A_TP_KEEP_INTVL ||
11372 	    reg == A_TP_INIT_SRTT || reg == A_TP_FINWAIT2_TIMER);
11373 
11374 	mtx_lock(&sc->reg_lock);
11375 	if (hw_off_limits(sc))
11376 		rc = ENXIO;
11377 	else {
11378 		rc = 0;
11379 		tre = G_TIMERRESOLUTION(t4_read_reg(sc, A_TP_TIMER_RESOLUTION));
11380 		tp_tick_us = (cclk_ps << tre) / 1000000;
11381 		if (reg == A_TP_INIT_SRTT)
11382 			v = tp_tick_us * G_INITSRTT(t4_read_reg(sc, reg));
11383 		else
11384 			v = tp_tick_us * t4_read_reg(sc, reg);
11385 	}
11386 	mtx_unlock(&sc->reg_lock);
11387 	if (rc != 0)
11388 		return (rc);
11389 	else
11390 		return (sysctl_handle_long(oidp, &v, 0, req));
11391 }
11392 
11393 /*
11394  * All fields in TP_SHIFT_CNT are 4b and the starting location of the field is
11395  * passed to this function.
11396  */
11397 static int
11398 sysctl_tp_shift_cnt(SYSCTL_HANDLER_ARGS)
11399 {
11400 	struct adapter *sc = arg1;
11401 	int rc, idx = arg2;
11402 	u_int v;
11403 
11404 	MPASS(idx >= 0 && idx <= 24);
11405 
11406 	mtx_lock(&sc->reg_lock);
11407 	if (hw_off_limits(sc))
11408 		rc = ENXIO;
11409 	else {
11410 		rc = 0;
11411 		v = (t4_read_reg(sc, A_TP_SHIFT_CNT) >> idx) & 0xf;
11412 	}
11413 	mtx_unlock(&sc->reg_lock);
11414 	if (rc != 0)
11415 		return (rc);
11416 	else
11417 		return (sysctl_handle_int(oidp, &v, 0, req));
11418 }
11419 
11420 static int
11421 sysctl_tp_backoff(SYSCTL_HANDLER_ARGS)
11422 {
11423 	struct adapter *sc = arg1;
11424 	int rc, idx = arg2;
11425 	u_int shift, v, r;
11426 
11427 	MPASS(idx >= 0 && idx < 16);
11428 
11429 	r = A_TP_TCP_BACKOFF_REG0 + (idx & ~3);
11430 	shift = (idx & 3) << 3;
11431 	mtx_lock(&sc->reg_lock);
11432 	if (hw_off_limits(sc))
11433 		rc = ENXIO;
11434 	else {
11435 		rc = 0;
11436 		v = (t4_read_reg(sc, r) >> shift) & M_TIMERBACKOFFINDEX0;
11437 	}
11438 	mtx_unlock(&sc->reg_lock);
11439 	if (rc != 0)
11440 		return (rc);
11441 	else
11442 		return (sysctl_handle_int(oidp, &v, 0, req));
11443 }
11444 
11445 static int
11446 sysctl_holdoff_tmr_idx_ofld(SYSCTL_HANDLER_ARGS)
11447 {
11448 	struct vi_info *vi = arg1;
11449 	struct adapter *sc = vi->adapter;
11450 	int idx, rc, i;
11451 	struct sge_ofld_rxq *ofld_rxq;
11452 	uint8_t v;
11453 
11454 	idx = vi->ofld_tmr_idx;
11455 
11456 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11457 	if (rc != 0 || req->newptr == NULL)
11458 		return (rc);
11459 
11460 	if (idx < 0 || idx >= SGE_NTIMERS)
11461 		return (EINVAL);
11462 
11463 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11464 	    "t4otmr");
11465 	if (rc)
11466 		return (rc);
11467 
11468 	v = V_QINTR_TIMER_IDX(idx) | V_QINTR_CNT_EN(vi->ofld_pktc_idx != -1);
11469 	for_each_ofld_rxq(vi, i, ofld_rxq) {
11470 #ifdef atomic_store_rel_8
11471 		atomic_store_rel_8(&ofld_rxq->iq.intr_params, v);
11472 #else
11473 		ofld_rxq->iq.intr_params = v;
11474 #endif
11475 	}
11476 	vi->ofld_tmr_idx = idx;
11477 
11478 	end_synchronized_op(sc, LOCK_HELD);
11479 	return (0);
11480 }
11481 
11482 static int
11483 sysctl_holdoff_pktc_idx_ofld(SYSCTL_HANDLER_ARGS)
11484 {
11485 	struct vi_info *vi = arg1;
11486 	struct adapter *sc = vi->adapter;
11487 	int idx, rc;
11488 
11489 	idx = vi->ofld_pktc_idx;
11490 
11491 	rc = sysctl_handle_int(oidp, &idx, 0, req);
11492 	if (rc != 0 || req->newptr == NULL)
11493 		return (rc);
11494 
11495 	if (idx < -1 || idx >= SGE_NCOUNTERS)
11496 		return (EINVAL);
11497 
11498 	rc = begin_synchronized_op(sc, vi, HOLD_LOCK | SLEEP_OK | INTR_OK,
11499 	    "t4opktc");
11500 	if (rc)
11501 		return (rc);
11502 
11503 	if (vi->flags & VI_INIT_DONE)
11504 		rc = EBUSY; /* cannot be changed once the queues are created */
11505 	else
11506 		vi->ofld_pktc_idx = idx;
11507 
11508 	end_synchronized_op(sc, LOCK_HELD);
11509 	return (rc);
11510 }
11511 #endif
11512 
11513 static int
11514 get_sge_context(struct adapter *sc, struct t4_sge_context *cntxt)
11515 {
11516 	int rc;
11517 
11518 	if (cntxt->cid > M_CTXTQID)
11519 		return (EINVAL);
11520 
11521 	if (cntxt->mem_id != CTXT_EGRESS && cntxt->mem_id != CTXT_INGRESS &&
11522 	    cntxt->mem_id != CTXT_FLM && cntxt->mem_id != CTXT_CNM)
11523 		return (EINVAL);
11524 
11525 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ctxt");
11526 	if (rc)
11527 		return (rc);
11528 
11529 	if (hw_off_limits(sc)) {
11530 		rc = ENXIO;
11531 		goto done;
11532 	}
11533 
11534 	if (sc->flags & FW_OK) {
11535 		rc = -t4_sge_ctxt_rd(sc, sc->mbox, cntxt->cid, cntxt->mem_id,
11536 		    &cntxt->data[0]);
11537 		if (rc == 0)
11538 			goto done;
11539 	}
11540 
11541 	/*
11542 	 * Read via firmware failed or wasn't even attempted.  Read directly via
11543 	 * the backdoor.
11544 	 */
11545 	rc = -t4_sge_ctxt_rd_bd(sc, cntxt->cid, cntxt->mem_id, &cntxt->data[0]);
11546 done:
11547 	end_synchronized_op(sc, 0);
11548 	return (rc);
11549 }
11550 
11551 static int
11552 load_fw(struct adapter *sc, struct t4_data *fw)
11553 {
11554 	int rc;
11555 	uint8_t *fw_data;
11556 
11557 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldfw");
11558 	if (rc)
11559 		return (rc);
11560 
11561 	if (hw_off_limits(sc)) {
11562 		rc = ENXIO;
11563 		goto done;
11564 	}
11565 
11566 	/*
11567 	 * The firmware, with the sole exception of the memory parity error
11568 	 * handler, runs from memory and not flash.  It is almost always safe to
11569 	 * install a new firmware on a running system.  Just set bit 1 in
11570 	 * hw.cxgbe.dflags or dev.<nexus>.<n>.dflags first.
11571 	 */
11572 	if (sc->flags & FULL_INIT_DONE &&
11573 	    (sc->debug_flags & DF_LOAD_FW_ANYTIME) == 0) {
11574 		rc = EBUSY;
11575 		goto done;
11576 	}
11577 
11578 	fw_data = malloc(fw->len, M_CXGBE, M_WAITOK);
11579 
11580 	rc = copyin(fw->data, fw_data, fw->len);
11581 	if (rc == 0)
11582 		rc = -t4_load_fw(sc, fw_data, fw->len);
11583 
11584 	free(fw_data, M_CXGBE);
11585 done:
11586 	end_synchronized_op(sc, 0);
11587 	return (rc);
11588 }
11589 
11590 static int
11591 load_cfg(struct adapter *sc, struct t4_data *cfg)
11592 {
11593 	int rc;
11594 	uint8_t *cfg_data = NULL;
11595 
11596 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11597 	if (rc)
11598 		return (rc);
11599 
11600 	if (hw_off_limits(sc)) {
11601 		rc = ENXIO;
11602 		goto done;
11603 	}
11604 
11605 	if (cfg->len == 0) {
11606 		/* clear */
11607 		rc = -t4_load_cfg(sc, NULL, 0);
11608 		goto done;
11609 	}
11610 
11611 	cfg_data = malloc(cfg->len, M_CXGBE, M_WAITOK);
11612 
11613 	rc = copyin(cfg->data, cfg_data, cfg->len);
11614 	if (rc == 0)
11615 		rc = -t4_load_cfg(sc, cfg_data, cfg->len);
11616 
11617 	free(cfg_data, M_CXGBE);
11618 done:
11619 	end_synchronized_op(sc, 0);
11620 	return (rc);
11621 }
11622 
11623 static int
11624 load_boot(struct adapter *sc, struct t4_bootrom *br)
11625 {
11626 	int rc;
11627 	uint8_t *br_data = NULL;
11628 	u_int offset;
11629 
11630 	if (br->len > 1024 * 1024)
11631 		return (EFBIG);
11632 
11633 	if (br->pf_offset == 0) {
11634 		/* pfidx */
11635 		if (br->pfidx_addr > 7)
11636 			return (EINVAL);
11637 		offset = G_OFFSET(t4_read_reg(sc, PF_REG(br->pfidx_addr,
11638 		    A_PCIE_PF_EXPROM_OFST)));
11639 	} else if (br->pf_offset == 1) {
11640 		/* offset */
11641 		offset = G_OFFSET(br->pfidx_addr);
11642 	} else {
11643 		return (EINVAL);
11644 	}
11645 
11646 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldbr");
11647 	if (rc)
11648 		return (rc);
11649 
11650 	if (hw_off_limits(sc)) {
11651 		rc = ENXIO;
11652 		goto done;
11653 	}
11654 
11655 	if (br->len == 0) {
11656 		/* clear */
11657 		rc = -t4_load_boot(sc, NULL, offset, 0);
11658 		goto done;
11659 	}
11660 
11661 	br_data = malloc(br->len, M_CXGBE, M_WAITOK);
11662 
11663 	rc = copyin(br->data, br_data, br->len);
11664 	if (rc == 0)
11665 		rc = -t4_load_boot(sc, br_data, offset, br->len);
11666 
11667 	free(br_data, M_CXGBE);
11668 done:
11669 	end_synchronized_op(sc, 0);
11670 	return (rc);
11671 }
11672 
11673 static int
11674 load_bootcfg(struct adapter *sc, struct t4_data *bc)
11675 {
11676 	int rc;
11677 	uint8_t *bc_data = NULL;
11678 
11679 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4ldcf");
11680 	if (rc)
11681 		return (rc);
11682 
11683 	if (hw_off_limits(sc)) {
11684 		rc = ENXIO;
11685 		goto done;
11686 	}
11687 
11688 	if (bc->len == 0) {
11689 		/* clear */
11690 		rc = -t4_load_bootcfg(sc, NULL, 0);
11691 		goto done;
11692 	}
11693 
11694 	bc_data = malloc(bc->len, M_CXGBE, M_WAITOK);
11695 
11696 	rc = copyin(bc->data, bc_data, bc->len);
11697 	if (rc == 0)
11698 		rc = -t4_load_bootcfg(sc, bc_data, bc->len);
11699 
11700 	free(bc_data, M_CXGBE);
11701 done:
11702 	end_synchronized_op(sc, 0);
11703 	return (rc);
11704 }
11705 
11706 static int
11707 cudbg_dump(struct adapter *sc, struct t4_cudbg_dump *dump)
11708 {
11709 	int rc;
11710 	struct cudbg_init *cudbg;
11711 	void *handle, *buf;
11712 
11713 	/* buf is large, don't block if no memory is available */
11714 	buf = malloc(dump->len, M_CXGBE, M_NOWAIT | M_ZERO);
11715 	if (buf == NULL)
11716 		return (ENOMEM);
11717 
11718 	handle = cudbg_alloc_handle();
11719 	if (handle == NULL) {
11720 		rc = ENOMEM;
11721 		goto done;
11722 	}
11723 
11724 	cudbg = cudbg_get_init(handle);
11725 	cudbg->adap = sc;
11726 	cudbg->print = (cudbg_print_cb)printf;
11727 
11728 #ifndef notyet
11729 	device_printf(sc->dev, "%s: wr_flash %u, len %u, data %p.\n",
11730 	    __func__, dump->wr_flash, dump->len, dump->data);
11731 #endif
11732 
11733 	if (dump->wr_flash)
11734 		cudbg->use_flash = 1;
11735 	MPASS(sizeof(cudbg->dbg_bitmap) == sizeof(dump->bitmap));
11736 	memcpy(cudbg->dbg_bitmap, dump->bitmap, sizeof(cudbg->dbg_bitmap));
11737 
11738 	rc = cudbg_collect(handle, buf, &dump->len);
11739 	if (rc != 0)
11740 		goto done;
11741 
11742 	rc = copyout(buf, dump->data, dump->len);
11743 done:
11744 	cudbg_free_handle(handle);
11745 	free(buf, M_CXGBE);
11746 	return (rc);
11747 }
11748 
11749 static void
11750 free_offload_policy(struct t4_offload_policy *op)
11751 {
11752 	struct offload_rule *r;
11753 	int i;
11754 
11755 	if (op == NULL)
11756 		return;
11757 
11758 	r = &op->rule[0];
11759 	for (i = 0; i < op->nrules; i++, r++) {
11760 		free(r->bpf_prog.bf_insns, M_CXGBE);
11761 	}
11762 	free(op->rule, M_CXGBE);
11763 	free(op, M_CXGBE);
11764 }
11765 
11766 static int
11767 set_offload_policy(struct adapter *sc, struct t4_offload_policy *uop)
11768 {
11769 	int i, rc, len;
11770 	struct t4_offload_policy *op, *old;
11771 	struct bpf_program *bf;
11772 	const struct offload_settings *s;
11773 	struct offload_rule *r;
11774 	void *u;
11775 
11776 	if (!is_offload(sc))
11777 		return (ENODEV);
11778 
11779 	if (uop->nrules == 0) {
11780 		/* Delete installed policies. */
11781 		op = NULL;
11782 		goto set_policy;
11783 	} else if (uop->nrules > 256) { /* arbitrary */
11784 		return (E2BIG);
11785 	}
11786 
11787 	/* Copy userspace offload policy to kernel */
11788 	op = malloc(sizeof(*op), M_CXGBE, M_ZERO | M_WAITOK);
11789 	op->nrules = uop->nrules;
11790 	len = op->nrules * sizeof(struct offload_rule);
11791 	op->rule = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11792 	rc = copyin(uop->rule, op->rule, len);
11793 	if (rc) {
11794 		free(op->rule, M_CXGBE);
11795 		free(op, M_CXGBE);
11796 		return (rc);
11797 	}
11798 
11799 	r = &op->rule[0];
11800 	for (i = 0; i < op->nrules; i++, r++) {
11801 
11802 		/* Validate open_type */
11803 		if (r->open_type != OPEN_TYPE_LISTEN &&
11804 		    r->open_type != OPEN_TYPE_ACTIVE &&
11805 		    r->open_type != OPEN_TYPE_PASSIVE &&
11806 		    r->open_type != OPEN_TYPE_DONTCARE) {
11807 error:
11808 			/*
11809 			 * Rules 0 to i have malloc'd filters that need to be
11810 			 * freed.  Rules i+1 to nrules have userspace pointers
11811 			 * and should be left alone.
11812 			 */
11813 			op->nrules = i;
11814 			free_offload_policy(op);
11815 			return (rc);
11816 		}
11817 
11818 		/* Validate settings */
11819 		s = &r->settings;
11820 		if ((s->offload != 0 && s->offload != 1) ||
11821 		    s->cong_algo < -1 || s->cong_algo > CONG_ALG_HIGHSPEED ||
11822 		    s->sched_class < -1 ||
11823 		    s->sched_class >= sc->params.nsched_cls) {
11824 			rc = EINVAL;
11825 			goto error;
11826 		}
11827 
11828 		bf = &r->bpf_prog;
11829 		u = bf->bf_insns;	/* userspace ptr */
11830 		bf->bf_insns = NULL;
11831 		if (bf->bf_len == 0) {
11832 			/* legal, matches everything */
11833 			continue;
11834 		}
11835 		len = bf->bf_len * sizeof(*bf->bf_insns);
11836 		bf->bf_insns = malloc(len, M_CXGBE, M_ZERO | M_WAITOK);
11837 		rc = copyin(u, bf->bf_insns, len);
11838 		if (rc != 0)
11839 			goto error;
11840 
11841 		if (!bpf_validate(bf->bf_insns, bf->bf_len)) {
11842 			rc = EINVAL;
11843 			goto error;
11844 		}
11845 	}
11846 set_policy:
11847 	rw_wlock(&sc->policy_lock);
11848 	old = sc->policy;
11849 	sc->policy = op;
11850 	rw_wunlock(&sc->policy_lock);
11851 	free_offload_policy(old);
11852 
11853 	return (0);
11854 }
11855 
11856 #define MAX_READ_BUF_SIZE (128 * 1024)
11857 static int
11858 read_card_mem(struct adapter *sc, int win, struct t4_mem_range *mr)
11859 {
11860 	uint32_t addr, remaining, n;
11861 	uint32_t *buf;
11862 	int rc;
11863 	uint8_t *dst;
11864 
11865 	mtx_lock(&sc->reg_lock);
11866 	if (hw_off_limits(sc))
11867 		rc = ENXIO;
11868 	else
11869 		rc = validate_mem_range(sc, mr->addr, mr->len);
11870 	mtx_unlock(&sc->reg_lock);
11871 	if (rc != 0)
11872 		return (rc);
11873 
11874 	buf = malloc(min(mr->len, MAX_READ_BUF_SIZE), M_CXGBE, M_WAITOK);
11875 	addr = mr->addr;
11876 	remaining = mr->len;
11877 	dst = (void *)mr->data;
11878 
11879 	while (remaining) {
11880 		n = min(remaining, MAX_READ_BUF_SIZE);
11881 		mtx_lock(&sc->reg_lock);
11882 		if (hw_off_limits(sc))
11883 			rc = ENXIO;
11884 		else
11885 			read_via_memwin(sc, 2, addr, buf, n);
11886 		mtx_unlock(&sc->reg_lock);
11887 		if (rc != 0)
11888 			break;
11889 
11890 		rc = copyout(buf, dst, n);
11891 		if (rc != 0)
11892 			break;
11893 
11894 		dst += n;
11895 		remaining -= n;
11896 		addr += n;
11897 	}
11898 
11899 	free(buf, M_CXGBE);
11900 	return (rc);
11901 }
11902 #undef MAX_READ_BUF_SIZE
11903 
11904 static int
11905 read_i2c(struct adapter *sc, struct t4_i2c_data *i2cd)
11906 {
11907 	int rc;
11908 
11909 	if (i2cd->len == 0 || i2cd->port_id >= sc->params.nports)
11910 		return (EINVAL);
11911 
11912 	if (i2cd->len > sizeof(i2cd->data))
11913 		return (EFBIG);
11914 
11915 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4i2crd");
11916 	if (rc)
11917 		return (rc);
11918 	if (hw_off_limits(sc))
11919 		rc = ENXIO;
11920 	else
11921 		rc = -t4_i2c_rd(sc, sc->mbox, i2cd->port_id, i2cd->dev_addr,
11922 		    i2cd->offset, i2cd->len, &i2cd->data[0]);
11923 	end_synchronized_op(sc, 0);
11924 
11925 	return (rc);
11926 }
11927 
11928 static int
11929 clear_stats(struct adapter *sc, u_int port_id)
11930 {
11931 	int i, v, chan_map;
11932 	struct port_info *pi;
11933 	struct vi_info *vi;
11934 	struct sge_rxq *rxq;
11935 	struct sge_txq *txq;
11936 	struct sge_wrq *wrq;
11937 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
11938 	struct sge_ofld_txq *ofld_txq;
11939 #endif
11940 #ifdef TCP_OFFLOAD
11941 	struct sge_ofld_rxq *ofld_rxq;
11942 #endif
11943 
11944 	if (port_id >= sc->params.nports)
11945 		return (EINVAL);
11946 	pi = sc->port[port_id];
11947 	if (pi == NULL)
11948 		return (EIO);
11949 
11950 	mtx_lock(&sc->reg_lock);
11951 	if (!hw_off_limits(sc)) {
11952 		/* MAC stats */
11953 		t4_clr_port_stats(sc, pi->tx_chan);
11954 		if (is_t6(sc)) {
11955 			if (pi->fcs_reg != -1)
11956 				pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
11957 			else
11958 				pi->stats.rx_fcs_err = 0;
11959 		}
11960 		for_each_vi(pi, v, vi) {
11961 			if (vi->flags & VI_INIT_DONE)
11962 				t4_clr_vi_stats(sc, vi->vin);
11963 		}
11964 		chan_map = pi->rx_e_chan_map;
11965 		v = 0;	/* reuse */
11966 		while (chan_map) {
11967 			i = ffs(chan_map) - 1;
11968 			t4_write_indirect(sc, A_TP_MIB_INDEX, A_TP_MIB_DATA, &v,
11969 			    1, A_TP_MIB_TNL_CNG_DROP_0 + i);
11970 			chan_map &= ~(1 << i);
11971 		}
11972 	}
11973 	mtx_unlock(&sc->reg_lock);
11974 	pi->tx_parse_error = 0;
11975 	pi->tnl_cong_drops = 0;
11976 
11977 	/*
11978 	 * Since this command accepts a port, clear stats for
11979 	 * all VIs on this port.
11980 	 */
11981 	for_each_vi(pi, v, vi) {
11982 		if (vi->flags & VI_INIT_DONE) {
11983 
11984 			for_each_rxq(vi, i, rxq) {
11985 #if defined(INET) || defined(INET6)
11986 				rxq->lro.lro_queued = 0;
11987 				rxq->lro.lro_flushed = 0;
11988 #endif
11989 				rxq->rxcsum = 0;
11990 				rxq->vlan_extraction = 0;
11991 				rxq->vxlan_rxcsum = 0;
11992 
11993 				rxq->fl.cl_allocated = 0;
11994 				rxq->fl.cl_recycled = 0;
11995 				rxq->fl.cl_fast_recycled = 0;
11996 			}
11997 
11998 			for_each_txq(vi, i, txq) {
11999 				txq->txcsum = 0;
12000 				txq->tso_wrs = 0;
12001 				txq->vlan_insertion = 0;
12002 				txq->imm_wrs = 0;
12003 				txq->sgl_wrs = 0;
12004 				txq->txpkt_wrs = 0;
12005 				txq->txpkts0_wrs = 0;
12006 				txq->txpkts1_wrs = 0;
12007 				txq->txpkts0_pkts = 0;
12008 				txq->txpkts1_pkts = 0;
12009 				txq->txpkts_flush = 0;
12010 				txq->raw_wrs = 0;
12011 				txq->vxlan_tso_wrs = 0;
12012 				txq->vxlan_txcsum = 0;
12013 				txq->kern_tls_records = 0;
12014 				txq->kern_tls_short = 0;
12015 				txq->kern_tls_partial = 0;
12016 				txq->kern_tls_full = 0;
12017 				txq->kern_tls_octets = 0;
12018 				txq->kern_tls_waste = 0;
12019 				txq->kern_tls_options = 0;
12020 				txq->kern_tls_header = 0;
12021 				txq->kern_tls_fin = 0;
12022 				txq->kern_tls_fin_short = 0;
12023 				txq->kern_tls_cbc = 0;
12024 				txq->kern_tls_gcm = 0;
12025 				mp_ring_reset_stats(txq->r);
12026 			}
12027 
12028 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12029 			for_each_ofld_txq(vi, i, ofld_txq) {
12030 				ofld_txq->wrq.tx_wrs_direct = 0;
12031 				ofld_txq->wrq.tx_wrs_copied = 0;
12032 				counter_u64_zero(ofld_txq->tx_iscsi_pdus);
12033 				counter_u64_zero(ofld_txq->tx_iscsi_octets);
12034 				counter_u64_zero(ofld_txq->tx_iscsi_iso_wrs);
12035 				counter_u64_zero(ofld_txq->tx_aio_jobs);
12036 				counter_u64_zero(ofld_txq->tx_aio_octets);
12037 				counter_u64_zero(ofld_txq->tx_toe_tls_records);
12038 				counter_u64_zero(ofld_txq->tx_toe_tls_octets);
12039 			}
12040 #endif
12041 #ifdef TCP_OFFLOAD
12042 			for_each_ofld_rxq(vi, i, ofld_rxq) {
12043 				ofld_rxq->fl.cl_allocated = 0;
12044 				ofld_rxq->fl.cl_recycled = 0;
12045 				ofld_rxq->fl.cl_fast_recycled = 0;
12046 				counter_u64_zero(
12047 				    ofld_rxq->rx_iscsi_ddp_setup_ok);
12048 				counter_u64_zero(
12049 				    ofld_rxq->rx_iscsi_ddp_setup_error);
12050 				ofld_rxq->rx_iscsi_ddp_pdus = 0;
12051 				ofld_rxq->rx_iscsi_ddp_octets = 0;
12052 				ofld_rxq->rx_iscsi_fl_pdus = 0;
12053 				ofld_rxq->rx_iscsi_fl_octets = 0;
12054 				ofld_rxq->rx_aio_ddp_jobs = 0;
12055 				ofld_rxq->rx_aio_ddp_octets = 0;
12056 				ofld_rxq->rx_toe_tls_records = 0;
12057 				ofld_rxq->rx_toe_tls_octets = 0;
12058 				ofld_rxq->rx_toe_ddp_octets = 0;
12059 				counter_u64_zero(ofld_rxq->ddp_buffer_alloc);
12060 				counter_u64_zero(ofld_rxq->ddp_buffer_reuse);
12061 				counter_u64_zero(ofld_rxq->ddp_buffer_free);
12062 			}
12063 #endif
12064 
12065 			if (IS_MAIN_VI(vi)) {
12066 				wrq = &sc->sge.ctrlq[pi->port_id];
12067 				wrq->tx_wrs_direct = 0;
12068 				wrq->tx_wrs_copied = 0;
12069 			}
12070 		}
12071 	}
12072 
12073 	return (0);
12074 }
12075 
12076 static int
12077 hold_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12078 {
12079 #ifdef INET6
12080 	struct in6_addr in6;
12081 
12082 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12083 	if (t4_get_clip_entry(sc, &in6, true) != NULL)
12084 		return (0);
12085 	else
12086 		return (EIO);
12087 #else
12088 	return (ENOTSUP);
12089 #endif
12090 }
12091 
12092 static int
12093 release_clip_addr(struct adapter *sc, struct t4_clip_addr *ca)
12094 {
12095 #ifdef INET6
12096 	struct in6_addr in6;
12097 
12098 	bcopy(&ca->addr[0], &in6.s6_addr[0], sizeof(in6.s6_addr));
12099 	return (t4_release_clip_addr(sc, &in6));
12100 #else
12101 	return (ENOTSUP);
12102 #endif
12103 }
12104 
12105 int
12106 t4_os_find_pci_capability(struct adapter *sc, int cap)
12107 {
12108 	int i;
12109 
12110 	return (pci_find_cap(sc->dev, cap, &i) == 0 ? i : 0);
12111 }
12112 
12113 int
12114 t4_os_pci_save_state(struct adapter *sc)
12115 {
12116 	device_t dev;
12117 	struct pci_devinfo *dinfo;
12118 
12119 	dev = sc->dev;
12120 	dinfo = device_get_ivars(dev);
12121 
12122 	pci_cfg_save(dev, dinfo, 0);
12123 	return (0);
12124 }
12125 
12126 int
12127 t4_os_pci_restore_state(struct adapter *sc)
12128 {
12129 	device_t dev;
12130 	struct pci_devinfo *dinfo;
12131 
12132 	dev = sc->dev;
12133 	dinfo = device_get_ivars(dev);
12134 
12135 	pci_cfg_restore(dev, dinfo);
12136 	return (0);
12137 }
12138 
12139 void
12140 t4_os_portmod_changed(struct port_info *pi)
12141 {
12142 	struct adapter *sc = pi->adapter;
12143 	struct vi_info *vi;
12144 	if_t ifp;
12145 	static const char *mod_str[] = {
12146 		NULL, "LR", "SR", "ER", "TWINAX", "active TWINAX", "LRM"
12147 	};
12148 
12149 	KASSERT((pi->flags & FIXED_IFMEDIA) == 0,
12150 	    ("%s: port_type %u", __func__, pi->port_type));
12151 
12152 	vi = &pi->vi[0];
12153 	if (begin_synchronized_op(sc, vi, HOLD_LOCK, "t4mod") == 0) {
12154 		PORT_LOCK(pi);
12155 		build_medialist(pi);
12156 		if (pi->mod_type != FW_PORT_MOD_TYPE_NONE) {
12157 			fixup_link_config(pi);
12158 			apply_link_config(pi);
12159 		}
12160 		PORT_UNLOCK(pi);
12161 		end_synchronized_op(sc, LOCK_HELD);
12162 	}
12163 
12164 	ifp = vi->ifp;
12165 	if (pi->mod_type == FW_PORT_MOD_TYPE_NONE)
12166 		if_printf(ifp, "transceiver unplugged.\n");
12167 	else if (pi->mod_type == FW_PORT_MOD_TYPE_UNKNOWN)
12168 		if_printf(ifp, "unknown transceiver inserted.\n");
12169 	else if (pi->mod_type == FW_PORT_MOD_TYPE_NOTSUPPORTED)
12170 		if_printf(ifp, "unsupported transceiver inserted.\n");
12171 	else if (pi->mod_type > 0 && pi->mod_type < nitems(mod_str)) {
12172 		if_printf(ifp, "%dGbps %s transceiver inserted.\n",
12173 		    port_top_speed(pi), mod_str[pi->mod_type]);
12174 	} else {
12175 		if_printf(ifp, "transceiver (type %d) inserted.\n",
12176 		    pi->mod_type);
12177 	}
12178 }
12179 
12180 void
12181 t4_os_link_changed(struct port_info *pi)
12182 {
12183 	struct vi_info *vi;
12184 	if_t ifp;
12185 	struct link_config *lc = &pi->link_cfg;
12186 	struct adapter *sc = pi->adapter;
12187 	int v;
12188 
12189 	PORT_LOCK_ASSERT_OWNED(pi);
12190 
12191 	if (is_t6(sc)) {
12192 		if (lc->link_ok) {
12193 			if (lc->speed > 25000 ||
12194 			    (lc->speed == 25000 && lc->fec == FEC_RS)) {
12195 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12196 				    A_MAC_PORT_AFRAMECHECKSEQUENCEERRORS);
12197 			} else {
12198 				pi->fcs_reg = T5_PORT_REG(pi->tx_chan,
12199 				    A_MAC_PORT_MTIP_1G10G_RX_CRCERRORS);
12200 			}
12201 			pi->fcs_base = t4_read_reg64(sc, pi->fcs_reg);
12202 			pi->stats.rx_fcs_err = 0;
12203 		} else {
12204 			pi->fcs_reg = -1;
12205 		}
12206 	} else {
12207 		MPASS(pi->fcs_reg != -1);
12208 		MPASS(pi->fcs_base == 0);
12209 	}
12210 
12211 	for_each_vi(pi, v, vi) {
12212 		ifp = vi->ifp;
12213 		if (ifp == NULL)
12214 			continue;
12215 
12216 		if (lc->link_ok) {
12217 			if_setbaudrate(ifp, IF_Mbps(lc->speed));
12218 			if_link_state_change(ifp, LINK_STATE_UP);
12219 		} else {
12220 			if_link_state_change(ifp, LINK_STATE_DOWN);
12221 		}
12222 	}
12223 }
12224 
12225 void
12226 t4_iterate(void (*func)(struct adapter *, void *), void *arg)
12227 {
12228 	struct adapter *sc;
12229 
12230 	sx_slock(&t4_list_lock);
12231 	SLIST_FOREACH(sc, &t4_list, link) {
12232 		/*
12233 		 * func should not make any assumptions about what state sc is
12234 		 * in - the only guarantee is that sc->sc_lock is a valid lock.
12235 		 */
12236 		func(sc, arg);
12237 	}
12238 	sx_sunlock(&t4_list_lock);
12239 }
12240 
12241 static int
12242 t4_ioctl(struct cdev *dev, unsigned long cmd, caddr_t data, int fflag,
12243     struct thread *td)
12244 {
12245 	int rc;
12246 	struct adapter *sc = dev->si_drv1;
12247 
12248 	rc = priv_check(td, PRIV_DRIVER);
12249 	if (rc != 0)
12250 		return (rc);
12251 
12252 	switch (cmd) {
12253 	case CHELSIO_T4_GETREG: {
12254 		struct t4_reg *edata = (struct t4_reg *)data;
12255 
12256 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12257 			return (EFAULT);
12258 
12259 		mtx_lock(&sc->reg_lock);
12260 		if (hw_off_limits(sc))
12261 			rc = ENXIO;
12262 		else if (edata->size == 4)
12263 			edata->val = t4_read_reg(sc, edata->addr);
12264 		else if (edata->size == 8)
12265 			edata->val = t4_read_reg64(sc, edata->addr);
12266 		else
12267 			rc = EINVAL;
12268 		mtx_unlock(&sc->reg_lock);
12269 
12270 		break;
12271 	}
12272 	case CHELSIO_T4_SETREG: {
12273 		struct t4_reg *edata = (struct t4_reg *)data;
12274 
12275 		if ((edata->addr & 0x3) != 0 || edata->addr >= sc->mmio_len)
12276 			return (EFAULT);
12277 
12278 		mtx_lock(&sc->reg_lock);
12279 		if (hw_off_limits(sc))
12280 			rc = ENXIO;
12281 		else if (edata->size == 4) {
12282 			if (edata->val & 0xffffffff00000000)
12283 				rc = EINVAL;
12284 			t4_write_reg(sc, edata->addr, (uint32_t) edata->val);
12285 		} else if (edata->size == 8)
12286 			t4_write_reg64(sc, edata->addr, edata->val);
12287 		else
12288 			rc = EINVAL;
12289 		mtx_unlock(&sc->reg_lock);
12290 
12291 		break;
12292 	}
12293 	case CHELSIO_T4_REGDUMP: {
12294 		struct t4_regdump *regs = (struct t4_regdump *)data;
12295 		int reglen = t4_get_regs_len(sc);
12296 		uint8_t *buf;
12297 
12298 		if (regs->len < reglen) {
12299 			regs->len = reglen; /* hint to the caller */
12300 			return (ENOBUFS);
12301 		}
12302 
12303 		regs->len = reglen;
12304 		buf = malloc(reglen, M_CXGBE, M_WAITOK | M_ZERO);
12305 		mtx_lock(&sc->reg_lock);
12306 		if (hw_off_limits(sc))
12307 			rc = ENXIO;
12308 		else
12309 			get_regs(sc, regs, buf);
12310 		mtx_unlock(&sc->reg_lock);
12311 		if (rc == 0)
12312 			rc = copyout(buf, regs->data, reglen);
12313 		free(buf, M_CXGBE);
12314 		break;
12315 	}
12316 	case CHELSIO_T4_GET_FILTER_MODE:
12317 		rc = get_filter_mode(sc, (uint32_t *)data);
12318 		break;
12319 	case CHELSIO_T4_SET_FILTER_MODE:
12320 		rc = set_filter_mode(sc, *(uint32_t *)data);
12321 		break;
12322 	case CHELSIO_T4_SET_FILTER_MASK:
12323 		rc = set_filter_mask(sc, *(uint32_t *)data);
12324 		break;
12325 	case CHELSIO_T4_GET_FILTER:
12326 		rc = get_filter(sc, (struct t4_filter *)data);
12327 		break;
12328 	case CHELSIO_T4_SET_FILTER:
12329 		rc = set_filter(sc, (struct t4_filter *)data);
12330 		break;
12331 	case CHELSIO_T4_DEL_FILTER:
12332 		rc = del_filter(sc, (struct t4_filter *)data);
12333 		break;
12334 	case CHELSIO_T4_GET_SGE_CONTEXT:
12335 		rc = get_sge_context(sc, (struct t4_sge_context *)data);
12336 		break;
12337 	case CHELSIO_T4_LOAD_FW:
12338 		rc = load_fw(sc, (struct t4_data *)data);
12339 		break;
12340 	case CHELSIO_T4_GET_MEM:
12341 		rc = read_card_mem(sc, 2, (struct t4_mem_range *)data);
12342 		break;
12343 	case CHELSIO_T4_GET_I2C:
12344 		rc = read_i2c(sc, (struct t4_i2c_data *)data);
12345 		break;
12346 	case CHELSIO_T4_CLEAR_STATS:
12347 		rc = clear_stats(sc, *(uint32_t *)data);
12348 		break;
12349 	case CHELSIO_T4_SCHED_CLASS:
12350 		rc = t4_set_sched_class(sc, (struct t4_sched_params *)data);
12351 		break;
12352 	case CHELSIO_T4_SCHED_QUEUE:
12353 		rc = t4_set_sched_queue(sc, (struct t4_sched_queue *)data);
12354 		break;
12355 	case CHELSIO_T4_GET_TRACER:
12356 		rc = t4_get_tracer(sc, (struct t4_tracer *)data);
12357 		break;
12358 	case CHELSIO_T4_SET_TRACER:
12359 		rc = t4_set_tracer(sc, (struct t4_tracer *)data);
12360 		break;
12361 	case CHELSIO_T4_LOAD_CFG:
12362 		rc = load_cfg(sc, (struct t4_data *)data);
12363 		break;
12364 	case CHELSIO_T4_LOAD_BOOT:
12365 		rc = load_boot(sc, (struct t4_bootrom *)data);
12366 		break;
12367 	case CHELSIO_T4_LOAD_BOOTCFG:
12368 		rc = load_bootcfg(sc, (struct t4_data *)data);
12369 		break;
12370 	case CHELSIO_T4_CUDBG_DUMP:
12371 		rc = cudbg_dump(sc, (struct t4_cudbg_dump *)data);
12372 		break;
12373 	case CHELSIO_T4_SET_OFLD_POLICY:
12374 		rc = set_offload_policy(sc, (struct t4_offload_policy *)data);
12375 		break;
12376 	case CHELSIO_T4_HOLD_CLIP_ADDR:
12377 		rc = hold_clip_addr(sc, (struct t4_clip_addr *)data);
12378 		break;
12379 	case CHELSIO_T4_RELEASE_CLIP_ADDR:
12380 		rc = release_clip_addr(sc, (struct t4_clip_addr *)data);
12381 		break;
12382 	default:
12383 		rc = ENOTTY;
12384 	}
12385 
12386 	return (rc);
12387 }
12388 
12389 #ifdef TCP_OFFLOAD
12390 static int
12391 toe_capability(struct vi_info *vi, bool enable)
12392 {
12393 	int rc;
12394 	struct port_info *pi = vi->pi;
12395 	struct adapter *sc = pi->adapter;
12396 
12397 	ASSERT_SYNCHRONIZED_OP(sc);
12398 
12399 	if (!is_offload(sc))
12400 		return (ENODEV);
12401 	if (hw_off_limits(sc))
12402 		return (ENXIO);
12403 
12404 	if (enable) {
12405 #ifdef KERN_TLS
12406 		if (sc->flags & KERN_TLS_ON && is_t6(sc)) {
12407 			int i, j, n;
12408 			struct port_info *p;
12409 			struct vi_info *v;
12410 
12411 			/*
12412 			 * Reconfigure hardware for TOE if TXTLS is not enabled
12413 			 * on any ifnet.
12414 			 */
12415 			n = 0;
12416 			for_each_port(sc, i) {
12417 				p = sc->port[i];
12418 				for_each_vi(p, j, v) {
12419 					if (if_getcapenable(v->ifp) & IFCAP_TXTLS) {
12420 						CH_WARN(sc,
12421 						    "%s has NIC TLS enabled.\n",
12422 						    device_get_nameunit(v->dev));
12423 						n++;
12424 					}
12425 				}
12426 			}
12427 			if (n > 0) {
12428 				CH_WARN(sc, "Disable NIC TLS on all interfaces "
12429 				    "associated with this adapter before "
12430 				    "trying to enable TOE.\n");
12431 				return (EAGAIN);
12432 			}
12433 			rc = t6_config_kern_tls(sc, false);
12434 			if (rc)
12435 				return (rc);
12436 		}
12437 #endif
12438 		if ((if_getcapenable(vi->ifp) & IFCAP_TOE) != 0) {
12439 			/* TOE is already enabled. */
12440 			return (0);
12441 		}
12442 
12443 		/*
12444 		 * We need the port's queues around so that we're able to send
12445 		 * and receive CPLs to/from the TOE even if the ifnet for this
12446 		 * port has never been UP'd administratively.
12447 		 */
12448 		if (!(vi->flags & VI_INIT_DONE) && ((rc = vi_init(vi)) != 0))
12449 			return (rc);
12450 		if (!(pi->vi[0].flags & VI_INIT_DONE) &&
12451 		    ((rc = vi_init(&pi->vi[0])) != 0))
12452 			return (rc);
12453 
12454 		if (isset(&sc->offload_map, pi->port_id)) {
12455 			/* TOE is enabled on another VI of this port. */
12456 			pi->uld_vis++;
12457 			return (0);
12458 		}
12459 
12460 		if (!uld_active(sc, ULD_TOM)) {
12461 			rc = t4_activate_uld(sc, ULD_TOM);
12462 			if (rc == EAGAIN) {
12463 				log(LOG_WARNING,
12464 				    "You must kldload t4_tom.ko before trying "
12465 				    "to enable TOE on a cxgbe interface.\n");
12466 			}
12467 			if (rc != 0)
12468 				return (rc);
12469 			KASSERT(sc->tom_softc != NULL,
12470 			    ("%s: TOM activated but softc NULL", __func__));
12471 			KASSERT(uld_active(sc, ULD_TOM),
12472 			    ("%s: TOM activated but flag not set", __func__));
12473 		}
12474 
12475 		/* Activate iWARP and iSCSI too, if the modules are loaded. */
12476 		if (!uld_active(sc, ULD_IWARP))
12477 			(void) t4_activate_uld(sc, ULD_IWARP);
12478 		if (!uld_active(sc, ULD_ISCSI))
12479 			(void) t4_activate_uld(sc, ULD_ISCSI);
12480 
12481 		pi->uld_vis++;
12482 		setbit(&sc->offload_map, pi->port_id);
12483 	} else {
12484 		pi->uld_vis--;
12485 
12486 		if (!isset(&sc->offload_map, pi->port_id) || pi->uld_vis > 0)
12487 			return (0);
12488 
12489 		KASSERT(uld_active(sc, ULD_TOM),
12490 		    ("%s: TOM never initialized?", __func__));
12491 		clrbit(&sc->offload_map, pi->port_id);
12492 	}
12493 
12494 	return (0);
12495 }
12496 
12497 /*
12498  * Add an upper layer driver to the global list.
12499  */
12500 int
12501 t4_register_uld(struct uld_info *ui)
12502 {
12503 	int rc = 0;
12504 	struct uld_info *u;
12505 
12506 	sx_xlock(&t4_uld_list_lock);
12507 	SLIST_FOREACH(u, &t4_uld_list, link) {
12508 	    if (u->uld_id == ui->uld_id) {
12509 		    rc = EEXIST;
12510 		    goto done;
12511 	    }
12512 	}
12513 
12514 	SLIST_INSERT_HEAD(&t4_uld_list, ui, link);
12515 	ui->refcount = 0;
12516 done:
12517 	sx_xunlock(&t4_uld_list_lock);
12518 	return (rc);
12519 }
12520 
12521 int
12522 t4_unregister_uld(struct uld_info *ui)
12523 {
12524 	int rc = EINVAL;
12525 	struct uld_info *u;
12526 
12527 	sx_xlock(&t4_uld_list_lock);
12528 
12529 	SLIST_FOREACH(u, &t4_uld_list, link) {
12530 	    if (u == ui) {
12531 		    if (ui->refcount > 0) {
12532 			    rc = EBUSY;
12533 			    goto done;
12534 		    }
12535 
12536 		    SLIST_REMOVE(&t4_uld_list, ui, uld_info, link);
12537 		    rc = 0;
12538 		    goto done;
12539 	    }
12540 	}
12541 done:
12542 	sx_xunlock(&t4_uld_list_lock);
12543 	return (rc);
12544 }
12545 
12546 int
12547 t4_activate_uld(struct adapter *sc, int id)
12548 {
12549 	int rc;
12550 	struct uld_info *ui;
12551 
12552 	ASSERT_SYNCHRONIZED_OP(sc);
12553 
12554 	if (id < 0 || id > ULD_MAX)
12555 		return (EINVAL);
12556 	rc = EAGAIN;	/* kldoad the module with this ULD and try again. */
12557 
12558 	sx_slock(&t4_uld_list_lock);
12559 
12560 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12561 		if (ui->uld_id == id) {
12562 			if (!(sc->flags & FULL_INIT_DONE)) {
12563 				rc = adapter_init(sc);
12564 				if (rc != 0)
12565 					break;
12566 			}
12567 
12568 			rc = ui->activate(sc);
12569 			if (rc == 0) {
12570 				setbit(&sc->active_ulds, id);
12571 				ui->refcount++;
12572 			}
12573 			break;
12574 		}
12575 	}
12576 
12577 	sx_sunlock(&t4_uld_list_lock);
12578 
12579 	return (rc);
12580 }
12581 
12582 int
12583 t4_deactivate_uld(struct adapter *sc, int id)
12584 {
12585 	int rc;
12586 	struct uld_info *ui;
12587 
12588 	ASSERT_SYNCHRONIZED_OP(sc);
12589 
12590 	if (id < 0 || id > ULD_MAX)
12591 		return (EINVAL);
12592 	rc = ENXIO;
12593 
12594 	sx_slock(&t4_uld_list_lock);
12595 
12596 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12597 		if (ui->uld_id == id) {
12598 			rc = ui->deactivate(sc);
12599 			if (rc == 0) {
12600 				clrbit(&sc->active_ulds, id);
12601 				ui->refcount--;
12602 			}
12603 			break;
12604 		}
12605 	}
12606 
12607 	sx_sunlock(&t4_uld_list_lock);
12608 
12609 	return (rc);
12610 }
12611 
12612 static int
12613 t4_deactivate_all_uld(struct adapter *sc)
12614 {
12615 	int rc;
12616 	struct uld_info *ui;
12617 
12618 	rc = begin_synchronized_op(sc, NULL, SLEEP_OK, "t4detuld");
12619 	if (rc != 0)
12620 		return (ENXIO);
12621 
12622 	sx_slock(&t4_uld_list_lock);
12623 
12624 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12625 		if (isset(&sc->active_ulds, ui->uld_id)) {
12626 			rc = ui->deactivate(sc);
12627 			if (rc != 0)
12628 				break;
12629 			clrbit(&sc->active_ulds, ui->uld_id);
12630 			ui->refcount--;
12631 		}
12632 	}
12633 
12634 	sx_sunlock(&t4_uld_list_lock);
12635 	end_synchronized_op(sc, 0);
12636 
12637 	return (rc);
12638 }
12639 
12640 static void
12641 t4_async_event(struct adapter *sc)
12642 {
12643 	struct uld_info *ui;
12644 
12645 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4async") != 0)
12646 		return;
12647 	sx_slock(&t4_uld_list_lock);
12648 	SLIST_FOREACH(ui, &t4_uld_list, link) {
12649 		if (ui->uld_id == ULD_IWARP) {
12650 			ui->async_event(sc);
12651 			break;
12652 		}
12653 	}
12654 	sx_sunlock(&t4_uld_list_lock);
12655 	end_synchronized_op(sc, 0);
12656 }
12657 
12658 int
12659 uld_active(struct adapter *sc, int uld_id)
12660 {
12661 
12662 	MPASS(uld_id >= 0 && uld_id <= ULD_MAX);
12663 
12664 	return (isset(&sc->active_ulds, uld_id));
12665 }
12666 #endif
12667 
12668 #ifdef KERN_TLS
12669 static int
12670 ktls_capability(struct adapter *sc, bool enable)
12671 {
12672 	ASSERT_SYNCHRONIZED_OP(sc);
12673 
12674 	if (!is_ktls(sc))
12675 		return (ENODEV);
12676 	if (!is_t6(sc))
12677 		return (0);
12678 	if (hw_off_limits(sc))
12679 		return (ENXIO);
12680 
12681 	if (enable) {
12682 		if (sc->flags & KERN_TLS_ON)
12683 			return (0);	/* already on */
12684 		if (sc->offload_map != 0) {
12685 			CH_WARN(sc,
12686 			    "Disable TOE on all interfaces associated with "
12687 			    "this adapter before trying to enable NIC TLS.\n");
12688 			return (EAGAIN);
12689 		}
12690 		return (t6_config_kern_tls(sc, true));
12691 	} else {
12692 		/*
12693 		 * Nothing to do for disable.  If TOE is enabled sometime later
12694 		 * then toe_capability will reconfigure the hardware.
12695 		 */
12696 		return (0);
12697 	}
12698 }
12699 #endif
12700 
12701 /*
12702  * t  = ptr to tunable.
12703  * nc = number of CPUs.
12704  * c  = compiled in default for that tunable.
12705  */
12706 static void
12707 calculate_nqueues(int *t, int nc, const int c)
12708 {
12709 	int nq;
12710 
12711 	if (*t > 0)
12712 		return;
12713 	nq = *t < 0 ? -*t : c;
12714 	*t = min(nc, nq);
12715 }
12716 
12717 /*
12718  * Come up with reasonable defaults for some of the tunables, provided they're
12719  * not set by the user (in which case we'll use the values as is).
12720  */
12721 static void
12722 tweak_tunables(void)
12723 {
12724 	int nc = mp_ncpus;	/* our snapshot of the number of CPUs */
12725 
12726 	if (t4_ntxq < 1) {
12727 #ifdef RSS
12728 		t4_ntxq = rss_getnumbuckets();
12729 #else
12730 		calculate_nqueues(&t4_ntxq, nc, NTXQ);
12731 #endif
12732 	}
12733 
12734 	calculate_nqueues(&t4_ntxq_vi, nc, NTXQ_VI);
12735 
12736 	if (t4_nrxq < 1) {
12737 #ifdef RSS
12738 		t4_nrxq = rss_getnumbuckets();
12739 #else
12740 		calculate_nqueues(&t4_nrxq, nc, NRXQ);
12741 #endif
12742 	}
12743 
12744 	calculate_nqueues(&t4_nrxq_vi, nc, NRXQ_VI);
12745 
12746 #if defined(TCP_OFFLOAD) || defined(RATELIMIT)
12747 	calculate_nqueues(&t4_nofldtxq, nc, NOFLDTXQ);
12748 	calculate_nqueues(&t4_nofldtxq_vi, nc, NOFLDTXQ_VI);
12749 #endif
12750 #ifdef TCP_OFFLOAD
12751 	calculate_nqueues(&t4_nofldrxq, nc, NOFLDRXQ);
12752 	calculate_nqueues(&t4_nofldrxq_vi, nc, NOFLDRXQ_VI);
12753 #endif
12754 
12755 #if defined(TCP_OFFLOAD) || defined(KERN_TLS)
12756 	if (t4_toecaps_allowed == -1)
12757 		t4_toecaps_allowed = FW_CAPS_CONFIG_TOE;
12758 #else
12759 	if (t4_toecaps_allowed == -1)
12760 		t4_toecaps_allowed = 0;
12761 #endif
12762 
12763 #ifdef TCP_OFFLOAD
12764 	if (t4_rdmacaps_allowed == -1) {
12765 		t4_rdmacaps_allowed = FW_CAPS_CONFIG_RDMA_RDDP |
12766 		    FW_CAPS_CONFIG_RDMA_RDMAC;
12767 	}
12768 
12769 	if (t4_iscsicaps_allowed == -1) {
12770 		t4_iscsicaps_allowed = FW_CAPS_CONFIG_ISCSI_INITIATOR_PDU |
12771 		    FW_CAPS_CONFIG_ISCSI_TARGET_PDU |
12772 		    FW_CAPS_CONFIG_ISCSI_T10DIF;
12773 	}
12774 
12775 	if (t4_tmr_idx_ofld < 0 || t4_tmr_idx_ofld >= SGE_NTIMERS)
12776 		t4_tmr_idx_ofld = TMR_IDX_OFLD;
12777 
12778 	if (t4_pktc_idx_ofld < -1 || t4_pktc_idx_ofld >= SGE_NCOUNTERS)
12779 		t4_pktc_idx_ofld = PKTC_IDX_OFLD;
12780 #else
12781 	if (t4_rdmacaps_allowed == -1)
12782 		t4_rdmacaps_allowed = 0;
12783 
12784 	if (t4_iscsicaps_allowed == -1)
12785 		t4_iscsicaps_allowed = 0;
12786 #endif
12787 
12788 #ifdef DEV_NETMAP
12789 	calculate_nqueues(&t4_nnmtxq, nc, NNMTXQ);
12790 	calculate_nqueues(&t4_nnmrxq, nc, NNMRXQ);
12791 	calculate_nqueues(&t4_nnmtxq_vi, nc, NNMTXQ_VI);
12792 	calculate_nqueues(&t4_nnmrxq_vi, nc, NNMRXQ_VI);
12793 #endif
12794 
12795 	if (t4_tmr_idx < 0 || t4_tmr_idx >= SGE_NTIMERS)
12796 		t4_tmr_idx = TMR_IDX;
12797 
12798 	if (t4_pktc_idx < -1 || t4_pktc_idx >= SGE_NCOUNTERS)
12799 		t4_pktc_idx = PKTC_IDX;
12800 
12801 	if (t4_qsize_txq < 128)
12802 		t4_qsize_txq = 128;
12803 
12804 	if (t4_qsize_rxq < 128)
12805 		t4_qsize_rxq = 128;
12806 	while (t4_qsize_rxq & 7)
12807 		t4_qsize_rxq++;
12808 
12809 	t4_intr_types &= INTR_MSIX | INTR_MSI | INTR_INTX;
12810 
12811 	/*
12812 	 * Number of VIs to create per-port.  The first VI is the "main" regular
12813 	 * VI for the port.  The rest are additional virtual interfaces on the
12814 	 * same physical port.  Note that the main VI does not have native
12815 	 * netmap support but the extra VIs do.
12816 	 *
12817 	 * Limit the number of VIs per port to the number of available
12818 	 * MAC addresses per port.
12819 	 */
12820 	if (t4_num_vis < 1)
12821 		t4_num_vis = 1;
12822 	if (t4_num_vis > nitems(vi_mac_funcs)) {
12823 		t4_num_vis = nitems(vi_mac_funcs);
12824 		printf("cxgbe: number of VIs limited to %d\n", t4_num_vis);
12825 	}
12826 
12827 	if (pcie_relaxed_ordering < 0 || pcie_relaxed_ordering > 2) {
12828 		pcie_relaxed_ordering = 1;
12829 #if defined(__i386__) || defined(__amd64__)
12830 		if (cpu_vendor_id == CPU_VENDOR_INTEL)
12831 			pcie_relaxed_ordering = 0;
12832 #endif
12833 	}
12834 }
12835 
12836 #ifdef DDB
12837 static void
12838 t4_dump_tcb(struct adapter *sc, int tid)
12839 {
12840 	uint32_t base, i, j, off, pf, reg, save, tcb_addr, win_pos;
12841 
12842 	reg = PCIE_MEM_ACCESS_REG(A_PCIE_MEM_ACCESS_OFFSET, 2);
12843 	save = t4_read_reg(sc, reg);
12844 	base = sc->memwin[2].mw_base;
12845 
12846 	/* Dump TCB for the tid */
12847 	tcb_addr = t4_read_reg(sc, A_TP_CMM_TCB_BASE);
12848 	tcb_addr += tid * TCB_SIZE;
12849 
12850 	if (is_t4(sc)) {
12851 		pf = 0;
12852 		win_pos = tcb_addr & ~0xf;	/* start must be 16B aligned */
12853 	} else {
12854 		pf = V_PFNUM(sc->pf);
12855 		win_pos = tcb_addr & ~0x7f;	/* start must be 128B aligned */
12856 	}
12857 	t4_write_reg(sc, reg, win_pos | pf);
12858 	t4_read_reg(sc, reg);
12859 
12860 	off = tcb_addr - win_pos;
12861 	for (i = 0; i < 4; i++) {
12862 		uint32_t buf[8];
12863 		for (j = 0; j < 8; j++, off += 4)
12864 			buf[j] = htonl(t4_read_reg(sc, base + off));
12865 
12866 		db_printf("%08x %08x %08x %08x %08x %08x %08x %08x\n",
12867 		    buf[0], buf[1], buf[2], buf[3], buf[4], buf[5], buf[6],
12868 		    buf[7]);
12869 	}
12870 
12871 	t4_write_reg(sc, reg, save);
12872 	t4_read_reg(sc, reg);
12873 }
12874 
12875 static void
12876 t4_dump_devlog(struct adapter *sc)
12877 {
12878 	struct devlog_params *dparams = &sc->params.devlog;
12879 	struct fw_devlog_e e;
12880 	int i, first, j, m, nentries, rc;
12881 	uint64_t ftstamp = UINT64_MAX;
12882 
12883 	if (dparams->start == 0) {
12884 		db_printf("devlog params not valid\n");
12885 		return;
12886 	}
12887 
12888 	nentries = dparams->size / sizeof(struct fw_devlog_e);
12889 	m = fwmtype_to_hwmtype(dparams->memtype);
12890 
12891 	/* Find the first entry. */
12892 	first = -1;
12893 	for (i = 0; i < nentries && !db_pager_quit; i++) {
12894 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12895 		    sizeof(e), (void *)&e);
12896 		if (rc != 0)
12897 			break;
12898 
12899 		if (e.timestamp == 0)
12900 			break;
12901 
12902 		e.timestamp = be64toh(e.timestamp);
12903 		if (e.timestamp < ftstamp) {
12904 			ftstamp = e.timestamp;
12905 			first = i;
12906 		}
12907 	}
12908 
12909 	if (first == -1)
12910 		return;
12911 
12912 	i = first;
12913 	do {
12914 		rc = -t4_mem_read(sc, m, dparams->start + i * sizeof(e),
12915 		    sizeof(e), (void *)&e);
12916 		if (rc != 0)
12917 			return;
12918 
12919 		if (e.timestamp == 0)
12920 			return;
12921 
12922 		e.timestamp = be64toh(e.timestamp);
12923 		e.seqno = be32toh(e.seqno);
12924 		for (j = 0; j < 8; j++)
12925 			e.params[j] = be32toh(e.params[j]);
12926 
12927 		db_printf("%10d  %15ju  %8s  %8s  ",
12928 		    e.seqno, e.timestamp,
12929 		    (e.level < nitems(devlog_level_strings) ?
12930 			devlog_level_strings[e.level] : "UNKNOWN"),
12931 		    (e.facility < nitems(devlog_facility_strings) ?
12932 			devlog_facility_strings[e.facility] : "UNKNOWN"));
12933 		db_printf(e.fmt, e.params[0], e.params[1], e.params[2],
12934 		    e.params[3], e.params[4], e.params[5], e.params[6],
12935 		    e.params[7]);
12936 
12937 		if (++i == nentries)
12938 			i = 0;
12939 	} while (i != first && !db_pager_quit);
12940 }
12941 
12942 static DB_DEFINE_TABLE(show, t4, show_t4);
12943 
12944 DB_TABLE_COMMAND_FLAGS(show_t4, devlog, db_show_devlog, CS_OWN)
12945 {
12946 	device_t dev;
12947 	int t;
12948 	bool valid;
12949 
12950 	valid = false;
12951 	t = db_read_token();
12952 	if (t == tIDENT) {
12953 		dev = device_lookup_by_name(db_tok_string);
12954 		valid = true;
12955 	}
12956 	db_skip_to_eol();
12957 	if (!valid) {
12958 		db_printf("usage: show t4 devlog <nexus>\n");
12959 		return;
12960 	}
12961 
12962 	if (dev == NULL) {
12963 		db_printf("device not found\n");
12964 		return;
12965 	}
12966 
12967 	t4_dump_devlog(device_get_softc(dev));
12968 }
12969 
12970 DB_TABLE_COMMAND_FLAGS(show_t4, tcb, db_show_t4tcb, CS_OWN)
12971 {
12972 	device_t dev;
12973 	int radix, tid, t;
12974 	bool valid;
12975 
12976 	valid = false;
12977 	radix = db_radix;
12978 	db_radix = 10;
12979 	t = db_read_token();
12980 	if (t == tIDENT) {
12981 		dev = device_lookup_by_name(db_tok_string);
12982 		t = db_read_token();
12983 		if (t == tNUMBER) {
12984 			tid = db_tok_number;
12985 			valid = true;
12986 		}
12987 	}
12988 	db_radix = radix;
12989 	db_skip_to_eol();
12990 	if (!valid) {
12991 		db_printf("usage: show t4 tcb <nexus> <tid>\n");
12992 		return;
12993 	}
12994 
12995 	if (dev == NULL) {
12996 		db_printf("device not found\n");
12997 		return;
12998 	}
12999 	if (tid < 0) {
13000 		db_printf("invalid tid\n");
13001 		return;
13002 	}
13003 
13004 	t4_dump_tcb(device_get_softc(dev), tid);
13005 }
13006 #endif
13007 
13008 static eventhandler_tag vxlan_start_evtag;
13009 static eventhandler_tag vxlan_stop_evtag;
13010 
13011 struct vxlan_evargs {
13012 	if_t ifp;
13013 	uint16_t port;
13014 };
13015 
13016 static void
13017 enable_vxlan_rx(struct adapter *sc)
13018 {
13019 	int i, rc;
13020 	struct port_info *pi;
13021 	uint8_t match_all_mac[ETHER_ADDR_LEN] = {0};
13022 
13023 	ASSERT_SYNCHRONIZED_OP(sc);
13024 
13025 	t4_write_reg(sc, A_MPS_RX_VXLAN_TYPE, V_VXLAN(sc->vxlan_port) |
13026 	    F_VXLAN_EN);
13027 	for_each_port(sc, i) {
13028 		pi = sc->port[i];
13029 		if (pi->vxlan_tcam_entry == true)
13030 			continue;
13031 		rc = t4_alloc_raw_mac_filt(sc, pi->vi[0].viid, match_all_mac,
13032 		    match_all_mac, sc->rawf_base + pi->port_id, 1, pi->port_id,
13033 		    true);
13034 		if (rc < 0) {
13035 			rc = -rc;
13036 			CH_ERR(&pi->vi[0],
13037 			    "failed to add VXLAN TCAM entry: %d.\n", rc);
13038 		} else {
13039 			MPASS(rc == sc->rawf_base + pi->port_id);
13040 			pi->vxlan_tcam_entry = true;
13041 		}
13042 	}
13043 }
13044 
13045 static void
13046 t4_vxlan_start(struct adapter *sc, void *arg)
13047 {
13048 	struct vxlan_evargs *v = arg;
13049 
13050 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13051 		return;
13052 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxst") != 0)
13053 		return;
13054 
13055 	if (sc->vxlan_refcount == 0) {
13056 		sc->vxlan_port = v->port;
13057 		sc->vxlan_refcount = 1;
13058 		if (!hw_off_limits(sc))
13059 			enable_vxlan_rx(sc);
13060 	} else if (sc->vxlan_port == v->port) {
13061 		sc->vxlan_refcount++;
13062 	} else {
13063 		CH_ERR(sc, "VXLAN already configured on port  %d; "
13064 		    "ignoring attempt to configure it on port %d\n",
13065 		    sc->vxlan_port, v->port);
13066 	}
13067 	end_synchronized_op(sc, 0);
13068 }
13069 
13070 static void
13071 t4_vxlan_stop(struct adapter *sc, void *arg)
13072 {
13073 	struct vxlan_evargs *v = arg;
13074 
13075 	if (sc->nrawf == 0 || chip_id(sc) <= CHELSIO_T5)
13076 		return;
13077 	if (begin_synchronized_op(sc, NULL, SLEEP_OK | INTR_OK, "t4vxsp") != 0)
13078 		return;
13079 
13080 	/*
13081 	 * VXLANs may have been configured before the driver was loaded so we
13082 	 * may see more stops than starts.  This is not handled cleanly but at
13083 	 * least we keep the refcount sane.
13084 	 */
13085 	if (sc->vxlan_port != v->port)
13086 		goto done;
13087 	if (sc->vxlan_refcount == 0) {
13088 		CH_ERR(sc, "VXLAN operation on port %d was stopped earlier; "
13089 		    "ignoring attempt to stop it again.\n", sc->vxlan_port);
13090 	} else if (--sc->vxlan_refcount == 0 && !hw_off_limits(sc))
13091 		t4_set_reg_field(sc, A_MPS_RX_VXLAN_TYPE, F_VXLAN_EN, 0);
13092 done:
13093 	end_synchronized_op(sc, 0);
13094 }
13095 
13096 static void
13097 t4_vxlan_start_handler(void *arg __unused, if_t ifp,
13098     sa_family_t family, u_int port)
13099 {
13100 	struct vxlan_evargs v;
13101 
13102 	MPASS(family == AF_INET || family == AF_INET6);
13103 	v.ifp = ifp;
13104 	v.port = port;
13105 
13106 	t4_iterate(t4_vxlan_start, &v);
13107 }
13108 
13109 static void
13110 t4_vxlan_stop_handler(void *arg __unused, if_t ifp, sa_family_t family,
13111     u_int port)
13112 {
13113 	struct vxlan_evargs v;
13114 
13115 	MPASS(family == AF_INET || family == AF_INET6);
13116 	v.ifp = ifp;
13117 	v.port = port;
13118 
13119 	t4_iterate(t4_vxlan_stop, &v);
13120 }
13121 
13122 
13123 static struct sx mlu;	/* mod load unload */
13124 SX_SYSINIT(cxgbe_mlu, &mlu, "cxgbe mod load/unload");
13125 
13126 static int
13127 mod_event(module_t mod, int cmd, void *arg)
13128 {
13129 	int rc = 0;
13130 	static int loaded = 0;
13131 
13132 	switch (cmd) {
13133 	case MOD_LOAD:
13134 		sx_xlock(&mlu);
13135 		if (loaded++ == 0) {
13136 			t4_sge_modload();
13137 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13138 			    t4_filter_rpl, CPL_COOKIE_FILTER);
13139 			t4_register_shared_cpl_handler(CPL_L2T_WRITE_RPL,
13140 			    do_l2t_write_rpl, CPL_COOKIE_FILTER);
13141 			t4_register_shared_cpl_handler(CPL_ACT_OPEN_RPL,
13142 			    t4_hashfilter_ao_rpl, CPL_COOKIE_HASHFILTER);
13143 			t4_register_shared_cpl_handler(CPL_SET_TCB_RPL,
13144 			    t4_hashfilter_tcb_rpl, CPL_COOKIE_HASHFILTER);
13145 			t4_register_shared_cpl_handler(CPL_ABORT_RPL_RSS,
13146 			    t4_del_hashfilter_rpl, CPL_COOKIE_HASHFILTER);
13147 			t4_register_cpl_handler(CPL_TRACE_PKT, t4_trace_pkt);
13148 			t4_register_cpl_handler(CPL_T5_TRACE_PKT, t5_trace_pkt);
13149 			t4_register_cpl_handler(CPL_SMT_WRITE_RPL,
13150 			    do_smt_write_rpl);
13151 			sx_init(&t4_list_lock, "T4/T5 adapters");
13152 			SLIST_INIT(&t4_list);
13153 			callout_init(&fatal_callout, 1);
13154 #ifdef TCP_OFFLOAD
13155 			sx_init(&t4_uld_list_lock, "T4/T5 ULDs");
13156 			SLIST_INIT(&t4_uld_list);
13157 #endif
13158 #ifdef INET6
13159 			t4_clip_modload();
13160 #endif
13161 #ifdef KERN_TLS
13162 			t6_ktls_modload();
13163 #endif
13164 			t4_tracer_modload();
13165 			tweak_tunables();
13166 			vxlan_start_evtag =
13167 			    EVENTHANDLER_REGISTER(vxlan_start,
13168 				t4_vxlan_start_handler, NULL,
13169 				EVENTHANDLER_PRI_ANY);
13170 			vxlan_stop_evtag =
13171 			    EVENTHANDLER_REGISTER(vxlan_stop,
13172 				t4_vxlan_stop_handler, NULL,
13173 				EVENTHANDLER_PRI_ANY);
13174 			reset_tq = taskqueue_create("t4_rst_tq", M_WAITOK,
13175 			    taskqueue_thread_enqueue, &reset_tq);
13176 			taskqueue_start_threads(&reset_tq, 1, PI_SOFT,
13177 			    "t4_rst_thr");
13178 		}
13179 		sx_xunlock(&mlu);
13180 		break;
13181 
13182 	case MOD_UNLOAD:
13183 		sx_xlock(&mlu);
13184 		if (--loaded == 0) {
13185 			int tries;
13186 
13187 			taskqueue_free(reset_tq);
13188 			sx_slock(&t4_list_lock);
13189 			if (!SLIST_EMPTY(&t4_list)) {
13190 				rc = EBUSY;
13191 				sx_sunlock(&t4_list_lock);
13192 				goto done_unload;
13193 			}
13194 #ifdef TCP_OFFLOAD
13195 			sx_slock(&t4_uld_list_lock);
13196 			if (!SLIST_EMPTY(&t4_uld_list)) {
13197 				rc = EBUSY;
13198 				sx_sunlock(&t4_uld_list_lock);
13199 				sx_sunlock(&t4_list_lock);
13200 				goto done_unload;
13201 			}
13202 #endif
13203 			tries = 0;
13204 			while (tries++ < 5 && t4_sge_extfree_refs() != 0) {
13205 				uprintf("%ju clusters with custom free routine "
13206 				    "still is use.\n", t4_sge_extfree_refs());
13207 				pause("t4unload", 2 * hz);
13208 			}
13209 #ifdef TCP_OFFLOAD
13210 			sx_sunlock(&t4_uld_list_lock);
13211 #endif
13212 			sx_sunlock(&t4_list_lock);
13213 
13214 			if (t4_sge_extfree_refs() == 0) {
13215 				EVENTHANDLER_DEREGISTER(vxlan_start,
13216 				    vxlan_start_evtag);
13217 				EVENTHANDLER_DEREGISTER(vxlan_stop,
13218 				    vxlan_stop_evtag);
13219 				t4_tracer_modunload();
13220 #ifdef KERN_TLS
13221 				t6_ktls_modunload();
13222 #endif
13223 #ifdef INET6
13224 				t4_clip_modunload();
13225 #endif
13226 #ifdef TCP_OFFLOAD
13227 				sx_destroy(&t4_uld_list_lock);
13228 #endif
13229 				sx_destroy(&t4_list_lock);
13230 				t4_sge_modunload();
13231 				loaded = 0;
13232 			} else {
13233 				rc = EBUSY;
13234 				loaded++;	/* undo earlier decrement */
13235 			}
13236 		}
13237 done_unload:
13238 		sx_xunlock(&mlu);
13239 		break;
13240 	}
13241 
13242 	return (rc);
13243 }
13244 
13245 DRIVER_MODULE(t4nex, pci, t4_driver, mod_event, 0);
13246 MODULE_VERSION(t4nex, 1);
13247 MODULE_DEPEND(t4nex, firmware, 1, 1, 1);
13248 #ifdef DEV_NETMAP
13249 MODULE_DEPEND(t4nex, netmap, 1, 1, 1);
13250 #endif /* DEV_NETMAP */
13251 
13252 DRIVER_MODULE(t5nex, pci, t5_driver, mod_event, 0);
13253 MODULE_VERSION(t5nex, 1);
13254 MODULE_DEPEND(t5nex, firmware, 1, 1, 1);
13255 #ifdef DEV_NETMAP
13256 MODULE_DEPEND(t5nex, netmap, 1, 1, 1);
13257 #endif /* DEV_NETMAP */
13258 
13259 DRIVER_MODULE(t6nex, pci, t6_driver, mod_event, 0);
13260 MODULE_VERSION(t6nex, 1);
13261 MODULE_DEPEND(t6nex, crypto, 1, 1, 1);
13262 MODULE_DEPEND(t6nex, firmware, 1, 1, 1);
13263 #ifdef DEV_NETMAP
13264 MODULE_DEPEND(t6nex, netmap, 1, 1, 1);
13265 #endif /* DEV_NETMAP */
13266 
13267 DRIVER_MODULE(cxgbe, t4nex, cxgbe_driver, 0, 0);
13268 MODULE_VERSION(cxgbe, 1);
13269 
13270 DRIVER_MODULE(cxl, t5nex, cxl_driver, 0, 0);
13271 MODULE_VERSION(cxl, 1);
13272 
13273 DRIVER_MODULE(cc, t6nex, cc_driver, 0, 0);
13274 MODULE_VERSION(cc, 1);
13275 
13276 DRIVER_MODULE(vcxgbe, cxgbe, vcxgbe_driver, 0, 0);
13277 MODULE_VERSION(vcxgbe, 1);
13278 
13279 DRIVER_MODULE(vcxl, cxl, vcxl_driver, 0, 0);
13280 MODULE_VERSION(vcxl, 1);
13281 
13282 DRIVER_MODULE(vcc, cc, vcc_driver, 0, 0);
13283 MODULE_VERSION(vcc, 1);
13284